content
stringlengths 5
1.05M
|
|---|
local cfg = {}
|
--------------------------------------------------------------------------------
--- Generated exports map for lua-nucleo/
-- @module lua-nucleo.code.exports
-- This file is a part of lua-nucleo library
-- See file `COPYRIGHT` for the license and copyright information
--------------------------------------------------------------------------------
-- WARNING! Do not change manually!
-- Generated by list-exports.
--------------------------------------------------------------------------------
return
{
END_OF_LOG_MESSAGE =
{
{ "lua-nucleo/log.lua", w = 0 };
};
EPSILON =
{
{ "lua-nucleo/math.lua", w = 0 };
};
FLUSH_SECONDS_DEFAULT =
{
{ "lua-nucleo/log.lua", w = 0 };
};
LOG_FLUSH_MODE =
{
{ "lua-nucleo/log.lua", w = 0 };
};
LOG_LEVEL =
{
{ "lua-nucleo/log.lua", w = 0 };
};
amap =
{
{ "lua-nucleo/args.lua", w = 0 };
};
args_proxy =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
arguments =
{
{ "lua-nucleo/args.lua", w = 0 };
};
arguments_ignorer =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
assert_is_boolean =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_function =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_nil =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_number =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_self =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_string =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_table =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_thread =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_type =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_is_userdata =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
assert_not_nil =
{
{ "lua-nucleo/typeassert.lua", w = 0 };
};
bind_many =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
capture_source_location =
{
{ "lua-nucleo/diagnostics.lua", w = 0 };
};
cdata_cat =
{
{ "lua-nucleo/string.lua", w = 0 };
};
cdata_wrap =
{
{ "lua-nucleo/string.lua", w = 0 };
};
check_decorator =
{
{ "lua-nucleo/testing/decorators.lua", w = 0 };
};
check_types =
{
{ "lua-nucleo/args.lua", w = 0 };
};
collect_all_garbage =
{
{ "lua-nucleo/misc.lua", w = 0 };
};
common_load_schema =
{
{ "lua-nucleo/dsl/common_load_schema.lua", w = 0 };
};
common_method_list =
{
{ "lua-nucleo/factory.lua", w = 0 };
};
compose =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
compose_many =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
count_substrings =
{
{ "lua-nucleo/string.lua", w = 0 };
};
create_common_fields_by_tag =
{
{ "lua-nucleo/dsl/dsl_loader.lua", w = 0 };
};
create_common_name_filter =
{
{ "lua-nucleo/dsl/dsl_loader.lua", w = 0 };
};
create_escape_subst =
{
{ "lua-nucleo/string.lua", w = 0 };
};
create_simple_tagged_tree_walkers =
{
{ "lua-nucleo/dsl/tagged-tree.lua", w = 0 };
};
create_table =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
cut_with_ellipsis =
{
{ "lua-nucleo/string.lua", w = 0 };
};
decoraror_checker_helper =
{
{ "lua-nucleo/testing/decorators.lua", w = 0 };
};
do_in_environment =
{
{ "lua-nucleo/sandbox.lua", w = 0 };
};
do_nothing =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
dostring_in_environment =
{
{ "lua-nucleo/sandbox.lua", w = 0 };
};
dump_nodes =
{
{ "lua-nucleo/dsl/dump_nodes.lua", w = 0 };
};
eat_tag =
{
{ "lua-nucleo/coro.lua", w = 0 };
};
eat_true =
{
{ "lua-nucleo/args.lua", w = 0 };
};
empty_table =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
ends_with =
{
{ "lua-nucleo/string.lua", w = 0 };
};
ensure =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_aposteriori_probability =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_equals =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_error =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_error_with_substring =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_fails_with_substring =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_has_substring =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_is =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_returns =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_strequals =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_tdeepequals =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
ensure_tequals =
{
{ "lua-nucleo/ensure.lua", w = 0 };
};
environment_values =
{
{ "lua-nucleo/testing/decorators.lua", w = 0 };
};
epsilon_equals =
{
{ "lua-nucleo/math.lua", w = 0 };
};
escape_for_json =
{
{ "lua-nucleo/string.lua", w = 0 };
};
escape_lua_pattern =
{
{ "lua-nucleo/string.lua", w = 0 };
};
escape_string =
{
{ "lua-nucleo/string.lua", w = 0 };
};
fill_curly_placeholders =
{
{ "lua-nucleo/string.lua", w = 0 };
};
fill_placeholders =
{
{ "lua-nucleo/string.lua", w = 0 };
};
fill_placeholders_ex =
{
{ "lua-nucleo/string.lua", w = 0 };
};
format_logsystem_date =
{
{ "lua-nucleo/log.lua", w = 0 };
};
get_current_logsystem_date =
{
{ "lua-nucleo/log.lua", w = 0 };
};
get_day_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
get_decasecond_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
get_escaped_chars_in_ranges =
{
{ "lua-nucleo/string.lua", w = 0 };
};
get_minute_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
get_quarter_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
get_tomorrow_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
get_yesterday_timestamp =
{
{ "lua-nucleo/timestamp.lua", w = 0 };
};
htmlspecialchars =
{
{ "lua-nucleo/string.lua", w = 0 };
};
identity =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
integer_to_string_with_base =
{
{ "lua-nucleo/string.lua", w = 0 };
};
invariant =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
is_boolean =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_function =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_nil =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_number =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_outer_yield_tag =
{
{ "lua-nucleo/coro.lua", w = 0 };
};
is_self =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_string =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_table =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_thread =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_type =
{
{ "lua-nucleo/type.lua", w = 0 };
};
is_userdata =
{
{ "lua-nucleo/type.lua", w = 0 };
};
kv_concat =
{
{ "lua-nucleo/string.lua", w = 0 };
};
lassert =
{
{ "lua-nucleo/assert.lua", w = 0 };
};
less_kv =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
less_than =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
list_caller =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
load_data_schema =
{
{ "lua-nucleo/dsl/walk_data_with_schema.lua", w = 0 };
};
load_data_walkers =
{
{ "lua-nucleo/dsl/walk_data_with_schema.lua", w = 0 };
};
looped_linear_interpolator =
{
{ "lua-nucleo/util/anim/interpolator.lua", w = 0 };
};
lower_bound =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
lower_bound_gt =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
lower_bound_pred =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
lua51_keywords =
{
{ "lua-nucleo/language.lua", w = 0 };
};
lua51_types =
{
{ "lua-nucleo/language.lua", w = 0 };
};
make_checker =
{
{ "lua-nucleo/checker.lua", w = 0 };
};
make_common_logging_config =
{
{ "lua-nucleo/log.lua", w = 0 };
};
make_concatter =
{
{ "lua-nucleo/string.lua", w = 0 };
};
make_config_environment =
{
{ "lua-nucleo/sandbox.lua", w = 0 };
};
make_deque =
{
{ "lua-nucleo/deque.lua", w = 0 };
};
make_dsl_loader =
{
{ "lua-nucleo/dsl/dsl_loader.lua", w = 0 };
};
make_generator_mt =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
make_loggers =
{
{ "lua-nucleo/log.lua", w = 0 };
};
make_logging_system =
{
{ "lua-nucleo/log.lua", w = 0 };
};
make_ophash_key_value_store =
{
{ "lua-nucleo/key_value_store/key_value_store_ophash.lua", w = 0 };
};
make_ordered_named_cat_manager =
{
{ "lua-nucleo/ordered_named_cat_manager.lua", w = 0 };
};
make_path_based_walker =
{
{ "lua-nucleo/dsl/path_based_walker.lua", w = 0 };
};
make_prettifier =
{
{ "lua-nucleo/prettifier.lua", w = 0 };
};
make_priority_queue =
{
{ "lua-nucleo/priority_queue.lua", w = 0 };
};
make_scoped_cat_tree_manager =
{
{ "lua-nucleo/scoped_cat_tree_manager.lua", w = 0 };
};
make_simple_key_value_store =
{
{ "lua-nucleo/key_value_store/key_value_store_simple.lua", w = 0 };
};
make_sophisticated_key_value_store =
{
{ "lua-nucleo/key_value_store/key_value_store_sophisticated.lua", w = 0 };
};
make_stack_with_factory =
{
{ "lua-nucleo/stack_with_factory.lua", w = 0 };
};
make_timed_queue =
{
{ "lua-nucleo/timed_queue.lua", w = 0 };
};
method_arguments =
{
{ "lua-nucleo/args.lua", w = 0 };
};
nargs =
{
{ "lua-nucleo/args.lua", w = 0 };
};
nearest_left_interpolator =
{
{ "lua-nucleo/util/anim/interpolator.lua", w = 0 };
};
number_to_string =
{
{ "lua-nucleo/string.lua", w = 0 };
};
optional_arguments =
{
{ "lua-nucleo/args.lua", w = 0 };
};
ordered_pairs =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
pack =
{
{ "lua-nucleo/args.lua", w = 0 };
};
pick_init =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
pick_one =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
quicksort =
{
{ "lua-nucleo/quicksort.lua", w = 0 };
};
remove_nil_arguments =
{
{ "lua-nucleo/functional.lua", w = 0 };
};
require_and_declare =
{
{ "lua-nucleo/require_and_declare.lua", w = 0 };
};
resume_inner =
{
{ "lua-nucleo/coro.lua", w = 0 };
};
serialize_number =
{
{ "lua-nucleo/string.lua", w = 0 };
};
split_by_char =
{
{ "lua-nucleo/string.lua", w = 0 };
};
split_by_offset =
{
{ "lua-nucleo/string.lua", w = 0 };
};
starts_with =
{
{ "lua-nucleo/string.lua", w = 0 };
};
taccumulate =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tappend_many =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tarraylisttohashlist =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tarraytohash =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tclone =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tcount_elements =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tdeepequals =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
tequals =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tfilterkeylist =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tflip =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tflip_inplace =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tgenerate_1d_linear =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tgenerate_2d_linear =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tgenerate_n =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tgetpath =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tidentityset =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tifilter =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tifindvalue_nonrecursive =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiflip =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiinsert_args =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tijoin_many =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tilistofrecordfields =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
timap =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
timap_inplace =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
timap_sliding =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
timapofrecordgroups =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
timapofrecords =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
times_and_values_looped =
{
{ "lua-nucleo/util/anim/interpolator.lua", w = 0 };
};
tipermute_inplace =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tisarray =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tisempty =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiset =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiunique =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tivalues =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiwalk =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tiwalker =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tjson_simple =
{
{ "lua-nucleo/string.lua", w = 0 };
};
tkeys =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tkeysvalues =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tkvlist2kvpairs =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tkvlist_to_hash =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tkvmap_unpack =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tkvtorecordlist =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tless =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
tless_kv =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
tmap_kv =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tmap_values =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tmapofrecordgroups =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tmerge_many =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tmore =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
tnormalize =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tnormalize_inplace =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
torderedset =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
torderedset_insert =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
torderedset_remove =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
toverride_many =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tpretty =
{
{ "lua-nucleo/tpretty.lua", w = 0 };
};
tpretty_ex =
{
{ "lua-nucleo/tpretty.lua", w = 0 };
};
tpretty_ordered =
{
{ "lua-nucleo/tpretty.lua", w = 0 };
};
treadonly =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
treadonly_ex =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tremap_to_array =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
trim =
{
{ "lua-nucleo/string.lua", w = 0 };
};
trunc =
{
{ "lua-nucleo/math.lua", w = 0 };
};
tserialize =
{
{ "lua-nucleo/tserialize.lua", w = 0 };
};
tset =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tset_many =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tsetof =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tsetpath =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tsetpathvalue =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tslice =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
tsort_kv =
{
{ "lua-nucleo/tdeepequals.lua", w = 0 };
};
tstr =
{
{ "lua-nucleo/tstr.lua", w = 0 };
};
tstr_cat =
{
{ "lua-nucleo/tstr.lua", w = 0 };
};
tvalues =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
twalk_pairs =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
twithdefaults =
{
{ "lua-nucleo/table-utils.lua", w = 0 };
};
unique_object =
{
{ "lua-nucleo/misc.lua", w = 0 };
};
upper_bound =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
upper_bound_gt =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
upper_bound_pred =
{
{ "lua-nucleo/algorithm.lua", w = 0 };
};
url_encode =
{
{ "lua-nucleo/string.lua", w = 0 };
};
validate_probability_precise =
{
{ "lua-nucleo/random.lua", w = 0 };
};
validate_probability_rough =
{
{ "lua-nucleo/random.lua", w = 0 };
};
walk_tagged_tree =
{
{ "lua-nucleo/dsl/tagged-tree.lua", w = 0 };
};
wrap_file_sink =
{
{ "lua-nucleo/log.lua", w = 0 };
};
yield_outer =
{
{ "lua-nucleo/coro.lua", w = 0 };
};
}
|
-- protocol naming
p4_paxos = Proto('p4_paxos','P4_PAXOSProtocol')
-- protocol fields
local p4_paxos_msgtype = ProtoField.string('p4_paxos.msgtype','msgtype')
local p4_paxos_instance = ProtoField.string('p4_paxos.instance','instance')
local p4_paxos_round = ProtoField.string('p4_paxos.round','round')
local p4_paxos_vround = ProtoField.string('p4_paxos.vround','vround')
local p4_paxos_acceptor = ProtoField.string('p4_paxos.acceptor','acceptor')
local p4_paxos_value = ProtoField.string('p4_paxos.value','value')
p4_paxos.fields = {p4_paxos_msgtype, p4_paxos_instance, p4_paxos_round, p4_paxos_vround, p4_paxos_acceptor, p4_paxos_value}
-- protocol dissector function
function p4_paxos.dissector(buffer,pinfo,tree)
pinfo.cols.protocol = 'P4_PAXOS'
local subtree = tree:add(p4_paxos,buffer(),'P4_PAXOS Protocol Data')
subtree:add(p4_paxos_msgtype,tostring(buffer(0,1):bitfield(0,8)))
subtree:add(p4_paxos_instance,tostring(buffer(1,2):bitfield(0,16)))
subtree:add(p4_paxos_round,tostring(buffer(3,1):bitfield(0,8)))
subtree:add(p4_paxos_vround,tostring(buffer(4,1):bitfield(0,8)))
subtree:add(p4_paxos_acceptor,tostring(buffer(5,8):bitfield(0,64)))
subtree:add(p4_paxos_value,tostring(buffer(13,64):bitfield(0,512)))
end
print( (require 'debug').getinfo(1).source )
-- creation of table for next layer(if required)
-- No table required
-- protocol registration
my_table = DissectorTable.get('p4_udp.dstPort')
my_table:add(0x8888,p4_paxos)
|
require 'luacov'
local tuple = require 'tuple'
context('Creating tuples', function()
test('Instantiates new tuples with () call', function()
local a = tuple(1,2)
assert_equal(#a, 2)
assert_equal(a[1],1)
assert_equal(a[2],2)
end)
test('Empty parens returns 0-tuples', function()
local a = tuple()
assert_equal(#a, 0)
end)
end)
context('Slicing tuples : t(i,j)', function()
test('One can slice values in a tuple', function()
local a = tuple('a', 'b', 'c', 'd', 'e')
local sub_a = a(2,4)
assert_equal(sub_a, tuple('b','c','d'))
end)
test('Argument j defaults to the last element in tuple', function()
local a = tuple(1,2,3,4,5)
local sub_a = a(3)
assert_equal(sub_a, tuple(3,4,5))
end)
test('Argument i defaults to the first element in tuple', function()
local a = tuple(1,2,3,4,5)
local sub_a = a()
assert_equal(sub_a, a)
end)
end)
context('String representation:', function()
test('class provides a tostring metamethod', function()
assert_equal(tostring(tuple(1,2,3)),'(1, 2, 3)')
end)
test('the string representation supports booleans', function()
assert_equal(tostring(tuple(true,false)),'(true, false)')
end)
end)
context('Inspecting tuples', function()
test('Tuple class provides an iterator', function()
local tup = tuple('l', 'u', 'a')
for i, element in tup:elements() do
assert_equal(element, ('lua'):sub(i,i))
end
end)
test('has() returns true if a value belongs to a tuple', function()
local tup = tuple(1,2,3,4,5,6,7,8,9,10)
for i = 1,10 do
assert_true(tup:has(i))
end
tup = tuple()
for i = 1,10 do
assert_false(tup:has(i))
end
end)
end)
context('Querying size', function()
test('len() returns the tuple size', function()
local tup = tuple(0.1, 0.2, 'a', 10, false)
local tup0 = tuple()
assert_equal(tup:len(), 5)
assert_equal(tup0:len(), 0)
end)
test('# operator is the same as len()', function()
local tup = tuple(0.1, 0.2, 'a', 10, false)
local tup0 = tuple()
assert_equal(#tup, tup:len())
assert_equal(#tup0, tup0:len())
end)
end)
context('Inclusion', function()
test('includes() returns true if tuple contains another', function()
local tup_big = tuple(1,2,3)
assert_true(tup_big:includes(tuple(1)))
assert_true(tup_big:includes(tuple(1,2)))
assert_true(tup_big:includes(tuple(1,2,3)))
assert_false(tup_big:includes(tuple(1,4)))
assert_false(tup_big:includes(tuple(0,2,3)))
assert_false(tup_big:includes(tuple(1,2,3,3)))
end)
test('tuples always includes itself', function()
local tup = tuple(1,2,3,4,5)
assert_true(tup:includes(tup))
end)
test('tuples always includes empty tuples', function()
assert_true(tuple(1):includes(tuple()))
assert_true(tuple():includes(tuple()))
end)
end)
context('Array conversion', function()
test('toArray() method converts a tuple to an array', function()
local tup = tuple('a', 'b', 'c')
local array = tup:toArray()
assert_equal(#array, 3)
assert_equal(array[1], 'a')
assert_equal(array[2], 'b')
assert_equal(array[3], 'c')
end)
test('Empty tuples are converted to empty arrays', function()
local tup = tuple()
local array = tup:toArray()
assert_equal(#array, 0)
end)
end)
context('Comparison is lexicographical', function()
context('Equality test', function()
test('Testing A == B', function()
local A = tuple('a', 'b', 'c', 'd', false, true)
local B = tuple('a', 'b', 'c', 'd', false, true)
assert_true(A == B)
end)
test('A tuple is always equal to itself', function()
local A = tuple('a', false, true)
assert_true(A == A)
end)
test('Tuples with different length are not equal', function()
local A = tuple('a', 'b')
local B = tuple('a', 'b', 'c')
assert_false(A == B)
end)
test('Tuples must be the exact same to be equal', function()
local A = tuple('a', 'b', 'd', 'c')
local B = tuple('a', 'b', 'c', 'd')
assert_false(A == B)
end)
end)
context('Relational order', function()
test('Relational < test', function()
assert_true(tuple('a', 'b', 'c') < tuple('b', 'c', 'd'))
assert_true(tuple(1,2,3,4) < tuple(2,3,4))
assert_false(tuple(1,2,3,4) < tuple(2,3,3))
end)
test('Relational <= test', function()
assert_true(tuple('a', 'b', 'c') <= tuple('b', 'b', 'c'))
assert_true(tuple(1,1,1) <= tuple(2,2,1,3))
assert_false(tuple(1,1,1) <= tuple(1,2,0,3))
end)
end)
end)
context('Operations', function()
test('Addition', function()
assert_equal(tuple(1) + tuple(2), tuple(1,2))
assert_equal(tuple(3,4) + tuple('a', false), tuple(3, 4, 'a', false))
assert_equal(tuple() + tuple(), tuple())
end)
test('Multiplication', function()
assert_equal(tuple('a','z') * 2, tuple('a', 'z', 'a', 'z'))
assert_equal(tuple(1) * 3, tuple(1,1,1))
assert_equal(2 * tuple(2), tuple(2,2))
assert_equal(tuple() * 10, tuple())
assert_nil(tuple() * 0)
end)
end)
|
require 'busted.runner'()
describe("labRenderers", function()
local labRenderers
local force0 = {
index = 0,
}
local force1 = {
index = 1,
}
local lab0 = {
type = "lab",
name = "lab",
valid = true,
unit_number = 0,
force = force0,
}
local lab1 = {
type = "lab",
name = "lab",
valid = true,
unit_number = 1,
force = force1,
}
local nonLab = {
type = "tool",
name = "hammer",
valid = true,
unit_number = 1,
force = force0,
}
local invalidLab = {
type = "lab",
name = "lab",
valid = false,
unit_number = 1,
force = force0,
}
local otherLab = {
type = "lab",
name = "fancy-lab",
valid = true,
unit_number = 1,
force = force0,
}
local sctLab = {
type = "lab",
name = "sct-lab-t4",
valid = true,
unit_number = 1,
force = force0,
}
local bigLab = {
type = "lab",
name = "big-lab",
valid = true,
unit_number = 1,
force = force0,
}
local schallMachineScalingLab6 = {
type = "lab",
name = "lab-MS-6",
valid = true,
unit_number = 2,
force = force0,
}
local bobLab = {
type = "lab",
name = "lab-2",
valid = true,
unit_number = 1,
force = force0,
}
local bobAlienLab = {
type = "lab",
name = "lab-alien",
valid = true,
unit_number = 1,
force = force0,
}
setup(function()
_G.rendering = require("spec.mocks.rendering")
labRenderers = require("core.labRenderers")
end)
before_each(function()
labRenderers.init({
labsByForce = {},
labAnimations = {},
labLights = {},
})
rendering.resetMock()
stub(softErrorReporting, "showModError")
end)
after_each(function()
softErrorReporting.showModError:revert()
end)
teardown(function()
labRenderers = nil
end)
it("has the same initial state", function()
assert.same(labRenderers.state, labRenderers.initialState)
end)
describe("isCompatibleLab", function()
it("accepts a regular lab", function()
assert.is_true(labRenderers.isCompatibleLab(lab0))
end)
it("accepts a Science Cost Tweaker lab", function()
assert.is_true(labRenderers.isCompatibleLab(sctLab))
end)
it("accepts a Big Lab", function()
assert.is_true(labRenderers.isCompatibleLab(bigLab))
end)
it("accepts Bob's labs", function()
assert.is_true(labRenderers.isCompatibleLab(bobLab))
assert.is_true(labRenderers.isCompatibleLab(bobAlienLab))
end)
it("rejects non-lab", function()
assert.is_false(labRenderers.isCompatibleLab(nonLab))
end)
it("rejects other labs", function()
assert.is_false(labRenderers.isCompatibleLab(otherLab))
end)
end)
describe("addLab", function()
it("adds a lab and creates render objects", function()
labRenderers.addLab(lab0)
assert.stub(softErrorReporting.showModError).was_not.called()
assert.truthy(labRenderers.state.labsByForce[lab0.force.index])
local lab = labRenderers.state.labsByForce[lab0.force.index][lab0.unit_number]
assert.truthy(labRenderers.state.labsByForce[lab0.force.index][lab0.unit_number])
local animationId = labRenderers.state.labAnimations[lab0.unit_number]
assert.truthy(animationId)
assert.is_true(rendering.is_valid(animationId))
local lightId = labRenderers.state.labLights[lab0.unit_number]
assert.truthy(lightId)
assert.is_true(rendering.is_valid(lightId))
end)
it("adds labs in separate forces", function()
labRenderers.addLab(lab0)
labRenderers.addLab(lab1)
assert.truthy(labRenderers.state.labsByForce[lab0.force.index])
assert.truthy(labRenderers.state.labsByForce[lab1.force.index])
assert.not_nil(next(labRenderers.state.labsByForce[lab0.force.index]))
assert.not_nil(next(labRenderers.state.labsByForce[lab1.force.index]))
assert.not_equal(labRenderers.state.labsByForce[lab0.force.index], labRenderers.state.labsByForce[lab1.force.index])
end)
it("scales renderers appropriately", function()
labRenderers.addLab(lab0)
labRenderers.addLab(bigLab)
labRenderers.addLab(schallMachineScalingLab6)
local animId, lightId = labRenderers.getRenderObjects(lab0)
assert.equal(1, rendering.get_x_scale(animId))
assert.equal(1, rendering.get_y_scale(animId))
assert.equal(1, rendering.get_scale(lightId))
local bigAnimId, bigLightId = labRenderers.getRenderObjects(bigLab)
local bigLabScale = labRenderers.specialLabScales[bigLab.name]
assert.equal(bigLabScale, rendering.get_x_scale(bigAnimId))
assert.equal(bigLabScale, rendering.get_y_scale(bigAnimId))
assert.equal(bigLabScale, rendering.get_scale(bigLightId))
local schallAnimId, schallLightId = labRenderers.getRenderObjects(schallMachineScalingLab6)
local schallLabScale = labRenderers.specialLabScales[schallMachineScalingLab6.name]
assert.equal(schallLabScale, rendering.get_x_scale(schallAnimId))
assert.equal(schallLabScale, rendering.get_y_scale(schallAnimId))
assert.equal(schallLabScale, rendering.get_scale(schallLightId))
end)
it("won't add a non-lab", function()
labRenderers.addLab(nonLab)
assert.is_nil(next(labRenderers.state.labsByForce))
end)
it("won't add a lab by any other name", function()
labRenderers.addLab(otherLab)
assert.is_nil(next(labRenderers.state.labsByForce))
end)
it("errors when attempting to add a nil entity", function()
labRenderers.addLab(nil)
assert.stub(softErrorReporting.showModError).was.called_with("errors.unregistered-entity-created")
end)
it("errors when attempting to add an invalid lab", function()
labRenderers.addLab(invalidLab)
assert.stub(softErrorReporting.showModError).was.called_with("errors.unregistered-entity-created")
end)
it("errors instead of adding a lab twice", function()
labRenderers.addLab(lab0)
labRenderers.addLab(lab0)
assert.stub(softErrorReporting.showModError).was.called_with("errors.lab-registered-twice")
end)
end)
describe("removeLab", function()
it("removes lab and its rendering objects", function()
labRenderers.addLab(lab0)
labRenderers.removeLab(lab0)
assert.stub(softErrorReporting.showModError).was_not.called()
assert.is_nil(next(labRenderers.labsForForce(lab0.force.index)))
assert.is_nil(next(labRenderers.state.labAnimations))
assert.is_nil(next(labRenderers.state.labLights))
end)
it("errors when an unregistered lab is removed", function()
labRenderers.removeLab(lab0)
assert.stub(softErrorReporting.showModError).was.called_with("errors.unregistered-lab-deleted")
end)
it("errors when an unregistered lab is removed, even if force exists", function()
labRenderers.addLab(lab0)
labRenderers.removeLab(lab0)
labRenderers.removeLab(lab0)
assert.stub(softErrorReporting.showModError).was.called_with("errors.unregistered-lab-deleted")
end)
end)
describe("getRenderObjects", function()
it("gets valid render objects for lab", function()
labRenderers.addLab(lab0)
local animationId, lightId = labRenderers.getRenderObjects(lab0)
assert.is_true(rendering.is_valid(animationId))
assert.is_true(rendering.is_valid(lightId))
end)
it("errors if animation was destroyed, and creates new animation", function()
labRenderers.addLab(lab0)
rendering.destroy(labRenderers.state.labAnimations[lab0.unit_number])
local animationId, lightId = labRenderers.getRenderObjects(lab0)
assert.stub(softErrorReporting.showModError).was.called_with("errors.render-object-destroyed")
assert.is_true(rendering.is_valid(animationId))
end)
it("errors if light was destroyed, and creates new light", function()
labRenderers.addLab(lab0)
rendering.destroy(labRenderers.state.labLights[lab0.unit_number])
local animationId, lightId = labRenderers.getRenderObjects(lab0)
assert.stub(softErrorReporting.showModError).was.called_with("errors.render-object-destroyed")
assert.is_true(rendering.is_valid(animationId))
end)
end)
end)
|
MSBTProfiles_SavedVars = {
["profiles"] = {
["Default"] = {
["creationVersion"] = "5.7.146",
},
},
}
MSBT_SavedMedia = {
["fonts"] = {
},
["sounds"] = {
},
}
|
--[[
Minecart
========
Copyright (C) 2019-2021 Joachim Stolberg
MIT
See license.txt for more information
]]--
-- for lazy programmers
local M = minetest.get_meta
local S = minecart.S
local CYCLE_TIME = 4
local function node_timer(pos)
local node = minetest.get_node(pos)
local dir = minetest.facedir_to_dir(node.param2)
minecart.punch_cart({x = pos.x, y = pos.y + 1, z = pos.z}, nil, 1, dir)
return true
end
local function after_dig_node(pos, oldnode, oldmetadata, digger)
techage.remove_node(pos, oldnode, oldmetadata)
end
minetest.register_node("minecart:cart_pusher", {
description = S("Cart Pusher"),
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
{-8/16,-8/16,-8/16, 8/16, 8/16, 8/16},
{-1/16, 8/16,-4/16, 1/16, 10/16, 4/16},
},
},
tiles = {
-- up, down, right, left, back, front
"default_steel_block.png^minecart_pusher_top.png",
"default_steel_block.png",
"default_steel_block.png^minecart_pusher.png",
"default_steel_block.png^minecart_pusher.png",
"default_steel_block.png^minecart_pusher.png",
"default_steel_block.png^minecart_pusher.png",
},
after_place_node = function(pos)
minetest.get_node_timer(pos):start(CYCLE_TIME)
end,
on_timer = node_timer,
paramtype2 = "facedir",
groups = {choppy=2, cracky=2, crumbly=2},
is_ground_content = true,
sounds = default.node_sound_metal_defaults(),
})
minetest.register_craft({
output = "minecart:cart_pusher",
recipe = {
{"dye:black", "default:steel_ingot", "dye:yellow"},
{"default:steel_ingot", "default:mese_crystal", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
},
})
|
local objects =
{
--Maxime
createObject(14506,2239.6999500,-1165.0999800,1038.0000000,0.0000000,0.0000000,0.0000000,46), --object(imy_motel_int,46), (1,46),
createObject(14846,1473.3994100,1752.2998000,14.8000000,0.0000000,0.0000000,0.0000000,46), --object(int_ppol,46), (2,46),
createObject(1535,1470.4000200,1752.5000000,13.7000000,0.0000000,0.0000000,0.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1473.4000200,1752.5365000,13.7000000,0.0000000,0.0000000,179.9950000,46), --object(gen_doorext14,46), (2,46),
createObject(8167,1466.1999500,1759.0999800,16.3000000,0.0000000,0.0000000,0.0000000,46), --object(apgate1_vegs01,46), (2,46),
createObject(1535,1467.0000000,1768.3000500,13.7000000,0.0000000,0.0000000,0.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1468.5000000,1768.3000500,13.7000000,0.0000000,0.0000000,0.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1471.0000000,1768.2998000,13.7000000,0.0000000,0.0000000,0.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1472.5000000,1768.3000500,13.7000000,0.0000000,0.0000000,0.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1776,1469.7998000,1767.5000000,14.9000000,0.0000000,0.0000000,0.0000000,46), --object(cj_candyvendor,46), (1,46),
createObject(2838,1475.0000000,1765.1992200,14.6600000,0.0000000,0.0000000,0.0000000,46), --object(gb_takeaway03,46), (1,46),
createObject(2370,1474.6999500,1765.0999800,13.8000000,0.0000000,0.0000000,359.5800000,46), --object(shop_set_1_table,46), (1,46),
createObject(1712,1478.0999800,1766.3000500,13.8000000,0.0000000,0.0000000,265.3960000,46), --object(kb_couch05,46), (1,46),
createObject(1710,1473.3000500,1767.4000200,13.8000000,0.0000000,0.0000000,0.0000000,46), --object(kb_couch07,46), (1,46),
createObject(1512,1476.8000500,1764.0999800,14.0000000,0.0000000,0.0000000,0.0000000,46), --object(dyn_wine_03,46), (1,46),
createObject(1512,1477.1999500,1767.3000500,14.4000000,0.0180000,89.7800000,268.3430000,46), --object(dyn_wine_03,46), (2,46),
createObject(1512,1477.0999800,1767.3000500,14.3350000,90.0000000,92.0480000,271.4760000,46), --object(dyn_wine_03,46), (3,46),
createObject(14527,1472.1992200,1760.0996100,14.6000000,0.0000000,0.0000000,0.0000000,46), --object(fannyfan,46), (1,46),
createObject(2395,1466.4000200,1758.0999800,13.8000000,0.0000000,0.0000000,90.0000000,46), --object(cj_sports_wall,46), (3,46),
createObject(2395,1466.3994100,1763.8994100,13.8000000,0.0000000,0.0000000,90.0000000,46), --object(cj_sports_wall,46), (4,46),
createObject(1778,1478.0000000,1753.5999800,13.8000000,0.0000000,0.0000000,170.0000000,46), --object(cj_mop_pail,46), (1,46),
createObject(1209,1466.6999500,1757.6999500,13.8000000,0.0000000,0.0000000,90.0000000,46), --object(vendmach,46), (1,46),
createObject(14520,1471.0000000,1759.5000000,14.1000000,0.0000000,0.0000000,217.2740000,46), --object(immy_clothes,46), (1,46),
createObject(2953,1476.3000500,1765.5000000,13.8000000,0.0000000,0.0000000,102.3020000,46), --object(kmb_paper_code,46), (1,46),
createObject(2953,1470.5999800,1757.9000200,13.8000000,0.0000000,0.0000000,92.2990000,46), --object(kmb_paper_code,46), (2,46),
createObject(2953,1466.4000200,1762.5000000,15.0000000,0.0000000,0.0000000,92.2960000,46), --object(kmb_paper_code,46), (3,46),
createObject(2690,1467.1999500,1753.1999500,14.1000000,0.0000000,0.0000000,190.0000000,46), --object(cj_fire_ext,46), (1,46),
createObject(2690,1467.5999800,1753.1999500,14.1000000,0.0000000,0.0000000,189.9980000,46), --object(cj_fire_ext,46), (2,46),
createObject(14819,1466.5300300,1765.3000500,14.9000000,0.0000000,0.0000000,270.0000000,46), --object(og_door,46), (1,46),
createObject(2110,1467.1999500,1755.9000200,13.8000000,0.0000000,0.0000000,270.0000000,46), --object(low_dinning_4,46), (1,46),
createObject(2108,1478.0000000,1767.0999800,13.8000000,0.0000000,0.0000000,0.0000000,46), --object(cj_mlight13,46), (1,46),
createObject(1810,1467.8000500,1754.5000000,13.8000000,0.0000000,0.0000000,245.3960000,46), --object(cj_foldchair,46), (1,46),
createObject(1810,1468.0000000,1755.5000000,13.8000000,0.0000000,0.0000000,295.3910000,46), --object(cj_foldchair,46), (2,46),
createObject(2894,1467.4000200,1755.0000000,14.6000000,0.0000000,0.0000000,270.0000000,46), --object(kmb_rhymesbook,46), (1,46),
createObject(2670,1473.8000500,1765.3000500,13.9000000,0.0000000,2.3020000,98.7470000,46), --object(proc_rubbish_1,46), (1,46),
createObject(1265,1477.5999800,1753.4000200,14.2000000,0.0000000,0.0000000,0.0000000,46), --object(blackbag2,46), (1,46),
createObject(1535,1478.6999500,1761.0999800,13.7000000,0.0000000,0.0000000,270.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1478.6999500,1755.4000200,13.7000000,0.0000000,0.0000000,270.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1478.6999500,1758.1999500,13.7000000,0.0000000,0.0000000,270.0000000,46), --object(gen_doorext14,46), (1,46),
createObject(1535,1478.6999500,1763.9000200,13.7000000,0.0000000,0.0000000,270.0000000,46), --object(gen_doorext14,46), (1,46),
}
local col = createColSphere( 1471.8935546875, 1752.9169921875, 14.760937690735, 20)
local function watchChanges( )
if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then
for key, value in pairs( objects ) do
setElementDimension( value, getElementDimension( getLocalPlayer( ) ) )
end
elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
end
end
addEventHandler( "onClientColShapeHit", col,
function( element )
if element == getLocalPlayer( ) then
addEventHandler( "onClientRender", root, watchChanges )
end
end
)
addEventHandler( "onClientColShapeLeave", col,
function( element )
if element == getLocalPlayer( ) then
removeEventHandler( "onClientRender", root, watchChanges )
end
end
)
-- Put them standby for now.
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
for index, object in ipairs ( objects ) do
setElementDoubleSided ( object, true )
-- if getElementModel(object) == 10281 then
-- setObjectScale ( object, 0.60000002384186 )
-- end
--setElementCollisionsEnabled ( object, true )
end
|
local Adapter = require('core.inventoryAdapter')
local Craft = require('farms.craft')
local turtle = _G.turtle
local CRAFTING_TABLE = 'minecraft:crafting_table'
local function clearGrid(inventory)
for i = 1, 16 do
local count = turtle.getItemCount(i)
if count > 0 then
inventory:insert(i, count)
if turtle.getItemCount(i) ~= 0 then
return false
end
end
end
return true
end
function turtle.craftItem(item, count, inventoryInfo)
local success, msg
local inventory = Adapter.wrap(inventoryInfo)
if not inventory then
return false, 'Invalid inventory'
end
local equipped, side
if not turtle.isEquipped('workbench') then
local modemSide = turtle.isEquipped('modem') or 'right'
local osides = { left = 'right', right = 'left' }
side = osides[modemSide]
if not turtle.select(CRAFTING_TABLE) then
clearGrid(inventory)
if not turtle.selectOpenSlot() then
return false, 'Inventory is full'
end
if not inventory:provide({ name = CRAFTING_TABLE, damage = 0 }, 1) then
return false, 'Missing crafting table'
end
end
local slot = turtle.select(CRAFTING_TABLE)
turtle.equip(side, CRAFTING_TABLE)
equipped = turtle.getItemDetail(slot.index)
end
clearGrid(inventory)
success, msg = Craft.craftRecipe(item, count or 1, inventory)
if equipped then
turtle.selectOpenSlot()
inventory:provide({ name = equipped.name, damage = equipped.damage }, 1)
turtle.equip(side, equipped.name .. ':' .. equipped.damage)
end
return success, msg
end
function turtle.canCraft(item, count, items)
return Craft.canCraft(item, count, items)
end
return true
|
local mock = require "deftest.mock"
local mockfs = require "deftest.mock.fs"
return function()
local basic
describe("basic credentials", function()
before(function()
basic = require "aws-sdk.core.credentials.basic"
mock.mock(sys)
mock.mock(os)
mockfs.mock()
end)
after(function()
package.loaded["aws-sdk.core.credentials.basic"] = nil
mock.unmock(sys)
mock.unmock(os)
mockfs.unmock()
end)
it("should should be able to read credentials from game.project", function()
sys.get_config.replace(function(key, default)
if key == "aws.access_key_id" then
return "fooaccess"
elseif key == "aws.secret_access_key" then
return "foosecret"
else
return sys.get_config.original(key, default)
end
end)
local provider = basic.from_defold_game_project()
assert(provider.get and provider.refresh, "The provider doesn't have a get and/or refresh function")
provider.refresh()
local access_key_id, secret_access_key, token = provider.get()
assert(access_key_id == "fooaccess", "Problem getting access_key_id")
assert(secret_access_key == "foosecret", "Problem getting secret_access_key")
assert(not token, "Didn't expect a token")
end)
it("should fail to refresh credentials from game.project if none are defined", function()
sys.get_config.replace(function(key, default)
return nil
end)
local provider = basic.from_defold_game_project()
assert_error(provider.refresh)
end)
it("should be able to read credentials from system environment with default prefix", function()
os.getenv.replace(function(key)
if key == "AWS_ACCESS_KEY_ID" then
return "fooaccess"
elseif key == "AWS_SECRET_ACCESS_KEY" then
return "foosecret"
else
return os.getenv.original(key)
end
end)
local provider = basic.from_env()
assert(provider.get and provider.refresh, "The provider doesn't have a get and/or refresh function")
provider.refresh()
local access_key_id, secret_access_key, token = provider.get()
assert(access_key_id == "fooaccess", "Problem getting access_key_id")
assert(secret_access_key == "foosecret", "Problem getting secret_access_key")
assert(not token, "Didn't expect a token")
end)
it("should be able to read credentials from system environment with a custom prefix", function()
os.getenv.replace(function(key)
if key == "PREFIX_ACCESS_KEY_ID" then
return "fooaccess"
elseif key == "PREFIX_SECRET_ACCESS_KEY" then
return "foosecret"
else
return os.getenv.original(key)
end
end)
local provider = basic.from_env("PREFIX_")
assert(provider.get and provider.refresh, "The provider doesn't have a get and/or refresh function")
provider.refresh()
local access_key_id, secret_access_key, token = provider.get()
assert(access_key_id == "fooaccess", "Problem getting access_key_id")
assert(secret_access_key == "foosecret", "Problem getting secret_access_key")
assert(not token, "Didn't expect a token")
end)
it("should fail to refresh credentials from system environment if none are set", function()
os.getenv.replace(function(key)
return nil
end)
local provider = basic.from_env()
assert_error(provider.refresh)
end)
it("should be able to read credentials from a json file", function()
mockfs.set_file("credentials", '{ "accessKeyId": "fooaccess", "secretAccessKey": "foosecret" }')
local provider = basic.from_json_file("credentials")
assert(provider.get and provider.refresh, "The provider doesn't have a get and/or refresh function")
provider.refresh()
local access_key_id, secret_access_key, token = provider.get()
assert(access_key_id == "fooaccess", "Problem getting accessKeyId from json")
assert(secret_access_key == "foosecret", "Problem getting secretAccessKey from json")
assert(not token, "Didn't expect a token")
end)
it("should fail to refresh credentials from json file if file doesn't exist", function()
mockfs.set_file("credentials", nil)
local provider = basic.from_json_file("credentials")
assert_error(provider.refresh)
end)
end)
end
|
data:extend({
{
allowed_values={"true","false"},
default_value="true",
localised_description="If stack sizes should be multiplied by the stack size setting, if not then the stack size setting determines the definite item stack size.",
localised_name="Item Stack Sizes Multiply?",
name="stackMultiply",
setting_type="startup",
type="bool-setting",
},
{
default_value=1,
localised_description="The integer responsible for determining item stack size.",
localised_name="Item Stack Size",
maximum_value=1000,
minimum_value=1,
name="stackSize",
setting_type="startup",
type="int-setting",
},
})
|
require( 'src/token_bucket' )
local lu = require( './tests/lib/luaunit' )
function test_01_consume()
local bucket = TokenBucket( 10 );
lu.assertEquals( bucket:consume( 9 ), true );
lu.assertEquals( bucket:getTokenCount(), 1 );
lu.assertEquals( bucket:consume(), true );
lu.assertEquals( bucket:consume(), false );
lu.assertEquals( bucket:getTokenCount(), 0 );
end
function test_02_check_replenish()
local bucket = TokenBucket( 10, 2 );
lu.assertEquals( bucket:consume( 10 ), true );
lu.assertEquals( bucket:getTokenCount(), 0 );
sleep( 0.25 );
lu.assertEquals( bucket:getTokenCount(), 0 );
sleep( 0.25 );
lu.assertEquals( bucket:getTokenCount(), 1 );
end
function test_03_test_constructor_params()
local bucket = TokenBucket( 10, 3 )
lu.assertEquals( bucket:getRate(), 1 / 3 );
lu.assertEquals( bucket:getTokenCount(), 10 );
end
--
-- helper
--
local clock = os.clock
function sleep(n) -- seconds
local t0 = clock()
while clock() - t0 <= n do end
end
|
data:extend({
{
type="recipe",
name="AppliedLargeGlassAmpoule",
category="AppliedGlassWorking1",
energy_required=10,
ingredients={
{"AppliedGlassTube", 1},
{type="fluid", amount=5, name="AppliedLightLiquidFuel"},
},
results={
{"AppliedLargeGlassAmpoule", 2},
},
enabled=false,
},{
type="recipe",
name="AppliedShortGlassTube",
category="AppliedGlassWorking1",
energy_required=10,
ingredients={
{"AppliedGlassTube", 1},
{type="fluid", amount=5, name="AppliedLightLiquidFuel"},
},
results={
{"AppliedShortGlassTube", 4},
},
enabled=false,
},{
type="recipe",
name="AppliedVacuumTubeBase",
category="AppliedGlassWorking1",
energy_required=10,
ingredients={
{"AppliedShortGlassTube", 1},
{"AppliedIronWire", 1},
{type="fluid", amount=5, name="AppliedLightLiquidFuel"},
},
result="AppliedVacuumTubeBase",
enabled=false,
},{
type="recipe",
name="AppliedBasicGetter",
energy_required=8,
ingredients={
{"AppliedIronStrip", 4},
{"AppliedPhosphorusPowder", 1},
},
results={
{"AppliedBasicGetter", 8},
},
enabled=false,
},{
type="recipe",
name="AppliedPreppedVacuumTube",
category="AppliedGlassWorking1",
energy_required=20,
ingredients={
{"AppliedIronStrip", 1},
{"AppliedIronWire", 1},
{"AppliedLargeGlassAmpoule", 1},
{"AppliedVacuumTubeBase", 1},
{"AppliedBasicGetter", 1},
{type="fluid", amount=5, name="AppliedLightLiquidFuel"},
},
result="AppliedPreppedVacuumTube",
enabled=false,
},{
type="recipe",
name="AppliedVacuumTube",
category="AppliedInductionHeating",
energy_required=5,
ingredients={
{"AppliedPreppedVacuumTube", 1},
},
result="AppliedVacuumTube",
enabled=false,
},{
type="recipe",
name="AppliedBasicSmallGlassCore",
category="AppliedGlassWorking1",
energy_required=4,
ingredients={
{"AppliedShortGlassTube", 1},
{type="fluid", amount=5, name="AppliedLightLiquidFuel"},
},
results={
{"AppliedBasicSmallGlassCore", 8},
},
enabled=false,
},{
type="recipe",
name="AppliedBasicResistor1",
category="AppliedElectronicComponentProduction1",
energy_required=2,
ingredients={
{"AppliedBasicSmallGlassCore", 1},
{"AppliedIronFineWire", 1},
{type="fluid", amount=5, name="AppliedBasicResin"},
},
result="AppliedBasicResistor1",
enabled=false,
},{
type="recipe",
name="AppliedBasicInductorCore",
energy_required=2,
ingredients={
{"AppliedIronStrip", 2},
},
result="AppliedBasicInductorCore",
enabled=false,
},{
type="recipe",
name="AppliedBasicInductor1",
category="AppliedElectronicComponentProduction1",
energy_required=2,
ingredients={
{"AppliedBasicInductorCore", 1},
{"AppliedIronFineWire", 2},
{type="fluid", amount=5, name="AppliedBasicResin"},
},
result="AppliedBasicInductor1",
enabled=false,
},{
type="recipe",
name="AppliedBasicCapacitor1",
category="AppliedElectronicComponentProduction1",
energy_required=2,
ingredients={
{"AppliedIronStrip", 1},
{"AppliedCopperStrip", 1},
{type="fluid", amount=5, name="AppliedBasicResin"},
},
result="AppliedBasicInductor1",
enabled=false,
},{
type="recipe",
name="AppliedBasicWoodenBoard",
energy_required=5,
ingredients={
{"AppliedTreatedWood", 1},
},
results={
{"AppliedBasicWoodenBoard", 2},
},
enabled=false,
},{
type="recipe",
name="AppliedBasicCircuitBoard1",
category="AppliedPCBEtching1",
energy_required=5,
ingredients={
{"AppliedBasicWoodenBoard", 1},
{type="fluid", amount=5, name="AppliedBasicResin"},
},
result="AppliedBasicCircuitBoard1",
enabled=false,
},{
type="recipe",
name="AppliedBasicEtchedCircuit1",
category="AppliedPCBEtching1",
energy_required=15,
ingredients={
{"AppliedBasicCircuitBoard1", 1},
{type="fluid", amount=5, name="AppliedFerricChloride"},
},
results={
{"AppliedBasicEtchedCircuit1", 1},
{type="fluid", amount=5, name="AppliedWasteWater1"},
},
enabled=false,
},{
type="recipe",
name="AppliedBasicPreppedCircuit1",
category="AppliedChipShooting1",
energy_required=10,
ingredients={
{"AppliedBasicEtchedCircuit1", 1},
{"AppliedVacuumTube", 3},
{"AppliedSolderWire", 1},
},
result="AppliedBasicPreppedCircuit1",
enabled=false,
},{
type="recipe",
name="AppliedBasicCircuit1",
category="AppliedChipShooting1",
energy_required=10,
ingredients={
{"AppliedBasicPreppedCircuit1", 1},
{"AppliedBasicResistor1", 5},
{"AppliedBasicInductor1", 1},
{"AppliedBasicCapacitor1", 2},
{"AppliedSolderWire", 1},
},
result="AppliedBasicCircuit1",
enabled=false,
},
})
|
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file path_based_movement_gen.lua
--! @brief component containing a path based movement generator
--! @copyright Sapier
--! @author Sapier
--! @date 2012-08-09
--
--! @defgroup mgen_path_based MGEN: Path based movement generator
--! @ingroup framework_int
--! @{
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
--! @class p_mov_gen
--! @brief a movement generator evaluating a path to a target and following it
--!@}
p_mov_gen = {}
p_mov_gen.max_waypoint_distance = 0.5
--! @brief movement generator identifier
--! @memberof p_mov_gen
p_mov_gen.name = "mgen_path"
-------------------------------------------------------------------------------
-- name: callback(entity,now)
--
--! @brief path based movement generator callback
--! @memberof p_mov_gen
--
-- param1: mob to do movement
-- param2: current time
-- retval: -
-------------------------------------------------------------------------------
function p_mov_gen.callback(entity,now,dstep)
mobf_assert_backtrace(entity ~= nil)
mobf_assert_backtrace(entity.dynamic_data ~= nil)
mobf_assert_backtrace(entity.dynamic_data.p_movement ~= nil)
if entity.dynamic_data.p_movement.eta ~= nil then
if now < entity.dynamic_data.p_movement.eta then
return
end
end
local current_pos = entity.object:getpos()
local handled = false
if entity.dynamic_data.p_movement.path == nil then
dbg_mobf.path_mov_lvl1(
"MOBF: path movement but mo path set!!")
return
end
local max_distance = p_mov_gen.max_waypoint_distance
mobf_assert_backtrace(entity.dynamic_data.p_movement.next_path_index ~= nil)
mobf_assert_backtrace(max_distance ~= nil)
--check if target is reached
if p_mov_gen.distance_to_next_point(entity,current_pos)
< max_distance then
dbg_mobf.path_mov_lvl1("MOBF: pathmov next to next point switching target")
local update_target = true
if entity.dynamic_data.p_movement.waypoint_stop then
entity.object:setvelocity({x=0,y=0,z=0})
end
--return to begining of path
if entity.dynamic_data.p_movement.next_path_index
== #entity.dynamic_data.p_movement.path then
if entity.dynamic_data.p_movement.cycle_path or
(entity.dynamic_data.p_movement.cycle_path == nil and
entity.data.patrol ~= nil and
entity.data.patrol.cycle_path) then
--0 is correct as it's incremented by one later
entity.dynamic_data.p_movement.next_path_index = 0
else
if entity.dynamic_data.p_movement.HANDLER_end_of_path ~= nil
and type(entity.dynamic_data.p_movement.HANDLER_end_of_path) == "function" then
entity.dynamic_data.p_movement.HANDLER_end_of_path(entity)
end
dbg_mobf.path_mov_lvl1("MOBF: cycle not set not updating point")
update_target = false
handled = true
end
end
if update_target then
mobf_assert_backtrace(entity.dynamic_data.p_movement.path ~= nil)
entity.dynamic_data.p_movement.next_path_index =
entity.dynamic_data.p_movement.next_path_index + 1
entity.dynamic_data.movement.target =
entity.dynamic_data.p_movement.path
[entity.dynamic_data.p_movement.next_path_index]
dbg_mobf.path_mov_lvl1("MOBF: (1) setting new target to index: " ..
entity.dynamic_data.p_movement.next_path_index .. " pos: " ..
printpos(entity.dynamic_data.movement.target))
handled = true
end
end
if not handled and
entity.dynamic_data.movement.target == nil then
mobf_assert_backtrace(entity.dynamic_data.p_movement.path ~= nil)
entity.dynamic_data.movement.target =
entity.dynamic_data.p_movement.path
[entity.dynamic_data.p_movement.next_path_index]
dbg_mobf.path_mov_lvl1("MOBF: (2) setting new target to index: " ..
entity.dynamic_data.p_movement.next_path_index .. " pos: " ..
printpos(entity.dynamic_data.movement.target))
end
mgen_follow.callback(entity,now)
end
-------------------------------------------------------------------------------
-- name: distance_to_next_point(entity)
--
--! @brief get distance to next target point (2d only)
--! @memberof p_mov_gen
--! @private
--
--! @param entity mob to check
--! @param current_pos position mob is atm
--
--! @retval distance
-------------------------------------------------------------------------------
function p_mov_gen.distance_to_next_point(entity,current_pos)
local index = entity.dynamic_data.p_movement.next_path_index
mobf_assert_backtrace(entity.dynamic_data.p_movement.path ~= nil)
mobf_assert_backtrace(index <= #entity.dynamic_data.p_movement.path)
return mobf_calc_distance_2d(current_pos,
entity.dynamic_data.p_movement.path[index])
end
-------------------------------------------------------------------------------
-- name: init_dynamic_data(entity,now)
--
--! @brief initialize dynamic data required by movement generator
--! @memberof p_mov_gen
--
--! @param entity to initialize
--! @param now current time
--! @param restored_data data restored on activate
-------------------------------------------------------------------------------
function p_mov_gen.init_dynamic_data(entity,now,restored_data)
local pos = entity.object:getpos()
local data = {
path = nil,
eta = nil,
last_move_stop = now,
next_path_index = 1,
force_target = nil,
pathowner = nil,
pathname = nil,
waypoint_stop = true,
}
if restored_data ~= nil and
type(restored_data) == "table" then
dbg_mobf.path_mov_lvl3(
"MOBF: path movement reading stored data: " .. dump(restored_data))
if restored_data.pathowner ~= nil and
restored_data.pathname ~= nil then
data.pathowner = restored_data.pathowner
data.pathname = restored_data.pathname
data.path = mobf_path.getpoints(data.pathowner,data.pathname)
dbg_mobf.path_mov_lvl3(
"MOBF: path movement restored points: " .. dump(data.path))
end
if restored_data.pathindex ~= nil and
type(restored_data.pathindex) == "number" and
restored_data.pathindex > 0 and
data.path ~= nil and
restored_data.pathindex < #data.path then
data.next_path_index = restored_data.pathindex
end
end
entity.dynamic_data.p_movement = data
mgen_follow.init_dynamic_data(entity,now)
entity.dynamic_data.movement.follow_speedup = false
end
-------------------------------------------------------------------------------
-- name: set_path(entity,path)
--
--! @brief set target for movgen
--! @memberof p_mov_gen
--! @public
--
--! @param entity mob to apply to
--! @param path to set
--! @param enable_speedup shall follow speedup be applied to path movement?
-------------------------------------------------------------------------------
function p_mov_gen.set_path(entity,path, enable_speedup)
mobf_assert_backtrace(entity.dynamic_data.p_movement ~= nil)
if path ~= nil then
entity.dynamic_data.p_movement.next_path_index = 1
entity.dynamic_data.movement.max_distance =
p_mov_gen.max_waypoint_distance
entity.dynamic_data.p_movement.path = path
--a valid path has at least 2 positions
mobf_assert_backtrace(#entity.dynamic_data.p_movement.path > 1)
entity.dynamic_data.movement.target =
entity.dynamic_data.p_movement.path[2]
entity.dynamic_data.movement.follow_speedup = enable_speedup
return true
else
entity.dynamic_data.p_movement.next_path_index = nil
entity.dynamic_data.movement.max_distance = nil
entity.dynamic_data.p_movement.path = nil
entity.dynamic_data.movement.target = nil
entity.dynamic_data.movement.follow_speedup = nil
return false
end
end
-------------------------------------------------------------------------------
-- name: set_cycle_path(entity,value)
--
--! @brief set state of path cycle mechanism
--! @memberof p_mov_gen
--! @public
--
--! @param entity mob to apply to
--! @param value to set true/false/nil(mob global default)
-------------------------------------------------------------------------------
function p_mov_gen.set_cycle_path(entity,value)
mobf_assert_backtrace(entity.dynamic_data.p_movement ~= nil)
entity.dynamic_data.p_movement.cycle_path = value
end
-------------------------------------------------------------------------------
-- name: set_end_of_path_handler(entity,handler)
--
--! @brief set handler to call for non cyclic paths if final target is reached
--! @memberof p_mov_gen
--! @public
--
--! @param entity mob to apply to
--! @param handler to call at final target
-------------------------------------------------------------------------------
function p_mov_gen.set_end_of_path_handler(entity,handler)
entity.dynamic_data.p_movement.HANDLER_end_of_path = handler
end
-------------------------------------------------------------------------------
-- name: set_target(entity, target, follow_speedup, max_distance)
--
--! @brief set target for movgen
--! @memberof p_mov_gen
--! @public
--
--! @param entity mob to apply to
--! @param target to set
--! @param follow_speedup use follow speedup to reach target
--! @param max_distance --unused here
-------------------------------------------------------------------------------
function p_mov_gen.set_target(entity, target, follow_speedup, max_distance)
mobf_assert_backtrace(target ~= nil)
local current_pos = entity.getbasepos(entity)
local targetpos = nil
if not mobf_is_pos(target) then
if target:is_player() then
targetpos = target:getpos()
targetpos.y = targetpos.y +0.5
else
if type(target.getbasepos) == "function" then
targetpos = target.getbasepos(target)
else
targetpos = target:getpos()
end
end
else
targetpos = target
end
if targetpos == nil then
return false
end
if entity.dynamic_data.p_movement.lasttargetpos ~= nil then
if mobf_pos_is_same(entity.dynamic_data.p_movement.lasttargetpos,
targetpos) then
return true
end
end
entity.dynamic_data.p_movement.lasttargetpos = targetpos
entity.dynamic_data.p_movement.path = nil
entity.dynamic_data.p_movement.next_path_index = 1
--on target mode max distance is always 0.5
entity.dynamic_data.movement.max_distance = p_mov_gen.max_waypoint_distance
--try to find path on our own
if not mobf_get_world_setting("mobf_disable_pathfinding") then
entity.dynamic_data.p_movement.path =
mobf_path.find_path(current_pos,targetpos,5,1,1,nil)
else
entity.dynamic_data.p_movement.path = nil
end
if entity.dynamic_data.p_movement.path ~= nil then
--a valid path has at least 2 positions
mobf_assert_backtrace(#entity.dynamic_data.p_movement.path > 1)
entity.dynamic_data.movement.target =
entity.dynamic_data.p_movement.path[2]
entity.dynamic_data.movement.follow_speedup = follow_speedup
return true
end
if entity.dynamic_data.p_movement.path == nil then
minetest.log(LOGLEVEL_INFO,
"MOBF: no pathfinding support/ no path found directly setting targetpos as path")
entity.dynamic_data.p_movement.path = {}
table.insert(entity.dynamic_data.p_movement.path,targetpos)
entity.dynamic_data.movement.target =
entity.dynamic_data.p_movement.path[1]
entity.dynamic_data.movement.follow_speedup = follow_speedup
return true
end
return false
end
--register this movement generator
registerMovementGen(p_mov_gen.name,p_mov_gen)
|
local mod = DBM:NewMod("d593", "DBM-Scenario-MoP")
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 2 $"):sub(12, -3))
mod:SetZone()
mod:RegisterCombat("scenario", 1050)
mod:RegisterEventsInCombat(
"SPELL_CAST_SUCCESS",
"UNIT_DIED",
"CHAT_MSG_MONSTER_YELL"
)
mod.onlyNormal = true
--Zan'thik Swarmer spawns don't show in logs, so might need to do /chatlog and /yell when they spawn and schedule a loop to get add wave timers for final boss
local warnGuidedMissle = mod:NewCastAnnounce(135546, 3, 5)
local warnImpale = mod:NewSpellAnnounce(133942, 2)
local specWarnGuidedMissle = mod:NewSpecialWarningPreWarn(135546, nil, 5)--So you can use Force field and not get weapons disabled.
local timerGuidedMissle = mod:NewCastTimer(5, 135546)--Time until impact
local timerImpaleCD = mod:NewNextTimer(6, 133942)
mod:RemoveOption("HealthFrame")
function mod:SPELL_CAST_SUCCESS(args)
if args.spellId == 135546 then
timerGuidedMissle:Start(args.sourceGUID)
if self:AntiSpam(2) then--Sometime 2 fire within 1-2 sec of eachother. We want to throttle warning spam but not cast timers so we can time our shield so it's up for both missles
warnGuidedMissle:Show()
specWarnGuidedMissle:Show()
end
elseif args.spellId == 134974 then
warnImpale:Show()
timerImpaleCD:Start()
end
end
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 67879 then--Commander Tel'vrak
timerImpaleCD:Cancel()
end
end
function mod:CHAT_MSG_MONSTER_YELL(msg)
if msg == L.TelvrakPull or msg:find(L.TelvrakPull) then
timerImpaleCD:Start(20)
end
end
|
--[[
@author Ilias-Timon Poulakis (FeedTheCat)
@license MIT
@version 1.0.2
@about Create an approximate razor edit from region under mouse
]]
local expand_beat_limit = 3
local shrink_beat_limit = 3
reaper.Undo_BeginBlock()
-- Get mouse cursor position
reaper.PreventUIRefresh(1)
local cursor_pos = reaper.GetCursorPosition()
-- View: Move edit cursor to mouse cursor (no snapping)
reaper.Main_OnCommand(40514, 0)
local mouse_pos = reaper.GetCursorPosition()
reaper.SetEditCurPos2(0, cursor_pos, false, false)
reaper.PreventUIRefresh(-1)
local _, reg_idx = reaper.GetLastMarkerAndCurRegion(0, mouse_pos)
if reg_idx == -1 then
local proj_length = reaper.GetProjectLength(0)
-- Set razor edit to space inbetween regions
reg_start_pos = 0
reg_end_pos = proj_length
for i = 0, reaper.CountProjectMarkers(0) - 1 do
local _, is_region, start_pos, end_pos = reaper.EnumProjectMarkers3(0, i)
if is_region then
if end_pos < mouse_pos then
reg_start_pos = end_pos
end
if start_pos > mouse_pos then
reg_end_pos = start_pos
break
end
end
end
-- Set razor edit end to mouse pos if it exceeds project length
if reg_start_pos == proj_length then
reg_end_pos = mouse_pos
end
else
-- Get region bounds from region idx at mouse
_, _, reg_start_pos, reg_end_pos = reaper.EnumProjectMarkers3(0, reg_idx)
end
-- Razor edit: Clear all areas
reaper.Main_OnCommand(42406, 0)
local _, _, _, reg_start_beat = reaper.TimeMap2_timeToBeats(0, reg_start_pos)
local _, _, _, reg_end_beat = reaper.TimeMap2_timeToBeats(0, reg_end_pos)
for t = 0, reaper.CountTracks(0) - 1 do
local raz_start_pos = reg_start_pos
local raz_end_pos = reg_end_pos
local track = reaper.GetTrack(0, t)
for i = 0, reaper.CountTrackMediaItems(track) - 1 do
local item = reaper.GetTrackMediaItem(track, i)
local item_length = reaper.GetMediaItemInfo_Value(item, 'D_LENGTH')
local item_start_pos = reaper.GetMediaItemInfo_Value(item, 'D_POSITION')
local item_mid_pos = item_start_pos + item_length / 2
local item_end_pos = item_start_pos + item_length
-- Check if item crosses start of region
if item_start_pos < reg_start_pos and item_end_pos > reg_start_pos then
-- Check if the larger part of the item is inside the region
if item_mid_pos >= reg_start_pos then
-- Expand razor edit to item_start_pos if below limit
local _, _, _, beat = reaper.TimeMap2_timeToBeats(0, item_start_pos)
if reg_start_beat - beat < expand_beat_limit + 0.0001 then
raz_start_pos = item_start_pos
end
else
-- Shrink razor edit to item_end_pos if below limit
local _, _, _, beat = reaper.TimeMap2_timeToBeats(0, item_end_pos)
if beat - reg_start_beat < shrink_beat_limit + 0.0001 then
raz_start_pos = item_end_pos
end
end
end
-- Check if item crosses end of region
if item_start_pos < reg_end_pos and item_end_pos > reg_end_pos then
if item_mid_pos <= reg_end_pos then
-- Expand razor edit to item_end_pos if below limit
local _, _, _, beat = reaper.TimeMap2_timeToBeats(0, item_end_pos)
if beat - reg_end_beat < expand_beat_limit + 0.0001 then
raz_end_pos = item_end_pos
end
else
-- Shrink razor edit to item_start_pos if below limit
local _, _, _, beat = reaper.TimeMap2_timeToBeats(0, item_start_pos)
if reg_end_beat - beat < shrink_beat_limit + 0.0001 then
raz_end_pos = item_start_pos
end
end
end
if item_start_pos > reg_end_pos then
break
end
end
local raz_edit = raz_start_pos .. ' ' .. raz_end_pos .. ' ""'
reaper.GetSetMediaTrackInfo_String(track, 'P_RAZOREDITS', raz_edit, true)
end
reaper.Undo_EndBlock('Create razor edit from region under mouse', -1)
|
local CRYPT = require "lcrypt"
local uuid = CRYPT.uuid
local guid = CRYPT.guid
local sys = require "sys"
local now = sys.now
local hostname = sys.hostname
local modf = math.modf
local ID = {}
-- UUID v4实现
function ID.uuid()
return uuid()
end
-- hash(主机名)-时间戳-微秒-(1~65535的随机数)
function ID.guid(host)
local hi, lo = modf(now())
return guid(host or hostname(), hi, lo * 1e4 // 1)
end
-- 初始化函数
return function (t)
for k, v in pairs(ID) do
t[k] = v
end
return ID
end
|
-- Swordburst 2
local Page = MagmaHub:addPage("Swordburst 2")
-- Services
local Players = game:GetService("Players")
-- Variables
local LocalPlayer = Players.LocalPlayer
-- Big Hit Box
local BigHitBox = Page:addToggle("Big Hit Box", nil, function ()
for _,v in pairs(game.Workspace.Mobs:children()) do
if v:FindFirstChild("Head") then
v.HumanoidRootPart.Transparency = 1
v.HumanoidRootPart.Size = Vector3.new(10, 10, 10)
end
end
end)
Threads:Add(function()
while wait() do
if BigHitBox:IsEnabeld() then
for _,v in pairs(game.Workspace.Mobs:children()) do
if v ~= nil and v:FindFirstChild("Head") and v:FindFirstChild("HumanoidRootPart") then
v.HumanoidRootPart.Transparency = 0.25
v.HumanoidRootPart.Size = Vector3.new(30, 25, 30)
if BigHitBox:IsEnabeld() == false then break end
end
end
end
end
end)
-- Reach
Page:addButton("Reach", function ()
if LocalPlayer.Character then
for _,p in pairs(LocalPlayer.Character:GetChildren()) do
if p.Name == "RightWeapon" or p.Name == "LeftWeapon" then
for _,v in pairs(p.Tool:GetChildren()) do
v.Size = Vector3.new(50, 50, 50)
v.Transparency = 1
end
end
end
end
end)
-- Infinite Stamina
local InfiniteStamina = Page:addToggle("Infinite Stamina")
Threads:Add(function()
while wait() do
if InfiniteStamina:IsEnabeld() then
if LocalPlayer.Character then
LocalPlayer.Character:WaitForChild("Entity").Stamina.Value = 100
end
end
end
end)
-- Unlock All Gamepasses and AnimPacks
Page:addButton("Unlock All Gamepasses and AnimPacks", function ()
local Profile = game.ReplicatedStorage.Profiles[LocalPlayer.Name]
-- Gamepasses
local CustomClothing = Instance.new("BoolValue", Profile.Gamepasses)
CustomClothing.Name = "CustomClothing"
-- AnimPacks
local Berserker = Instance.new("StringValue", Profile.AnimPacks)
Berserker.Name = "Berserker"
Berserker.Value = "2HSword"
local Ninja = Instance.new("StringValue", Profile.AnimPacks)
Ninja.Name = "Ninja"
Ninja.Value = "Katana"
local Vigilante = Instance.new("StringValue", Profile.AnimPacks)
Vigilante.Name = "Vigilante"
Vigilante.Value = "DualWield"
local Noble = Instance.new("StringValue", Profile.AnimPacks)
Noble.Name = "Noble"
Noble.Value = "SingleSword"
-- Fix AnimPacks Settings
local AnimPacksSettings = LocalPlayer:WaitForChild("PlayerGui").CardinalUI.PlayerUI.MainFrame.TabFrames.Settings.AnimPacks
AnimPacksSettings.ChildAdded:Connect(function(child)
if child.Text == "[2HSword]Berserker" then
child.MouseButton1Click:Connect(function()
if child.BackgroundColor3 == Color3.new() then
Profile.AnimSettings["2HSword"].Value = "Berserker"
else
Profile.AnimSettings["2HSword"].Value = ""
end
end)
elseif child.Text == "[Katana]Ninja" then
child.MouseButton1Click:Connect(function()
if child.BackgroundColor3 == Color3.new() then
Profile.AnimSettings["Katana"].Value = "Ninja"
else
Profile.AnimSettings["Katana"].Value = ""
end
end)
elseif child.Text == "[DualWield]Vigilante" then
child.MouseButton1Click:Connect(function()
if child.BackgroundColor3 == Color3.new() then
Profile.AnimSettings["DualWield"].Value = "Vigilante"
else
Profile.AnimSettings["DualWield"].Value = ""
end
end)
elseif child.Text == "[SingleSword]Noble" then
child.MouseButton1Click:Connect(function()
if child.BackgroundColor3 == Color3.new() then
Profile.AnimSettings["SingleSword"].Value = "Noble"
else
Profile.AnimSettings["SingleSword"].Value = ""
end
end)
end
end)
end)
-- Dismantle All
Page:addInput("Dismantle All", function (inp)
for _,item in pairs(game.ReplicatedStorage.Profiles[LocalPlayer.Name].Inventory:GetChildren()) do
if item.Name == inp then
game.ReplicatedStorage.Event:FireServer("Equipment", {"Dismantle", item})
print('Dismantled: "'..inp..'" #'..item.Value)
end
end
end)
-- Max Upgrade
Page:addInput("Max Upgrade", function (inp)
local item = game.ReplicatedStorage.Profiles[LocalPlayer.Name].Inventory:FindFirstChild(inp)
if item then
for _ = 1, 100 do
game.ReplicatedStorage.Event:FireServer("Equipment", {"Upgrade", item, false})
end
print('Max Upgraded: "'..inp..'" #'..item.Value)
end
end)
-- Teleports
local Teleports = MagmaHub:addPage("Teleports")
local TeleportSystemCount = 1
for _, TeleportSystem in pairs(game.Workspace:GetChildren()) do
if TeleportSystem.Name == "TeleportSystem" then
local PartCount = 1
local CurrentTeleportSystemCount = TeleportSystemCount
for _, Part in pairs(TeleportSystem:GetChildren()) do
Teleports:addButton(tostring(CurrentTeleportSystemCount).." : "..PartCount, function()
if firetouchinterest == nil then
LocalPlayer.Character.HumanoidRootPart.CFrame = Part.CFrame
else
firetouchinterest(LocalPlayer.Character.HumanoidRootPart, Part, 0)
wait()
firetouchinterest(LocalPlayer.Character.HumanoidRootPart, Part, 1)
end
end)
PartCount = PartCount + 1
end
TeleportSystem.ChildAdded:Connect(function(child)
Teleports:addButton(tostring(CurrentTeleportSystemCount).." : "..PartCount, function()
if firetouchinterest == nil then
LocalPlayer.Character.HumanoidRootPart.CFrame = child.CFrame
else
firetouchinterest(LocalPlayer.Character.HumanoidRootPart, child, 0)
wait()
firetouchinterest(LocalPlayer.Character.HumanoidRootPart, child, 1)
end
end)
PartCount = PartCount + 1
end)
TeleportSystemCount = TeleportSystemCount + 1
end
end
|
--[[ File Writer ]]--
local fileWriter = {}
local writer = require 'writer'
--[[ First prep
> o (table) output
> m (table) module
]]
local function prepareModule(o, m)
o.fields = m.params
o.body.text = '\n### ' .. m.returns.name .. '\n'
o.header.text = '# ' .. m.title .. '\n'
if m.description then o.header:write('\n' .. m.description .. '\n') end
o.header:write('\n## Contents\n')
o.footer:write(
'/README.md)\n\n[string]: https://www.lua.org/manual/5.1/manual.html#5.4\n'
.. '[table]: https://www.lua.org/manual/5.1/manual.html#5.5\n\n'
)
o.footer:write('[' .. m.returns.name .. ']: #' .. m.returns.name:lower())
o.header:write('\n- _Fields_\n - **[' .. m.returns.name .. '][]')
if m.returns.typing then
o.header:write(' : [' .. m.returns.typing .. '][]**')
o.body:write('\nExtends: **[' .. m.returns.typing .. '][]**\n')
else
o.header:write('**')
end
o.body:write('\nRequires: **none**\n')
o.header:write('\n - `No requirements`')
end
--[[ Second prep
> o (table) output
> f (table) field
> m (table) module
]]
local function prepareField(o, f, m)
o.header:write('\n - **[' .. m.returns.name .. '][].' .. f.name)
o.body:write('\n→ `' .. f.name .. '`')
if f.typing then
o.header:write(' : ' .. f.typing .. '')
o.body:write(' **' .. f.typing .. '**')
end
if f.default then
if f.default == '' then
o.header:write(' = _nil_')
o.body:write(' _[optional]_')
else
o.header:write(' = ' .. f.default)
o.body:write(' _[' .. f.default .. ']_')
end
end
if f.title then
o.header:write('**\n - `' .. f.title .. '`')
o.body:write('\n`' .. f.title .. '`')
else
o.header:write('**')
end
o.body:write('\n')
end
--[[ Third prep
> o (table) output
> m (table) method
> mod (table) module
]]
local function prepareMethods(o, m, mod)
-- WARNING probably I must add sorting here but it looks like already sorted
local orderedReturns = {}
for name, ret in pairs(m.returns or {}) do
orderedReturns[ret.order] = ret
orderedReturns[ret.order].name = name
end
m.name = m.name:gsub('^' .. mod.name, mod.returns.name)
o.header:write(' - **[' .. m.name .. '][] (')
local first = true
for name, arg in pairs(m.params or {}) do
if not first then o.header:write(', ') end
o.header:write(name)
if not arg.default then o.header:write('\\*') end
first = false
end
o.header:write(')')
first = true
for _, ret in pairs(orderedReturns) do
if first then
o.header:write(' : ')
else
o.header:write(', ')
end
o.header:write(ret.typing)
first = false
end
o.header:write('**')
o.body:write('\n### ' .. m.name .. '\n')
o.footer:write('\n[' .. m.name .. ']: #' ..
m.name:lower():gsub('%p', '') .. '\n')
o.header:write('\n')
if m.title then
o.header:write(' - `' .. m.title .. '`\n')
o.body:write('\n' .. m.title .. '\n')
end
if m.description then
o.body:write('\n> ' .. m.description:gsub('\n', '\n> ') .. '\n')
end
local function universal(name, any)
o.body:write('`' .. name .. '`')
if any.typing then
o.body:write(' : **' .. any.typing .. '**')
end
if any.default then
if any.default == '' then
any.default = 'optional'
end
o.body:write(' _[' .. any.default .. ']_')
end
if any.title then
o.body:write('\n`' .. any.title .. '`')
end
end
for name, arg in pairs(m.params or {}) do
o.body:write('\n→ ')
universal(name, arg)
o.body:write('\n')
end
for _, ret in pairs(orderedReturns) do
o.body:write('\n← ')
universal(ret.name, ret)
o.body:write('\n')
end
end
--[[ Write file
> reqPath (string)
> module (table)
]]
function fileWriter.write(reqPath, module)
local data = module.files[reqPath]
if not data.module then return end
local file = writer.open(module.config.outPath .. '/' .. reqPath .. '.md')
if not file then return end
local write = function(self, text) self.text = self.text .. text end
local output = {
methods = {},
header = { write = write },
body = { write = write },
footer = { write = write },
}
output.footer.text = '\n## Footer\n\n[Back to root](' ..
module.config.rootPath .. '/' .. module.config.outPath
data.module.returns = data.module.returns or {}
data.module.returns.name = data.module.returns.name or data.module.name
prepareModule(output, data.module)
-- extract methods
for name, f in pairs(data.functions) do
f.name = name
if name:find(data.module.name .. '%p') == 1 then
output.methods[f.order] = f
end
end
for name, field in pairs(output.fields or {}) do
field.name = name
prepareField(output, field, data.module)
end
output.header:write('\n- _Methods_\n')
for _, method in pairs(output.methods or {}) do
prepareMethods(output, method, data.module)
end
file:write(output.header.text .. output.body.text .. output.footer.text)
file:close()
end
return fileWriter
|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- 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.
-- Built-in Types
---
--- The type *nil* has one single value, **nil**, whose main property is to be
--- different from any other value; it usually represents the absence of a
--- useful value.
---@class nil
---
--- The type *boolean* has two values, **false** and **true**. Both **nil** and
--- **false** make a condition false; any other value makes it true.
---@class boolean
---
--- The type *number* uses two internal representations, or two subtypes, one
--- called *integer* and the other called *float*. Lua has explicit rules about
--- when each representation is used, but it also converts between them
--- automatically as needed. Therefore, the programmer may choose to mostly
--- ignore the difference between integers and floats or to assume complete
--- control over the representation of each number. Standard Lua uses 64-bit
--- integers and double-precision (64-bit) floats, but you can also compile
--- Lua so that it uses 32-bit integers and/or single-precision (32-bit)
--- floats. The option with 32 bits for both integers and floats is
--- particularly attractive for small machines and embedded systems. (See
--- macro LUA_32BITS in file luaconf.h.)
---@class number
---
--- Lua can call (and manipulate) functions written in Lua and functions
--- written in C. Both are represented by the type *function*.
---@class function
---
--- The type *userdata* is provided to allow arbitrary C data to be stored in
--- Lua variables. A userdata value represents a block of raw memory. There
--- are two kinds of userdata: *full userdata*, which is an object with a block
--- of memory managed by Lua, and *light userdata*, which is simply a C pointer
--- value. Userdata has no predefined operations in Lua, except assignment
--- and identity test. By using *metatables*, the programmer can define
--- operations for full userdata values. Userdata values cannot be
--- created or modified in Lua, only through the C API. This guarantees the
--- integrity of data owned by the host program.
---@class userdata
---
--- The type *thread* represents independent threads of execution and it is
--- used to implement coroutines. Lua threads are not related to
--- operating-system threads. Lua supports coroutines on all systems, even those
--- that do not support threads natively.
---@class thread
---
--- The type *table* implements associative arrays, that is, arrays that can
--- have as indices not only numbers, but any Lua value except **nil** and NaN.
--- (*Not a Number* is a special floating-point value used by the IEEE 754
--- standard to represent undefined or unrepresentable numerical results, such
--- as `0/0`.) Tables can be heterogeneous; that is, they can contain values of
--- all types (except **nil**). Any key with value **nil** is not considered
--- part oft he table. Conversely, any key that is not part of a table has an
--- a ssociated value **nil**.
---
--- Tables are the sole data-structuring mechanism in Lua; they can be used to
--- represent ordinary arrays, lists, symbol tables, sets, records, graphs,
--- trees, etc. To represent records, Lua uses the field name as an index. The
--- language supports this representation by providing `a.name` as syntactic
--- sugar for `a["name"]`. There are several convenient ways to create tables
--- in Lua.
---
--- Like indices, the values of table fields can be of any type. In particular,
--- because functions are first-class values, table fields can contain functions.
--- Thus tables can also carry *methods*.
---
--- The indexing of tables follows the definition of raw equality in the
--- language. The expressions `a[i]` and `a[j]` denote the same table element
--- if and only if `i` and `j` are raw equal (that is, equal without
--- metamethods). In particular, floats with integral values are equal to
--- their respective integers. To avoid ambiguities, any float with integral
--- value used as a key is converted to its respective integer. For instance,
--- if you write `a[2.0] = true`, the actual key inserted into the table will
--- be the integer `2`. (On the other hand, 2 and "`2`" are different Lua
--- values and therefore denote different table entries.)
---@class table
---
--- Any of the above Built-in Types.
---@class any
---
---@class void
|
--[[
grid of cells that store a template for rendering and a solid mask
written in a pretty inefficient way for now :)
]]
--config
local cell_size = vec2(3, 3)
local space_glyph = (" "):byte(1)
--doesn't actually rely on grid
local function parse_template(template, f)
local z = #template - 1
for _, lines in ipairs(template) do
local w = 0
for i, v in ipairs(lines) do
if type(v) == "string" then
w = math.max(w, #v)
end
end
local h = #lines
local cx = math.floor((cell_size.x - w) / 2)
local cy = math.floor((cell_size.y - h) / 2)
local colour = 0xff00ff
local i = 0
for _, v in ipairs(lines) do
if type(v) == "number" then
--new line colour
colour = v
else
--new template line
i = i + 1
local line = v
local oy = i + cy - 1
for j = 1, #line do
local ox = j + cx - 1
local glyph = line:byte(j)
if glyph ~= space_glyph then
f(ox, oy, z, glyph, colour)
end
end
end
end
--inverse z order
z = z - 1
end
end
--cells are now fairly vestigial, could be refactored into just grid
local cell = class({
name = "cell",
})
function cell:new(x, y)
self.pos = vec2(x, y) --could be implicit
self.template = false
self.solid = false
self.type = "empty"
self.elevation = 0
end
local _inline_celldraw_display
local _inline_celldraw_self
local _inline_celldraw_x
local _inline_celldraw_y
local function _inline_celldraw(ox, oy, z, glyph, colour)
_inline_celldraw_display:add(
_inline_celldraw_x + ox,
_inline_celldraw_y + oy,
z + _inline_celldraw_self.elevation,
glyph, colour
)
end
function cell:draw(display)
if not self.template then
return
end
_inline_celldraw_x = self.pos.x * cell_size.x
_inline_celldraw_y = self.pos.y * cell_size.y
_inline_celldraw_display = display
_inline_celldraw_self = self
parse_template(self.template, _inline_celldraw)
end
local grid = class({
name = "grid",
})
function grid:new(w, h)
self.size = vec2(w, h)
self.cells = functional.generate(self.size.y, function(y)
return functional.generate(self.size.x, function(x)
return cell(x, y)
end)
end)
end
function grid:draw(display, near)
local halfsize = vec2(love.graphics.getDimensions())
:vdivi(cell_size)
:vdivi(display.tile_size)
:sdivi(ZOOM_LEVEL)
:sdivi(2) --halfsize
:saddi(2) --pad margin in case of tall tiles
for _, row in ipairs(self.cells) do
for _, v in ipairs(row) do
if intersect.aabb_point_overlap(near, halfsize, v.pos) then
v:draw(display)
end
end
end
end
function grid:cell(x, y)
x = math.floor(x)
y = math.floor(y)
assert(self:in_bounds(x, y), "attempt to get cell out of bounds")
return self.cells[y][x]
end
function grid:clear(x, y)
self:cell(x, y):clear()
end
function grid:set(x, y, template, solid, type, elevation)
local cell = self:cell(x, y)
cell.template = template
cell.solid = solid
cell.type = type or (solid and "wall" or "empty")
cell.elevation = elevation or 0
end
function grid:in_bounds(x, y)
return (x > 0 and x <= self.size.x)
and (y > 0 and y <= self.size.y)
end
function grid:solid_at(x, y)
return not self:in_bounds(x, y) or self:cell(x, y).solid
end
function grid:water_at(x, y)
return self:in_bounds(x, y) and self:cell(x, y).type == "water"
end
--export
grid.cell_size = cell_size
grid.parse_template = parse_template
return grid
|
local Buffer, _, method = class('Buffer')
Buffer.__description = "Modified version of Luvit's low-level buffer class."
local ffi = require('ffi')
local concat = table.concat
local gc, cast, ffi_copy, ffi_string = ffi.gc, ffi.cast, ffi.copy, ffi.string
local lshift, rshift, tohex, tobit = bit.lshift, bit.rshift, bit.tohex, bit.tobit
ffi.cdef[[
void *malloc(size_t size);
void *calloc(size_t num, size_t size);
void *realloc(void *ptr, size_t size);
void free(void *ptr);
]]
local C = ffi.os == 'Windows' and ffi.load('msvcrt') or ffi.C
function Buffer:__init(arg)
if type(arg) == 'number' then
self._len = arg
self._cdata = gc(cast('unsigned char*', C.calloc(arg, 1)), C.free)
elseif type(arg) == 'string' then
self._len = #arg
self._cdata = gc(cast("unsigned char*", C.calloc(self._len, 1)), C.free)
ffi_copy(self._cdata, arg, self._len)
end
end
function Buffer:__tostring()
return ffi_string(self._cdata, self._len)
end
function Buffer:__len()
return self._len
end
local function get(self, k)
if k < 0 or k > self._len then
return error('buffer index out of bounds')
end
return self._cdata[k]
end
local function set(self, k, v)
if k < 0 or k > self._len then
return error('buffer index out of bounds')
end
self._cdata[k] = v
end
local function complement8(value)
return value < 0x80 and value or value - 0x100
end
local function complement16(value)
return value < 0x8000 and value or value - 0x10000
end
local function readUInt8(self, k)
return get(self, k)
end
local function readUInt16LE(self, k)
return get(self, k) + lshift(get(self, k + 1), 8)
end
local function readUInt16BE(self, k)
return lshift(get(self, k), 8) + get(self, k + 1)
end
local function readUInt32LE(self, k)
return get(self, k) + lshift(get(self, k + 1), 8) + lshift(get(self, k + 2), 16) + get(self, k + 3) * 0x1000000
end
local function readUInt32BE(self, k)
return get(self, k) * 0x1000000 + lshift(get(self, k + 1), 16) + lshift(get(self, k + 2), 8) + get(self, k + 3)
end
local function readInt8(self, k)
return complement8(readUInt8(self, k))
end
local function readInt16LE(self, k)
return complement16(readUInt16LE(self, k))
end
local function readInt16BE(self, k)
return complement16(readUInt16BE(self, k))
end
local function readInt32LE(self, k)
tobit(readInt32LE(self, k))
end
local function readInt32BE(self, k)
tobit(readInt32BE(self, k))
end
local function readString(self, k, len)
k = k or 0
len = len or self._len - k
return ffi_string(self._cdata + k, len)
end
local function writeUInt8(self, k, v)
set(self, k, rshift(v, 0))
end
local function writeUInt16LE(self, k, v)
set(self, k, rshift(v, 0))
set(self, k + 1, rshift(v, 8))
end
local function writeUInt16BE(self, k, v)
set(self, k, rshift(v, 8))
set(self, k + 1, rshift(v, 0))
end
local function writeUInt32LE(self, k, v)
set(self, k, rshift(v, 0))
set(self, k + 1, rshift(v, 8))
set(self, k + 2, rshift(v, 16))
set(self, k + 3, rshift(v, 24))
end
local function writeUInt32BE(self, k, v)
set(self, k, rshift(v, 24))
set(self, k + 1, rshift(v, 16))
set(self, k + 2, rshift(v, 8))
set(self, k + 3, rshift(v, 0))
end
local function writeString(self, k, str, len)
k = k or 0
len = len or #str
ffi_copy(self._cdata + k, str, len)
end
local function toString(self, i, j)
i = i or 0
j = j or self._len
return ffi_string(self._cdata + i, j - i)
end
local function toHex(self, i, j)
local str = {}
i = i or 0
j = j or self._len
for n = i, j - 1 do
str[n + 1] = tohex(get(self, n), 2)
end
return concat(str, ' ')
end
local function copy(self, target, targetStart, sourceStart, sourceEnd)
targetStart = targetStart or 0
sourceStart = sourceStart or 0
sourceEnd = sourceEnd or self._len
local len = sourceEnd - sourceStart
ffi_copy(target._cdata + targetStart, self._cdata + sourceStart, len)
end
method('readUInt8', readUInt8, 'offset', 'Reads an unsigned 8-bit integer from the buffer')
method('readUInt16LE', readUInt16LE, 'offset', 'Reads an unsigned 16-bit little-endian integer from the buffer')
method('readUInt16BE', readUInt16BE, 'offset', 'Reads an unsigned 16-bit big-endian integer from the buffer')
method('readUInt32LE', readUInt32LE, 'offset', 'Reads an unsigned 32-bit little-endian integer from the buffer')
method('readUInt32BE', readUInt32BE, 'offset', 'Reads an unsigned 32-bit big-endian integer from the buffer')
method('readInt8', readInt8, 'offset', 'Reads a signed 8-bit integer from the buffer')
method('readInt16LE', readInt16LE, 'offset', 'Reads a signed 16-bit little-endian integer from the buffer')
method('readInt16BE', readInt16BE, 'offset', 'Reads a signed 16-bit big-endian integer from the buffer')
method('readInt32LE', readInt32LE, 'offset', 'Reads a signed 32-bit little-endian integer from the buffer')
method('readInt32BE', readInt32BE, 'offset', 'Reads a signed 32-bit big-endian integer from the buffer')
method('readString', readString, '[offset, len]', 'Reads a Lua string from the buffer')
method('writeUInt8', writeUInt8, 'offset', 'Writes an unsigned 8-bit integer to the buffer')
method('writeUInt16LE', writeUInt16LE, 'offset', 'Writes an unsigned 16-bit little-endian integer to the buffer')
method('writeUInt16BE', writeUInt16BE, 'offset', 'Writes an unsigned 16-bit big-endian integer to the buffer')
method('writeUInt32LE', writeUInt32LE, 'offset', 'Writes an unsigned 32-bit little-endian integer to the buffer')
method('writeUInt32BE', writeUInt32BE, 'offset', 'Writes an unsigned 32-bit big-endian integer to the buffer')
method('writeInt8', writeUInt8, 'offset', 'Writes an unsigned 8-bit integer to the buffer')
method('writeInt16LE', writeUInt16LE, 'offset', 'Writes a signed 16-bit little-endian integer to the buffer')
method('writeInt16BE', writeUInt16BE, 'offset', 'Writes a signed 16-bit big-endian integer to the buffer')
method('writeInt32LE', writeUInt32LE, 'offset', 'Writes a signed 32-bit little-endian integer to the buffer')
method('writeInt32BE', writeUInt32BE, 'offset', 'Writes a signed 32-bit big-endian integer to the buffer')
method('writeString', writeString, 'offset, string[, len]', 'Writes a Lua string to the buffer')
method('toString', toString, '[i, j]', 'Returns a slice of the buffer as a raw string')
method('toHex', toHex, '[i, j]', 'Returns a slice of the buffer as a hex string')
method('copy', copy, 'target[, targetStart, sourceStart, sourceEnd]', 'Copies a slice of the buffer into another buffer')
return Buffer
|
include("shared.lua")
--------------------------------------------------------------------------------
ENT.ClientProps = {}
ENT.ButtonMap = {}
ENT.ButtonMap["FrontPneumatic"] = {
pos = Vector(460.0,-45.0,-50.0),
ang = Angle(0,90,90),
width = 900,
height = 100,
scale = 0.1,
}
ENT.ButtonMap["RearPneumatic"] = {
pos = Vector(-483.0,45.0,-50.0),
ang = Angle(0,270,90),
width = 900,
height = 100,
scale = 0.1,
}
ENT.ButtonMap["Test1"] = {
pos = Vector(460.0,-15,46.5),
ang = Angle(0,90,90),
width = 32,
height = 96,
scale = 1,
}
ENT.ButtonMap["AirDistributor"] = {
pos = Vector(-180,70,-50),
ang = Angle(0,180,90),
width = 80,
height = 40,
scale = 0.1,
}
-- Wagon numbers
ENT.ButtonMap["TrainNumber1"] = {
pos = Vector(30,-67.6,-12),
ang = Angle(0,0,90),
width = 130,
height = 55,
scale = 0.20,
}
ENT.ButtonMap["TrainNumber2"] = {
pos = Vector(30+28,67.7,-12),
ang = Angle(0,180,90),
width = 130,
height = 55,
scale = 0.20,
}
--------------------------------------------------------------------------------
ENT.ClientPropsInitialized = false
ENT.ClientProps["train_line"] = {
model = "models/metrostroi/81-717/black_arrow.mdl",
pos = Vector(447.10,-14.4,58),
ang = Angle(90,0,180)
}
ENT.ClientProps["brake_line"] = {
model = "models/metrostroi/81-717/red_arrow.mdl",
pos = Vector(447.00,-14.4,58),
ang = Angle(90,0,180)
}
ENT.ClientProps["brake_cylinder"] = {
model = "models/metrostroi/81-717/black_arrow.mdl",
pos =Vector(447.10,-18.8,57.9),
ang = Angle(90,0,180)
}
--------------------------------------------------------------------------------
ENT.ClientProps["ampermeter"] = {
model = "models/metrostroi/81-717/black_arrow.mdl",
pos = Vector(447.00,11.0,57.3),
ang = Angle(90,0,180)
}
ENT.ClientProps["voltmeter"] = {
model = "models/metrostroi/81-717/black_arrow.mdl",
pos = Vector(447.00,15.5,57.3),
ang = Angle(90,0,180)
}
ENT.ClientProps["volt1"] = {
model = "models/metrostroi/81-717/black_arrow.mdl",
pos = Vector(447.00,-9.7,58),
ang = Angle(90,0,180)
}
--------------------------------------------------------------------------------
ENT.ClientProps["battery"] = {
model = "models/metrostroi/81-717/switch01.mdl",
pos = Vector(446.0,0.0,55),
ang = Angle(90,0,180)
}
ENT.ClientProps["gv"] = {
model = "models/metrostroi/81-717/gv.mdl",
pos = Vector(154,62.5+1.5,-65),
ang = Angle(-90,0,-90)
}
ENT.ClientProps["gv_wrench"] = {
model = "models/metrostroi/81-717/reverser.mdl",
pos = Vector(154,62.5+1.5,-65),
ang = Angle(0,0,0)
}
--------------------------------------------------------------------------------
--[[for x=0,11 do
for y=0,3 do
ENT.ClientProps["a"..(x+12*y)] = {
model = "models/metrostroi/81-717/circuit_breaker.mdl",
pos = Vector(393.8,-52.5+x*2.75,37.5-y*8),
ang = Angle(90,0,0)
}
end
end]]--
--[[Metrostroi.ClientPropForButton("battery",{
panel = "Battery",
button = "VBToggle",
model = "models/metrostroi/81-717/switch01.mdl",
z = -10.7,
})]]--
--------------------------------------------------------------------------------
-- Add doors
local function GetDoorPosition(i,k,j)
if j == 0
then return Vector(351.0 - 34*k - 231*i,-65*(1-2*k),-2.8)
else return Vector(351.0 - 34*(1-k) - 231*i,-65*(1-2*k),-2.8)
end
end
for i=0,3 do
for k=0,1 do
ENT.ClientProps["door"..i.."x"..k.."a"] = {
model = "models/metrostroi/e/em508_door1.mdl",
pos = GetDoorPosition(i,k,0),
ang = Angle(0,180*k,0)
}
ENT.ClientProps["door"..i.."x"..k.."b"] = {
model = "models/metrostroi/e/em508_door2.mdl",
pos = GetDoorPosition(i,k,1),
ang = Angle(0,180*k,0)
}
end
end
ENT.ClientProps["door1"] = {
model = "models/metrostroi/e/em508_door5.mdl",
pos = Vector(455.5,0.5,-5),
ang = Angle(0,0,0)
}
ENT.ClientProps["door2"] = {
model = "models/metrostroi/e/em508_door5.mdl",
pos = Vector(-479.5,.0,-5),
ang = Angle(0,180,0)
}
ENT.FrontDoor = 0
ENT.RearDoor = 0
ENT.PassengerDoor = 0
ENT.CabinDoor = 0
--------------------------------------------------------------------------------
function ENT:UpdateTextures()
local texture = Metrostroi.Skins["train"][self:GetNW2String("texture")]
local passtexture = Metrostroi.Skins["pass"][self:GetNW2String("passtexture")]
local cabintexture = Metrostroi.Skins["cab"][self:GetNW2String("cabtexture")]
for _,ent in pairs(self.ClientEnts) do
if not IsValid(ent) then continue end
for k,v in pairs(ent:GetMaterials()) do
local tex = string.Explode("/",v)
tex = tex[#tex]
if cabintexture and cabintexture.textures[tex] then
ent:SetSubMaterial(k-1,cabintexture.textures[tex])
end
if passtexture and passtexture.textures[tex] then
ent:SetSubMaterial(k-1,passtexture.textures[tex])
end
if texture and texture.textures[tex] then
ent:SetSubMaterial(k-1,texture.textures[tex])
end
end
end
end
--------------------------------------------------------------------------------
function ENT:Think()
self.BaseClass.Think(self)
if self.Texture ~= self:GetNW2String("texture") then
self.Texture = self:GetNW2String("texture")
self:UpdateTextures()
end
if self.PassTexture ~= self:GetNW2String("passtexture") then
self.PassTexture = self:GetNW2String("passtexture")
self:UpdateTextures()
end
if self.CabinTexture ~= self:GetNW2String("cabtexture") then
self.CabinTexture = self:GetNW2String("cabtexture")
self:UpdateTextures()
end
if self.RearDoor < 90 and self:GetPackedBool(156) or self.RearDoor > 0 and not self:GetPackedBool(156) then
local RearDoorData = self.ClientProps["door2"]
--RearDoor:SetLocalPos(RearDoorData.pos + Vector(-2,-0,0))
self.RearDoor = math.max(0,math.min(90,self.RearDoor + (self:GetPackedBool(156) and 1 or -1)*self.DeltaTime*180))
end
if not self.ClientPropsMatrix["door2"] or self.ClientPropsMatrix["door2"]:GetAngles().yaw ~= self.RearDoor then
self:ApplyMatrix("door2",Vector(0,-16,0),Angle(0,self.RearDoor,0))
end
if self.FrontDoor < 90 and self:GetPackedBool(157) or self.FrontDoor > 0 and not self:GetPackedBool(157) then
local FrontDoorData = self.ClientProps["door1"]
--FrontDoor:SetLocalPos(FrontDoorData.pos + Vector(-2,-0,0))
self.FrontDoor = math.max(0,math.min(90,self.FrontDoor + (self:GetPackedBool(157) and 1 or -1)*self.DeltaTime*180))
self:ApplyMatrix("door1",Vector(0,-16,0),Angle(0,self.FrontDoor,0))
end
if not self.ClientPropsMatrix["door1"] or self.ClientPropsMatrix["door1"]:GetAngles().yaw ~= self.FrontDoor then
self:ApplyMatrix("door1",Vector(0,-16,0),Angle(0,self.FrontDoor,0))
end
local transient = (self.Transient or 0)*0.05
if (self.Transient or 0) ~= 0.0 then self.Transient = 0.0 end
-- Simulate pressure gauges getting stuck a little
--self:Animate("brake", self:GetPackedRatio(0)^0.5, 0.00, 0.65, 256,24)
--self:Animate("controller", self:GetPackedRatio(1), 0.30, 0.70, 384,24)
--self:Animate("reverser", 1-self:GetPackedRatio(2), 0.25, 0.75, 4,false)
self:Animate("volt1", self:GetPackedRatio(10), 0.38,0.64)
--self:ShowHide("reverser", self:GetPackedBool(0))
self:Animate("brake_line", self:GetPackedRatio(4), 0.16, 0.84, 256)--,,2,0.01)
self:Animate("train_line", self:GetPackedRatio(5)-transient, 0.16, 0.84, 256)--,,2,0.01)
self:Animate("brake_cylinder", self:GetPackedRatio(6), 0.17, 0.86, 256)--,,2,0.03)
self:Animate("voltmeter", self:GetPackedRatio(7), 0.38, 0.63)
self:Animate("ampermeter", self:GetPackedRatio(8), 0.38, 0.63)
--self:Animate("volt2", 0, 0.38, 0.63)
self:Animate("battery", self:GetPackedBool(7) and 1 or 0, 0,1, 16, false)
-- Animate AV switches
for i,v in ipairs(self.Panel.AVMap) do
local value = self:GetPackedBool(64+(i-1)) and 1 or 0
self:Animate("a"..(i-1),value,0,1,8,false)
end
-- Main switch
if self.LastValue ~= self:GetPackedBool(5) then
self.ResetTime = CurTime()+2.0
self.LastValue = self:GetPackedBool(5)
end
self:Animate("gv_wrench", (self:GetPackedBool(5) and 1 or 0), 0,0.51, 128, 1,false)
self:ShowHide("gv_wrench", CurTime() < self.ResetTime)
-- Animate doors
for i=0,3 do
for k=0,1 do
local n_l = "door"..i.."x"..k.."a"
local n_r = "door"..i.."x"..k.."b"
local animation = self:Animate(n_l,self:GetPackedBool(21+i+4-k*4) and 1 or 0,0,1, 0.8 + (-0.2+0.4*math.random()),0)
local offset_l = Vector(math.abs(31*animation),0,0)
local offset_r = Vector(math.abs(32*animation),0,0)
if self.ClientEnts[n_l] then
self.ClientEnts[n_l]:SetPos(self:LocalToWorld(self.ClientProps[n_l].pos + (1.0 - 2.0*k)*offset_l))
self.ClientEnts[n_l]:SetSkin(self:GetSkin())
end
if self.ClientEnts[n_r] then
self.ClientEnts[n_r]:SetPos(self:LocalToWorld(self.ClientProps[n_r].pos - (1.0 - 2.0*k)*offset_r))
self.ClientEnts[n_r]:SetSkin(self:GetSkin())
end
end
end
if self.ClientEnts["door1"] then self.ClientEnts["door1"]:SetSkin(self:GetSkin()) end
if self.ClientEnts["door2"] then self.ClientEnts["door2"]:SetSkin(self:GetSkin()) end
-- Brake-related sounds
local brakeLinedPdT = self:GetPackedRatio(9)
local dT = self.DeltaTime
self.BrakeLineRamp1 = self.BrakeLineRamp1 or 0
if (brakeLinedPdT > -0.001)
then self.BrakeLineRamp1 = self.BrakeLineRamp1 + 4.0*(0-self.BrakeLineRamp1)*dT
else self.BrakeLineRamp1 = self.BrakeLineRamp1 + 4.0*((-0.6*brakeLinedPdT)-self.BrakeLineRamp1)*dT
end
self.BrakeLineRamp1 = math.Clamp(self.BrakeLineRamp1,0,1)
self:SetSoundState("release2_w",self.BrakeLineRamp1^1.65,1.0)
self.BrakeLineRamp2 = self.BrakeLineRamp2 or 0
if (brakeLinedPdT < 0.001)
then self.BrakeLineRamp2 = self.BrakeLineRamp2 + 4.0*(0-self.BrakeLineRamp2)*dT
else self.BrakeLineRamp2 = self.BrakeLineRamp2 + 8.0*(0.1*brakeLinedPdT-self.BrakeLineRamp2)*dT
end
self.BrakeLineRamp2 = math.Clamp(self.BrakeLineRamp2,0,1)
self:SetSoundState("release3_w",self.BrakeLineRamp2 + math.max(0,self.BrakeLineRamp1/2-0.15),1.0)
self:SetSoundState("cran1_w",math.min(1,self:GetPackedRatio(4)/50*(self:GetPackedBool(6) and 1 or 0)),1.0)
-- Compressor
local state = self:GetPackedBool(20)
self.PreviousCompressorState = self.PreviousCompressorState or false
if self.PreviousCompressorState ~= state then
self.PreviousCompressorState = state
if state then
self:SetSoundState("compressor_ezh",1,1)
else
self:SetSoundState("compressor_ezh",0,1)
self:SetSoundState("compressor_ezh_end",0,1)
self:SetSoundState("compressor_ezh_end",1,1)
--self:PlayOnce("compressor_e_end",nil,1,nil,true)
end
end
-- RK rotation
if self:GetPackedBool(112) then self.RKTimer = CurTime() end
local state = (CurTime() - (self.RKTimer or 0)) < 0.2
self.PreviousRKState = self.PreviousRKState or false
if self.PreviousRKState ~= state then
self.PreviousRKState = state
if state then
self:SetSoundState("rk_spin",0.7,1,nil,0.75)
else
self:SetSoundState("rk_spin",0,0,nil,0.75)
self:SetSoundState("rk_stop",0,1,nil,0.75)
self:SetSoundState("rk_stop",0.7,1,nil,0.75)
end
end
-- DIP sound
--self:SetSoundState("bpsn1",self:GetPackedBool(52) and 1 or 0,1.0)
end
function ENT:Draw()
self.BaseClass.Draw(self)
end
function ENT:DrawPost()
self:DrawOnPanel("FrontPneumatic",function()
draw.DrawText(self:GetNW2Bool("FbI") and "Isolated" or "Open","Trebuchet24",150,30,Color(0,0,0,255))
draw.DrawText(self:GetNW2Bool("FtI") and "Isolated" or "Open","Trebuchet24",650,30,Color(0,0,0,255))
draw.DrawText(self:GetPackedBool(160) and "Brake" or "Released","Trebuchet24",950,30,Color(0,0,0,255))
end)
self:DrawOnPanel("RearPneumatic",function()
draw.DrawText(self:GetNW2Bool("RbI") and "Isolated" or "Open","Trebuchet24",150,30,Color(0,0,0,255))
draw.DrawText(self:GetNW2Bool("RtI") and "Isolated" or "Open","Trebuchet24",650,30,Color(0,0,0,255))
end)
self:DrawOnPanel("AirDistributor",function()
draw.DrawText(self:GetNW2Bool("AD") and "Air Distributor ON" or "Air Distributor OFF","Trebuchet24",0,0,Color(0,0,0,255))
end)
self:DrawOnPanel("AirDistributor",function()
draw.DrawText(self:GetNW2Bool("AD") and "Air Distributor ON" or "Air Distributor OFF","Trebuchet24",0,0,Color(0,0,0,255))
end)
-- Draw train numbers
local dc = render.GetLightColor(self:GetPos())
self:DrawOnPanel("TrainNumber1",function()
draw.DrawText(Format("%04d",self:EntIndex()),"MetrostroiSubway_LargeText3",0,0,Color(255*dc.x,255*dc.y,255*dc.z,255))
end)
self:DrawOnPanel("TrainNumber2",function()
draw.DrawText(Format("%04d",self:EntIndex()),"MetrostroiSubway_LargeText3",0,0,Color(255*dc.x,255*dc.y,255*dc.z,255))
end)
--render.DrawLine( self:LocalToWorld(self.ClientProps["door1"].pos - Vector(0,16,0)), self:LocalToWorld(self.ClientProps["door1"].pos + Vector(0,16,0)), Color(0,0,255), false)
end
|
-- [Environment variables](http://en.wikipedia.org/wiki/Environment_variable)
-- are a universal mechanism for [conveying configuration
-- information to Unix programs](http://www.12factor.net/config).
-- To get a value for a key, use `os.getenv`. This will return
-- nil if the key isn't present in the environment.
print("FOO:", os.getenv("FOO"))
print("BAR:", os.getenv("BAR"))
|
----------------------------------------------------------------------
-- Various utility functions for creating unit tests in Torch for DeepBoof
--
-- Peter Abeles
----------------------------------------------------------------------
boof = {}
boof.output_base_directory = "torch_layers"
boof.float_types = {"F32","F64"}
boof.all_types = {"U8","S64","F32","F64"}
function boof.boof_to_tensor_name( boof_type )
if boof_type == "F32" then
return "torch.FloatTensor"
elseif boof_type == "F64" then
return "torch.DoubleTensor"
elseif boof_type == "S64" then
return "torch.LongTensor"
elseif boof_type == "U8" then
return "torch.ByteTensor"
elseif boof_type == "cuda" then
return "torch.CudaTensor"
else
print("Unknown/Unsupported type "..boof_type)
end
end
function boof.create_output(operation_name, data_type, variant)
local output_dir = paths.concat(boof.output_base_directory,operation_name,string.format('%s/%03d',data_type,variant))
os.execute("mkdir -p "..output_dir)
print(output_dir)
return output_dir
end
function boof.save( output_dir, input, operation, output )
torch.save(paths.concat(output_dir,'input'), input)
torch.save(paths.concat(output_dir,'operation'), operation)
torch.save(paths.concat(output_dir,'output'), output)
torch.save(paths.concat(output_dir,'input_ascii'), input, 'ascii')
torch.save(paths.concat(output_dir,'operation_ascii'), operation, 'ascii')
torch.save(paths.concat(output_dir,'output_ascii'), output, 'ascii')
end
|
--[[
R15 with constraints and animations
]]
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CCDIKController = require(ReplicatedStorage.Source.CCDIKController)
local dummy = workspace.HumanMale_Model
local leftTarget = workspace.newTargetConstraints
local dummyMotor6Ds = {}
local dummyDescendants = dummy:GetDescendants()
for _,descendant in pairs (dummyDescendants) do
if descendant:IsA("Motor6D") then
dummyMotor6Ds[descendant.Name] = descendant
end
end
local upperLeg = dummyMotor6Ds["LeftHip"]
local knee = dummyMotor6Ds["LeftKnee"]
local foot = dummyMotor6Ds["LeftAnkle"]
local leftLeg = {upperLeg,knee,foot}
local leftLegController = CCDIKController.new(leftLeg)
leftLegController:GetConstraints()
--Stepped for the CCDIK to reset the .Transform property
RunService.Stepped:Connect(function()
local goal = leftTarget.Position
leftLegController:CCDIKIterateOnce(goal,0)
end)
|
#!/usr/bin/env lua
local benchmark = require 'benchmark'
local native = require 'mtype.native'
local pure = require 'mtype.pure'
-- unpack is not global since Lua 5.3
local unpack = table.unpack or unpack --luacheck: std lua51
local type_raw = type
local type_native = native.type
local type_pure = pure.type
-- Number of iterations.
local N = 5000000
-- disable JIT when running on LuaJIT
if jit then jit.off() end
local reporter = benchmark.bm(20, nil, true)
local function measure (label, func)
-- warm up
for i=1, N / 100 do
func()
end
reporter:report(function()
for i=1, N do
func()
end
end, label)
end
local meta_str = setmetatable({}, {
__type = 'meta'
})
local meta_fun = setmetatable({
tag = 'meta'
}, {
__type = function(self)
return self.tag
end
})
for _, desc in ipairs {
{ 'number' , 42 },
{ 'string' , 'allons-y!' },
{ 'table without __type' , setmetatable({}, {}) },
{ 'table with string __type', meta_str },
{ 'table with func __type' , meta_fun },
} do
local label, value = unpack(desc)
print('-- '..label)
measure('type', function()
type_raw(value)
end)
measure('mtype (pure)', function()
type_pure(value)
end)
measure('mtype (native)', function()
type_native(value)
end)
print('')
end
|
AnimSprite = {}
AnimSprite.__index = AnimSprite
local function newAnimSprite(img, tw, th, fpt, loop, x, y)
local w, h = img:getDimensions()
local txs = w / tw
local tys = h / th
local quads = {}
for i = 0, txs do
quads[i] = {}
for j = 0, tys do
quads[i][j] = love.graphics.newQuad(i * tw, j * th, tw, th, w, h)
end
end
return setmetatable({
x = x or tw/2, y = y or th/2,
tx = 0, ty = 0,
txs = txs, tys = tys,
tw = tw, th = th,
quads = quads,
flipX = false, flipY = false,
img = img,
loop = (loop == nil and true) or loop,
fpt = fpt or 3,
time = 0
}, AnimSprite)
end
setmetatable(AnimSprite, {
__call = function(_, ...) return newAnimSprite(...) end
})
function AnimSprite:update(dt)
if not self.loop and self.tx + 1 == self.txs or self.fpt == 0 then
return
end
self.time = self.time + 1;
while (self.time > self.fpt) do
self.time = self.time - self.fpt
self.tx = (self.tx + 1) % self.txs
end
end
function AnimSprite:draw(x, y, col)
love.graphics.setColor(col or white)
love.graphics.draw(self.img,
self.quads[self.tx][self.ty],
x, y,
0,
(self.flipX and -1) or 1, (self.flipY and -1) or 1,
self.x, self.y)
end
function AnimSprite:drawSpecific(x, y, tx, ty, fx, fy, col)
love.graphics.setColor(col or white)
love.graphics.draw(self.img,
self.quads[tx][ty],
x, y,
0,
(fx and -1) or 1, (fy and -1) or 1,
self.x, self.y)
end
|
local bits = {false, false, false, false, false, false, false, false}
local val = 0
local op = 0
local function s(b)
return string.format("%3s", bits[b] and "X" or ".")
end
while true do
print(
s(8) ..
s(1) ..
s(2) ..
"\t" ..
"8 1 2" ..
"\n" ..
s(7) ..
string.format("%3s", val) ..
s(3) ..
"\t" .. "7 . 3" .. "\n" .. s(6) .. s(5) .. s(4) .. "\t" .. "6 5 4" .. "\n"
)
if op == 0 then
io.write("Introduce valor bitmasking (0 para salir): ")
op = io.read("*number")
if op == 0 then
os.exit()
end
else
io.write("Introduce valor bitmasking (0 para resetear): ")
op = io.read("*number")
if op == 0 then
bits = {false, false, false, false, false, false, false, false}
val = 0
end
end
if bits[op] ~= nil then
val = bits[op] and val - 2 ^ (op - 1) or val + 2 ^ (op - 1)
bits[op] = not bits[op]
end
end
|
module( ..., package.seeall )
local at = require "attributes"
local function pt(t)
local level=0
local function doprint(t)
for k,v in pairs(t) do
print(string.rep(" ",level) ..string.format("%s = %s",k,tostring(v)))
if type(v)=="table"or type(v)=="romtable" then
level=level+1
doprint(v)
level=level-1
end
end
end
doprint(t)
end
-- Add specific components to the 'components' table
function add_platform_components( t, board, cpu )
t.bonfire_riscv = { macro = 'ENABLE_BONFIRE_RISCV' }
t.bonfire_gdbserver = {
macro= 'ENABLE_BONFIRE_GDBSERVER',
attrs= {
uart = at.uart_attr('GDB_DEBUG_UART','1'),
speed= at.int_attr('GDB_DEBUG_BAUD',300,1000000,115200)
}
}
end
-- Add specific configuration to the 'configs' table
function add_platform_configs( t, board, cpu )
--if board:lower()=="bonfire_papilio_pro" then
t.i2c = {
attrs = {
scl_bit = at.int_attr('I2C_SCL_BIT',0 ,31),
sda_bit = at.int_attr('I2C_SDA_BIT', 0,31)
}
}
t.bonfire = {
attrs= {
num_uarts=at.int_attr('NUM_UART',1,16),
uarts=at.array_of(at.string_attr('UART_BASE_ADDR',32),true),
uart_ints=at.array_of(at.string_attr('UART_INTS',32),true)
}
}
end
-- Return an array of all the available platform modules for the given cpu
function get_platform_modules( board, cpu )
m = { riscv = { lib = '"riscv"', open = luaopen_riscv },
gdbserver= { lib='"gdbserver"', map="gdbserver_map", open=false }
}
return m
end
|
return {
summary = 'Reinitialize the RandomGenerator with a new seed.',
description = [[
Seed the RandomGenerator with a new seed. Each seed will cause the RandomGenerator to produce a
unique sequence of random numbers.
]],
arguments = {
seed = {
type = 'number',
description = 'The random seed.'
},
low = {
type = 'number',
description = 'The lower 32 bits of the seed.'
},
high = {
type = 'number',
description = 'The upper 32 bits of the seed.'
}
},
returns = {},
notes = [[
For precise 64 bit seeds, you should specify the lower and upper 32 bits of the seed separately.
Otherwise, seeds larger than 2^53 will start to lose precision.
]]
}
|
--[[
ScrubBuster by burneddi
]]
--Libraries
local StatLogic = AceLibrary("StatLogic-1.0")
ScrubBuster = {
stats = {}; --the table in which we'll gather the stats, organized by unit name
tempUnit = nil;
talentsTimeout = false; --whether talent check has timed out for current unit
};
--Check that BonusScanner version is correct, and print an alert if it isn't:
if BONUSSCANNER_VERSION ~= "3.5x" then
DEFAULT_CHAT_FRAME:AddMessage(RED_FONT_COLOR_CODE.."ScrubBuster has detected an incorrect BonusScanner version. Some inspect stats will appear incorrect. Verify that you are using the BonusScanner version included with ScrubBuster."..FONT_COLOR_CODE_CLOSE);
end
-----------------------------
--Script handling stuff etc--
-----------------------------
--we need a timeout for INSPECT_TALENT_READY function in case it never fires for whatever reason
local waitingForTalents = false;
local waitedForTalents = 0; --time we've spent waiting for talents
CreateFrame("Frame", "ScrubBusterTimeout");
function ScrubBusterTimeout_OnUpdate(self, elapsed)
if not waitingForTalents then
waitedForTalents = 0;
self:SetScript("OnUpdate", nil);
return;
end
waitedForTalents = waitedForTalents + elapsed;
if waitedForTalents >= 2 then
ScrubBusterFrame:UnregisterEvent("INSPECT_TALENT_READY");
if ScrubBuster.tempUnit then
DEFAULT_CHAT_FRAME:AddMessage(RED_FONT_COLOR_CODE.."ScrubBuster: Timeout retrieving talent data for inspect. Chances are there is something wrong with the server you're playing on. Talent effects might not be calculated."..FONT_COLOR_CODE_CLOSE);
ScrubBuster.talentsTimeout = true;
ScrubBusterTalentTimeoutFrame:Show();
ScrubBuster.tempUnit = nil;
ScrubBuster.tempSpecial = nil;
end
waitedForTalents = 0;
waitingforTalents = false;
self:SetScript("OnUpdate", nil);
end
end
function ScrubBuster_OnLoad()
--we should probably do stuff here
end
function ScrubBuster_OnEvent(event, ...)
if event == "INSPECT_TALENT_READY" then
ScrubBusterFrame:UnregisterEvent("INSPECT_TALENT_READY");
if ScrubBuster.tempUnit then
local name = UnitName(ScrubBuster.tempUnit);
ScrubBuster.stats[name] = {};
ScrubBuster.stats[name]["talentsDone"] = true;
waitingForTalents = false;
ScrubBuster:ScrubBust(ScrubBuster.tempUnit, true, ScrubBuster.tempSpecial);
--ScrubBuster.stats[name]["level"], ScrubBuster.stats[name]["stats"], ScrubBuster.stats[name]["weaponStats"], ScrubBuster.stats[name]["itemStats"] = ScrubBuster:GetStats(ScrubBuster.tempUnit, ScrubBuster.tempSpecial);
ScrubBuster.tempUnit = nil;
ScrubBuster.tempSpecial = nil;
ScrubBuster_StatsDone(name);
end
end
end
function ScrubBuster_StatsDone(name)
--dummy function to hook into that gets called after stats have been gathered for name
end
--------------
--!!DANGER!!--
--------------
--variables ahead
--lots of boring patterns we need to match to lots of boring stats that items can have
--used in tooltip scanning
local sbDPSTemplate = string.gsub(getglobal("DPS_TEMPLATE"), "%%.1f", "(%%d+%%.%%d+)"); --yeah, we're just
local sbDPSTemplate2 = string.gsub(getglobal("DPS_TEMPLATE"), "%%.1f", "(%%d+%%,%%d+)"); --copying bonusscanner
local sbSpeedTemplate = getglobal("WEAPON_SPEED") .. " " .. "(%d+%.%d+)";
local sbSpeedTemplate2 = getglobal("WEAPON_SPEED") .. " " .. "(%d+%,%d+)";
local sbDamageTemplate = string.gsub(getglobal("DAMAGE_TEMPLATE"), "%%d %- %%d", "(%%d+) %%- (%%d+)");
local sbElementalDamageTemplate = string.gsub(getglobal("DAMAGE_TEMPLATE_WITH_SCHOOL"), "%%d %- %%d %%s", "(%%d+) %%- (%%d+) (%%a+)");
local sbAmmoDamageTemplate = string.gsub(getglobal("AMMO_DAMAGE_TEMPLATE"), "%%g", "(%%d+)");
local sbAmmoElementalDamageTemplate = string.gsub(getglobal("AMMO_SCHOOL_DAMAGE_TEMPLATE"), "%%g %%s", "(%%d+) (%%a+)");
--I don't think the next two are actually used for any weapons
--local sbSingleDamageTemplate = string.gsub(getglobal("SINGLE_DAMAGE_TEMPLATE"), "%%d", "(%%d+)");
--local sbSingleElementalDamageTemplate = string.gsub(getglobal("SINGLE_DAMAGE_TEMPLATE_WITH_SCHOOL"), "%%d %%s", "(%%d+) (%%a+)");
--The next two should also be caught by regular damage templates, which is ok for our uses
--local sbExtraDamageTemplate = string.gsub(getglobal("PLUS_DAMAGE_TEMPLATE"), "%%d %- %%d", "(%%d+) %- (%%d+)");
--local sbExtraElementalDamageTemplate = string.gsub(getglobal("PLUS_DAMAGE_TEMPLATE_WITH_SCHOOL"), "%%d %- %%d %s", "(%%d+) %- (%%d+) (%%a+)");
--The next two aren't used for any arrows I've ever heard of
--local sbExtraAmmoDamageTemplate = string.gsub(getglobal("PLUS_AMMO_DAMAGE_TEMPLATE"), "%%g", "(%%d+)");
--local sbExtraAmmoElementalDamageTemplate = string.gsub(getglobal("PLUS_AMMO_SCHOOL_DAMAGE_TEMPLATE"), "%%g %%s", "(%%d+) (%%a+)");
local sbExtraSingleDamageTemplate = string.gsub(getglobal("PLUS_SINGLE_DAMAGE_TEMPLATE"), "%%d", "(%%d+)");
local sbExtraSingleElementalDamageTemplate = string.gsub(getglobal("PLUS_SINGLE_DAMAGE_TEMPLATE_WITH_SCHOOL"), "%%d %%s", "(%%d+) (%%a+)");
local sbWeaponClasses = { --table of weapon classes as they appear in the tooltip, along with what we want to call them
--this will be even more important later if we end up adding support for non-english localizations
--most things like this are already "localized" through GlobalStrings I think, but this one isn't
["Staff"] = "STAFF",
["Polearm"] = "POLEARM",
["Mace"] = "MACE",
["Axe"] = "AXE",
["Sword"] = "SWORD",
["Wand"] = "WAND",
["Dagger"] = "DAGGER",
["Thrown"] = "THROWN",
["Fist Weapon"] = "FISTWEAPON",
["Shield"] = "SHIELD",
["Bow"] = "BOW",
["Gun"] = "GUN",
["Crossbow"] = "CROSSBOW",
["Idol"] = "IDOL",
["Libram"] = "LIBRAM",
["Totem"] = "TOTEM",
--there's also "Held in Off-hand" (called "OFFHANDITEM") items but they're handled outside of this table
--also items for which we can't figure this out will be called "UNKNOWN"
};
local sbWeaponHand = { --table of which hand/slot the weapon goes to
[getglobal("INVTYPE_2HWEAPON")] = "TWOHAND", --both hands
[getglobal("INVTYPE_WEAPON")] = "ONEHAND", --either main or offhand
[getglobal("INVTYPE_WEAPONOFFHAND")] = "OFFHAND",
[getglobal("INVTYPE_WEAPONMAINHAND")] = "MAINHAND",
[getglobal("INVTYPE_HOLDABLE")] = "OFFHAND",
[getglobal("INVTYPE_RANGED")] = "RANGED",
[getglobal("INVTYPE_SHIELD")] = "OFFHAND",
[getglobal("INVTYPE_THROWN")] = "RANGED",
--[getglobal("INVTYPE_RELIC")] = "RELIC",
};
local sbDamageTypes = { --table for elemental damage types
[getglobal("DAMAGE_SCHOOL2")] = "HOLY",
[getglobal("DAMAGE_SCHOOL3")] = "FIRE",
[getglobal("DAMAGE_SCHOOL4")] = "NATURE",
[getglobal("DAMAGE_SCHOOL5")] = "FROST",
[getglobal("DAMAGE_SCHOOL6")] = "SHADOW",
[getglobal("DAMAGE_SCHOOL7")] = "ARCANE",
};
local ClassNameToID = {
"WARRIOR",
"PALADIN",
"HUNTER",
"ROGUE",
"PRIEST",
"SHAMAN",
"MAGE",
"WARLOCK",
"DRUID",
["WARRIOR"] = 1,
["PALADIN"] = 2,
["HUNTER"] = 3,
["ROGUE"] = 4,
["PRIEST"] = 5,
["SHAMAN"] = 6,
["MAGE"] = 7,
["WARLOCK"] = 8,
["DRUID"] = 9,
};
---------------
--DANGER OVER--
---------------
--quick rounding function in case we need it
--Example: sbRound(420.1488, 2); outputs 420.15
function ScrubBuster:round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function ScrubBuster:ConvertBStoSB(bsstats)
--Function for converting BonusScanner stats to our table format, because we're unique snowflakes
--(also because bonusscanner's way of indexing stats is awful) (not saying ours is better)
local conversiontable = {
--syntax: BONUSSCANNERSTAT = ScrubBuster.statTable.key.Stat,
STR = {["primary"] = "str"},
AGI = {["primary"] = "agi"},
STA = {["primary"] = "sta"},
INT = {["primary"] = "int"},
SPI = {["primary"] = "spi"},
HEALTH = {["resource"] = "health"},
HEALTHREG = {["resource"] = "healthRegen"},
MANA = {["resource"] = "mana"},
MANAREG = {["resource"] = "manaRegenWhileCasting"}, --bonusscanner's manareg is mp5 so it's while casting
ARCANERES = {["resist"] = "arcane"},
FIRERES = {["resist"] = "fire"},
NATURERES = {["resist"] = "nature"},
FROSTRES = {["resist"] = "frost"},
SHADOWRES = {["resist"] = "shadow"},
HASTE = {["physical"] = "hasteRating"},
TOHIT = {["physical"] = "hitRating"},
CRIT = {["melee"] = "critRating"},
ARMORPEN = {["physical"] = "armorPen"},
EXPERTISE = {["melee"] = "expertiseRating"},
ATTACKPOWER = {["melee"] = "attackPower"},
DMGWPN = {["melee"] = "mainHandDmgMax"}, --this affects mainhand and offhand min and max damage
--so we'll have to hack it in properly later
RANGEDATTACKPOWER = {["ranged"] = "attackPower"},
RANGEDDMG = {["ranged"] = "dmgMax"}, --this affects ranged min and max damage, also have to hack it
DMG = {["spell"] = "damage"},
HOLYDMG = {["spell"] = "holyDamage"},
FIREDMG = {["spell"] = "fireDamage"},
NATUREDMG = {["spell"] = "natureDamage"},
FROSTDMG = {["spell"] = "frostDamage"},
SHADOWDMG = {["spell"] = "shadowDamage"},
ARCANEDMG = {["spell"] = "arcaneDamage"},
HEAL = {["spell"] = "healing"},
SPELLCRIT = {["spell"] = "critRating"},
HOLYCRIT = {["spell"] = "holyCritRating"},
FIRECRIT = {["spell"] = "fireCritRating"},
NATURECRIT = {["spell"] = "natureCritRating"},
FROSTCRIT = {["spell"] = "frostCritRating"},
SHADOWCRIT = {["spell"] = "shadowCritRating"},
ARCANECRIT = {["spell"] = "arcaneCritRating"},
SPELLTOHIT = {["spell"] = "hitRating"},
SPELLH = {["spell"] = "hasteRating"},
SPELLPEN = {["spell"] = "penetration"},
ARMOR = {["defense"] = "armor"},
DEFENSE = {["defense"] = "defenseRating"},
DODGE = {["defense"] = "dodgeRating"},
PARRY = {["defense"] = "parryRating"},
BLOCK = {["defense"] = "blockRating"},
BLOCKVALUE = {["defense"] = "blockValue"},
RESILIENCE = {["defense"] = "resilience"}
};
local convertedstats = ScrubBuster:InitStatsTable();
for k,v in pairs(bsstats) do
local temp = conversiontable[k];
if temp ~= nil then
local cat;local val;
cat, val = next(temp);
if cat and k == "ATTACKPOWER" then --generic item AP also gives RAP
convertedstats["melee"]["attackPower"]["posMod"] = v;
if convertedstats["ranged"]["attackPower"]["posMod"] then
convertedstats["ranged"]["attackPower"]["posMod"] = convertedstats["ranged"]["attackPower"]["posMod"] + v;
else
convertedstats["ranged"]["attackPower"]["posMod"] = v;
end
elseif cat and k == "CRIT" then --critrating gives both melee and ranged critrating
convertedstats["melee"]["critRating"]["posMod"] = v;
convertedstats["ranged"]["critRating"]["posMod"] = v;
elseif cat and k == "DMGWPN" then
convertedstats["melee"]["mainHandDmgMax"]["posMod"] = v;
convertedstats["melee"]["mainHandDmgMin"]["posMod"] = v;
convertedstats["melee"]["offHandDmgMax"]["posMod"] = v;
convertedstats["melee"]["offHandDmgMin"]["posMod"] = v;
elseif cat and k == "RANGEDDMG" then
convertedstats["ranged"]["dmgMax"]["posMod"] = v;
convertedstats["ranged"]["dmgMin"]["posMod"] = v;
elseif cat then
convertedstats[cat][val]["posMod"] = v;
end
end
end
return convertedstats
end
function ScrubBuster:ScrubBust(target, refresh, special)
--the primary function that handles ou're shit
--Gets the stats and puts them into the ScrubBuster.stats table, indexed by name
--refresh is bool, it should be true if we're only refreshing the stats of the currently inspected unit
--special is a table of all the special features we want, it will get passed on to the stat getting
--function
if not UnitIsPlayer(target) or not CanInspect(target) or not CheckInteractDistance(target, 1) then return nil end
local name = UnitName(target);
ScrubBuster.stats = {}; --temporary(?): reset the stats variable
--(might add gearscore -like character stat databasing stuff later)
if UnitIsUnit("player", target) then
ScrubBuster.stats[name] = {};
ScrubBuster.talentsTimeout = false;
ScrubBuster.stats[name]["level"], ScrubBuster.stats[name]["stats"], ScrubBuster.stats[name]["weaponStats"], ScrubBuster.stats[name]["itemStats"] = ScrubBuster:GetStats(target, special);
ScrubBuster_StatsDone(name);
elseif refresh then
ScrubBuster.stats[name] = {};
ScrubBuster.stats[name]["level"], ScrubBuster.stats[name]["stats"], ScrubBuster.stats[name]["weaponStats"], ScrubBuster.stats[name]["itemStats"] = ScrubBuster:GetStats(target, special);
ScrubBuster_StatsDone(name);
else --it's an inspect target and we're not refreshing, so we need to wait for talents to be done
ScrubBuster.talentsTimeout = false;
--actually, even if we can't get the talents let's get their stats anyway, and then get them
--again when talents become available
ScrubBuster.stats[name] = {};
ScrubBuster.stats[name]["level"], ScrubBuster.stats[name]["stats"], ScrubBuster.stats[name]["weaponStats"], ScrubBuster.stats[name]["itemStats"] = ScrubBuster:GetStats(target, special);
ScrubBuster_StatsDone(name);
ScrubBuster.tempUnit = target;
ScrubBuster.tempSpecial = special;
waitingForTalents = true;
waitedForTalents = 0;
ScrubBusterTimeout:SetScript("OnUpdate", ScrubBusterTimeout_OnUpdate);
ScrubBusterFrame:RegisterEvent("INSPECT_TALENT_READY");
NotifyInspect(target);
--rest of this stuff will be handled by the talent ready eventhandler
end
return true;
end
function ScrubBuster:InitStatsTable()
--Initializes the stats table. Most values are initialized as zeroes, but some
--(at this moment, only multiplier values) default to 1.
--This whole thing is pretty awful so if you're not me and are reading this I'm so sorry.
--I will try to collect some relevant notes here, for myself and for you
--Each stat has three table fields:
--Base is self-explanatory, it's the base value of the stat. ie. what displays as the
--white number in your character sheet. Things like racials, talents? and stuff go here.
--For some stats, such as weapon damage, base is the only value used, but for (in)consistency's
--sake these stats have the other fields too.
--posMod is the positive modifier or buff. Equipment bonuses, most active auras, etc. affect this stat
--(or the negMod stat if they're negative modifiers). A notorious exception to this is multiplier
--buffs like Blessing of Kings: they multiply the base+posMod value of the stat (I believe negMod
--doesn't get multiplied), but increase the base value. So if you're naked and
--have Blessing of Kings on you, the stats on your character sheet will appear as white (unbuffed).
--negMod is the negative modifier or buff. Negative auras affect this. It's basically the
--red component of stats on the character sheet.
--mult is stat multiplier. Percentual multipliers will be added to this, and then after everything
--else is sorted out this gets resolved into actual stat points (I believe that's how it works
--at least). This means things like % increase racials (human, tauren),
--Blessing of Kings, and the like.
--IMPORTANT NOTICE: these stack multiplicatively, so whenever this field is changed the correct
--syntax is for example: ["mult"] = ["mult"] * (1 + 0.1);
--
--In the case of weapon damage (mainHandDmgMin etc) this multiplier affects things like
--dual wield specialization etc. For offhand weapons it defaults to 0.5 as that's the
--damage penalty for dual wielding. Weapon DPS is calculated from min and max damage,
--so this multiplier should not be applied to that
--TODO: should probably write a function to handle changes to stats in this table rather
--than doing it the hard way.
--About multipliers (eg. human spirit racial, BoK) and negative buffs that reduce stat by absolute value:
--Multipliers do not seem to apply to the magnitude of negative buffs. Needs more testing
--to ascertain, but for now we'll go with this.
--the way total stat is assumed to be calculated is as such:
--(base + posMod) * mult - negMod
--HOWEVER, negative buffs that reduce a stat by a percentage just directly modify the mult value,
--which means that they also ultimately appear as a white "unmodified" stat on the char sheet
--About increasedAttackSpeed (percentual haste):
--[[
Patch 1.12
Previously Haste and Slow effects worked inconsistently, with spells working
differently from weapons, and hastes and slows not acting as inverses of each other.
We have revised the system so that all haste and slow effects work the same way,
and haste and slow percentages of the same magnitude perfectly cancel each other out
(30% haste and 30% slow combine to no change). As a result, we had to change the tooltip
numbers on all spell haste effects, and on all melee and range slow effects.
The numbers in the tooltips are different, but the game functionality is unchanged
(other than slight rounding errors). Those tooltips that changed will now display larger
numbers than they used to display. Conceptually, haste values indicate how much more
of that activity you can perform in a given time. 30% melee haste means 30% more swings
in a given time. Slow values indicate how much longer an activity takes to complete.
30% slow means an action takes 30% longer to finish.
Haste now stacks multiplicatively.
IN OTHER WORDS:
- posMod is increased speed (a positive decimal value, eg. 0.35 = 35% increased speed)
- negMod is SLOWS, a positive decimal value!!!!, **NOT** a negative decimal value
these slows cancel out haste 1:1, which means that in the formula they're a divisor
also generally slows don't stack. At all. We'll cross that bridge when (if) we get to it.
- Base is kinda just there, I doubt it will generally be used for anything.
but if it's used it will be a positive decimal value
it kinda should default to 1 but won't
- The way these are in practice calculated is like this:
(1 + base) * (1 + posMod) / (1 + negMod)
considering base is supposed to be zero, the first part can probably be omitted
- When adding to a value make sure to multiply instead of just adding, so if you
add eg. a 15% haste effect to the posMod then that's (1 + posMod) * (1 + 0.15) - 1;
]]
--Damage multipliers (offHandDamageMultiplier etc) are another stat with special exception treatment
--They only use one field: base. They seem to all be percentage points, not actual percentages,
--so they work like critPercentage, dodgePercentage etc. so that a 5% damage modifier always results
--in 5 percentage points being added to the current modifier.
--Example: warrior in Defensive Stance (-10% damage) who has Two-Handed Weapon Specialization (+5% damage)
--result is 95% damage, not 94.5% damage.
--Damage multipliers (offHandDamageMultiplier etc) are the other stat with special exception treatment
--Damage multipliers are a flat out multiplier for weapon damage, some talents and buffs
--have it. On the character sheet it has special treatment (compared to other multipliers),
--as any damage multipliers make the damage stat appear green and in the tooltip you'll
--see the multiplier as a percentage. These only use the "mult" field, and stack multiplicatively
--(even though the UI might have you believe otherwise).
--oh by the way for weapon damage "base" is base dmg + effect from attackpower etc.,
--"posMod" is any positive buffs that may be picked up like sharpening stones or Brutal Earthstorm Diamond
--"negMod" is negative buffs. Currently we don't pick up buffs though and don't plan to.
--Multiplier is not used except for offhand damage penalty.
local stats = {
["primary"] = {
["str"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["agi"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["sta"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["int"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["spi"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["resource"] = {
["health"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["healthRegen"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mana"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["manaRegen"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["manaRegenWhileCasting"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
--[[["general"] = {
["damageMultiplier"] = {["base"] = 1, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},]]
["resist"] = {
["arcane"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["fire"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["nature"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["frost"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["shadow"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["defense"] = {
["armor"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["defense"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["defenseRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["dodgeRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["dodgePercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["parryRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["parryPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["blockRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["blockPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["blockValue"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["resilience"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
--critReduction is the reduction to the chance of being critically struck by *melee attacks*
--We don't track this for spells or ranged attacks because.
--things like some talents, Defense skill, and Resilience increase this.
--Note that Defense skill is technically supposed to increase it in relation
--to the attacker's Weapon Skill, but for our purposes this doesn't matter
["critReduction"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
--hitReduction is the same as critReduction, except for chance of being hit in melee
--some talents add this, as does the Defense skill
["hitReduction"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["physical"] = {
["hasteRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hitRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
--hitPercent is things like talent that give you flat hit chance percentages
--It's not shown in the character sheet AFAIK but we'll collect it anyway
--this here is generic physical (melee+ranged), then there's specific ones and a spell one
["hitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["armorPen"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
--["increasedAttackSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["melee"] = {
["attackPower"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["expertiseRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["expertise"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["increasedAttackSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandDmgMin"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandDmgMax"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandDps"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandExpertise"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandCritRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["mainHandDamageMultiplier"] = {["base"] = 1, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandDmgMin"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 0.5},
["offHandDmgMax"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 0.5},
["offHandDps"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandExpertise"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandCritRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["offHandDamageMultiplier"] = {["base"] = 1, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["ranged"] = {
["attackPower"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["increasedAttackSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["damageMultiplier"] = {["base"] = 1, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["dmgMin"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["dmgMax"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["dps"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["speed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["ammoDps"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
},
["spell"] = {
["damage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["holyDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["fireDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["natureDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["frostDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["shadowDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["arcaneDamage"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["healing"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hitRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["holyHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["fireHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["natureHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["frostHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["shadowHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["arcaneHitPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["critPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["holyCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["fireCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["natureCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["frostCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["shadowCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["arcaneCritPercent"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["hasteRating"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["increasedAttackSpeed"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1},
["penetration"] = {["base"] = 0, ["posMod"] = 0, ["negMod"] = 0, ["mult"] = 1}
}
};
return stats;
end
function ScrubBuster:AddAuras(stats, auras, weaponStats, itemStats, level, class, special)
--adds all auras in a table to the main stats
for _,aura in pairs(auras) do
if aura["isTalent"] then
local rank = aura["talentRank"];
local effect = aura["func"](rank, stats, weaponStats, itemStats, level, special);
stats = ScrubBuster:AddStat(stats, effect);
elseif aura["isRacial"] then
local effect = aura["func"](weaponStats, class);
stats = ScrubBuster:AddStat(stats, effect);
end
end
return stats;
end
function ScrubBuster:AddStat(mainStats, addStats) --adds stats to the stats table
--both parameters must be tables and in the stat table format.
--mainStats should be the complete table with all values initialized, for addStats it doesn't matter
for cat,stats in pairs(addStats) do
for stat,values in pairs(stats) do
for k,v in pairs(values) do
--this is where the stuff actually happens
local main = mainStats[cat][stat];
if stat == "increasedAttackSpeed" then
--haste has special treatment
if k == "mult" then
main["mult"] = main["mult"] * v;
else
main[k] = (1 + main[k]) * (1 + v) - 1;
end
else
--rest of the stats should be uniform
if k == "mult" then
main["mult"] = main["mult"] * v;
else
main[k] = main[k] + v;
end
end
end
end
end
return mainStats;
end
function ScrubBuster:GetStats(target, spec)
--Gets the total stats of the player
--If target is inspect make sure to call NotifyInspect before this or results will be incorrect
--Talents for the target must be ready before this runs, or else talentbonuses will not be properly
--added, so if calling this for target other than the player make sure to call this from the
--INSPECT_TALENTS_READY eventhandler or something
--Returns int level, table stats, table weaponStats
--get some info about target
local _, race = UnitRace(target);
local level = UnitLevel(target);
if level == -1 then level = 70 end; --if someone's level ?? (over 10 levels above you, or a boss), we'll just assume they're level 70.
local _, class = UnitClass(target);
local classID = ClassNameToID[class];
local inspect = not UnitIsUnit("player", target); --if true, we're checking the inspected target
local stats = ScrubBuster:InitStatsTable(); --see initStatsTable function for structure of table
local canBlock = false; --whether they have the Block skill, without it they will have 0% block chance always
local canParry = false; --same as above except for parry
local weaponStats = { --these are the raw weapon stats, whereas stats table has modified ones
mainHand = {
hasItem = false, --true if a weapon (or something at all) is found in this slot
isWeapon = false, --true if the item is a weapon
weaponType = {}, --type of the weapon as supplied by the tooltip scanning function (table, [1] is handcount, [2] is class)
damage = {}, --table of different damage schools on the weapon, supplied by the weapon tooltip scanning function
speed = nil, --base weapon speed
dps = nil, --dps as it appears on the tooltip
iLvl = nil; --item level
itemId = nil; --item ID
},
offHand = {
hasItem = false,
isWeapon = false,
weaponType = {},
damage = {},
speed = nil,
dps = nil,
iLvl = nil;
itemId = nil;
},
ranged = {
hasItem = false,
isWeapon = false,
weaponType = {},
damage = {},
speed = nil,
dps = nil,
iLvl = nil;
itemId = nil;
},
ammo = { --we can't actually get ammo for inspect targets but what the hell
hasItem = false,
weaponType = nil, --ammo is a little special as in we only have two types for it, "BULLET" and "ARROW"
dps = {}, --ammo only has dps (how much dps it adds to the weapon), not a damage range like weapons.
--This is a table of the different DPS schools it can have, gotten from the scanner function.
iLvl = nil;
itemId = nil;
},
dualWielding = false; --whether they're dual wielding or not. Assume they're not.
};
--This table will contain talentaura effects. They have different priorities
--to decide when their effects are resolved, which are the keys in this table:
--1 will be done first, followed by 2 and so forth.
--Priority 1 is things that modify a primary stat, and don't depend on any other stats
--For instance, +10 intellect
--Priority 2 is things that modify a secondary stat, and don't depend on any other stats
--For instance, +20 attack power
--Priority 3 is things that depend on primary stats somehow.
--For instance, "15% of your intellect is converted into attack power". Some talents are like this.
--Priority 4 is things that depend on secondary stats somehow. I dunno if any exist.
local auras = { [1] = {}, [2] = {}, [3] = {} };
--Sanity check the specials
local special = spec;
if not special then
special = {};
end
if special["quiverIAS"] and class ~= "WARRIOR" and class ~= "ROGUE" and class ~= "HUNTER" then
special["quiverIAS"] = nil;
end
if special["ammoDPS"] and class ~= "WARRIOR" and class ~= "ROGUE" and class ~= "HUNTER" then
special["ammoDPS"] = nil;
end
if special["warriorStance"] and class ~= "WARRIOR" then
special["warriorStance"] = nil;
end
if special["druidForm"] and class ~= "DRUID" then
special["druidForm"] = nil;
end
------------------
--ADD BASE STATS--
------------------
--add basestats to stats
for k,v in pairs(ScrubBuster.BaseStats[race][class][level]) do
stats["primary"][k]["base"] = stats["primary"][k]["base"] + v;
end
--health and mana, based on class
for k,v in pairs(ScrubBuster.BaseHealthMana[class][level]) do
stats["resource"][k]["base"] = stats["resource"][k]["base"] + v;
end
--base secondary stats
--dodge, curiously enough base dodge can be negative for some classes
stats["defense"]["dodgePercent"]["base"] = stats["defense"]["dodgePercent"]["base"] + ScrubBuster.BaseDodge[classID];
--Block, classes with shields will essentially have 5% base block chance through passive skill Block
--this is Warriors, Paladins, Shamans
if class == "WARRIOR" or class == "PALADIN" or class == "SHAMAN" then
canBlock = true;
stats["defense"]["blockPercent"]["base"] = stats["defense"]["blockPercent"]["base"] + 5.00;
end
--Parry, all melee classes except Shamans have this as a passive ability. Enhancement shamans get it
--through a talent.
--warriors can get the ability at level 6, hunters and paladins at 8, rogues at 12. We'll just assume
--they have the ability as soon as they're of that level
if class == "WARRIOR" and level >= 6 then
canParry = true;
stats["defense"]["parryPercent"]["base"] = stats["defense"]["parryPercent"]["base"] + 5.00;
elseif (class == "HUNTER" or class == "PALADIN") and level >= 8 then
canParry = true;
stats["defense"]["parryPercent"]["base"] = stats["defense"]["parryPercent"]["base"] + 5.00;
elseif class == "ROGUE" and level >= 12 then
canParry = true;
stats["defense"]["parryPercent"]["base"] = stats["defense"]["parryPercent"]["base"] + 5.00;
elseif class == "SHAMAN" then
local _, _, _, _, talentRank = GetTalentInfo(2, 13, inspect);
if talentRank > 0 then
canParry = true;
stats["defense"]["parryPercent"]["base"] = stats["defense"]["parryPercent"]["base"] + 5.00;
end
end
--defense, this is technically a skill and we can't get it, but generally everyone will have it at
--the maximum value allowed for their level (level*5) so we'll just go with that
stats["defense"]["defense"]["base"] = stats["defense"]["defense"]["base"] + level * 5;
--Spell crit, all classes have a different base spell crit as well as different spellcrit from int gain
stats["spell"]["critPercent"]["base"] = stats["spell"]["critPercent"]["base"] + ScrubBuster.BaseSpellCrit[classID];
--Physical crit, same story as for spellcrit but this was a lot harder to figure out for some reason
stats["melee"]["critPercent"]["base"] = stats["melee"]["critPercent"]["base"] + ScrubBuster.BaseCrit[classID];
stats["ranged"]["critPercent"]["base"] = stats["ranged"]["critPercent"]["base"] + ScrubBuster.BaseCrit[classID];
--Melee attack power, some classes gain this from levels
if class == "WARRIOR" or class == "PALADIN" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + level * 3;
elseif class == "SHAMAN" or class == "ROGUE" or class == "HUNTER" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + level * 2;
end
--Ranged attack power, some classes get this from levels
if class == "HUNTER" then
stats["ranged"]["attackPower"]["base"] = stats["ranged"]["attackPower"]["base"] + level * 2;
elseif class == "WARRIOR" or class == "ROGUE" then
stats["ranged"]["attackPower"]["base"] = stats["ranged"]["attackPower"]["base"] + level;
end
---------------------------------------
--Handle any weapons they might wield--
---------------------------------------
local itemlink16 = GetInventoryItemLink(target, 16); --slot 16, main hand
local itemlink17 = GetInventoryItemLink(target, 17); --slot 17, off hand
local itemlink18, itemlink0;
if not UnitHasRelicSlot(target) then
itemlink18 = GetInventoryItemLink(target, 18); --slot 18, ranged
itemlink0 = GetInventoryItemLink(target, 0); --slot 0, ammo
end
-- Slot16
if itemlink16 then
local wstats = weaponStats.mainHand;
wstats.hasItem = true;
_,_,_,wstats.iLvl = GetItemInfo(itemlink16);
wstats.itemId = tonumber(string.match(itemlink16, "|c%x%x%x%x%x%x%x%x|Hitem:(%d+):"));
wstats.damage, wstats.speed, wstats.dps, wstats.weaponType, wstats.isWeapon = ScrubBuster:ScanWeapTooltip(itemlink16);
local dmgmin, dmgmax = ScrubBuster:CombineDamageTable(wstats.damage);
if wstats.weaponType then --only do stuff if we could figure out it's actually a weapon to begin with
--some sanity checking must be necessary here, in case the item wasn't a proper weapon
if not wstats.speed then wstats.speed = 2.00 end --we'll just give it unarmed speed
--it puts the stats in the table or it gets the hose
--this is the first time we actually get these, so no need to add just assign
stats["melee"]["mainHandDmgMin"]["base"] = dmgmin;
stats["melee"]["mainHandDmgMax"]["base"] = dmgmax;
--stats.MAINHANDDPS = dps; --actually, let's calculate this later
stats["melee"]["mainHandSpeed"]["base"] = wstats.speed;
else --if we couldn't figure out what kind of weapon it is, fallback to unarmed
stats["melee"]["mainHandDmgMin"]["base"] = 1;
stats["melee"]["mainHandDmgMax"]["base"] = 2;
stats["melee"]["mainHandSpeed"]["base"] = 2.00;
end
else --the itemlink is nil, so they're unarmed
stats["melee"]["mainHandDmgMin"]["base"] = 1;
stats["melee"]["mainHandDmgMax"]["base"] = 2;
stats["melee"]["mainHandSpeed"]["base"] = 2.00;
end
-- Slot17
if itemlink17 then
local wstats = weaponStats.offHand;
wstats.hasItem = true;
_,_,_,wstats.iLvl = GetItemInfo(itemlink17);
wstats.itemId = tonumber(string.match(itemlink17, "|c%x%x%x%x%x%x%x%x|Hitem:(%d+):"));
wstats.damage, wstats.speed, wstats.dps, wstats.weaponType, wstats.isWeapon = ScrubBuster:ScanWeapTooltip(itemlink17);
local dmgmin, dmgmax = ScrubBuster:CombineDamageTable(wstats.damage);
if wstats.weaponType and not (wstats.weaponType[2] == "OFFHANDITEM" or wstats.weaponType[2] == "SHIELD") then
--only do stuff if it's relevant
weaponStats["dualWielding"] = true;
if not wstats.speed then wstats.speed = 2.00 end --same sanity check as above
stats["melee"]["offHandDmgMin"]["base"] = dmgmin;
stats["melee"]["offHandDmgMax"]["base"] = dmgmax;
stats["melee"]["offHandSpeed"]["base"] = wstats.speed;
else --their offhand isn't a weapon
stats["melee"]["offHandDmgMin"]["base"] = 0;
stats["melee"]["offHandDmgMax"]["base"] = 0;
stats["melee"]["offHandSpeed"]["base"] = 2.00;
end
else --the itemlink is nil
stats["melee"]["offHandDmgMin"]["base"] = 0;
stats["melee"]["offHandDmgMax"]["base"] = 0;
stats["melee"]["offHandSpeed"]["base"] = 2.00;
end
-- Slot18
if itemlink18 then
local wstats = weaponStats.ranged;
wstats.hasItem = true;
_,_,_,wstats.iLvl = GetItemInfo(itemlink18);
wstats.itemId = tonumber(string.match(itemlink18, "|c%x%x%x%x%x%x%x%x|Hitem:(%d+):"));
wstats.damage, wstats.speed, wstats.dps, wstats.weaponType, wstats.isWeapon = ScrubBuster:ScanWeapTooltip(itemlink18);
local dmgmin, dmgmax = ScrubBuster:CombineDamageTable(wstats.damage);
if wstats.weaponType then
if not wstats.speed then wstats.speed = 2.00 end
stats["ranged"]["dmgMin"]["base"] = dmgmin;
stats["ranged"]["dmgMax"]["base"] = dmgmax;
stats["ranged"]["speed"]["base"] = wstats.speed;
end
else --the itemlink is null, so they have no ranged
stats["ranged"]["dmgMin"]["base"] = 1;
stats["ranged"]["dmgMax"]["base"] = 2;
stats["ranged"]["speed"]["base"] = 2.00; --these are actually the base ranged values, although character sheet shows N/A if you have no ranged weapon
end
-- Slot0, ammo (can't see for inspect, but we can guess it):
if itemlink0 then
local wstats = weaponStats.ammo;
wstats.hasItem = true;
_,_,_,wstats.iLvl = GetItemInfo(itemlink0);
wstats.itemId = tonumber(string.match(itemlink0, "|c%x%x%x%x%x%x%x%x|Hitem:(%d+):"));
wstats.dps, wstats.weaponType = ScrubBuster:ScanAmmoTooltip(itemlink0);
if wstats.dps and wstats.weaponType then --we'll only do anything if we figure out everything we want about the ammo
--combine the ammo DPS table into one, since for now we only need the total deeps for anything
for _,v in pairs(wstats.dps) do
stats["ranged"]["ammoDps"]["base"] = stats["ranged"]["ammoDps"]["base"] + v;
end
end
elseif special["ammoDPS"] then
local wstats = weaponStats.ammo;
wstats.hasItem = true;
wstats.dps = special["ammoDPS"]
if weaponStats.ranged.weaponType[2] == "BOW" then wstats.weaponType = "ARROW";
elseif weaponStats.ranged.weaponType[2] == "CROSSBOW" then wstats.weaponType = "ARROW";
else
--we'll default to bullet in case there's no ranged weapon, whatever, it's not like
--this stat will get used if that's the case
wstats.weaponType = "BULLET";
end
stats["ranged"]["ammoDps"]["base"] = stats["ranged"]["ammoDps"]["base"] + wstats.dps;
end
--Add ammo damage to weapon damage, if it's applicable
--check for Thori'dal (which is the only? weapon that doesn't use or benefit from ammo), too...
if weaponStats.ranged.hasItem and weaponStats.ammo.hasItem and weaponStats.ranged.itemId ~= 34334 then
if weaponStats.ranged.weaponType[2] == "BOW" and weaponStats.ammo.weaponType == "ARROW" then
local dmg = stats["ranged"]["ammoDps"]["base"] * stats["ranged"]["speed"]["base"];
stats["ranged"]["dmgMin"]["base"] = stats["ranged"]["dmgMin"]["base"] + dmg;
stats["ranged"]["dmgMax"]["base"] = stats["ranged"]["dmgMax"]["base"] + dmg;
elseif weaponStats.ranged.weaponType[2] == "CROSSBOW" and weaponStats.ammo.weaponType == "ARROW" then
local dmg = stats["ranged"]["ammoDps"]["base"] * stats["ranged"]["speed"]["base"];
stats["ranged"]["dmgMin"]["base"] = stats["ranged"]["dmgMin"]["base"] + dmg;
stats["ranged"]["dmgMax"]["base"] = stats["ranged"]["dmgMax"]["base"] + dmg;
elseif weaponStats.ranged.weaponType[2] == "GUN" and weaponStats.ammo.weaponType == "BULLET" then
local dmg = stats["ranged"]["ammoDps"]["base"] * stats["ranged"]["speed"]["base"];
stats["ranged"]["dmgMin"]["base"] = stats["ranged"]["dmgMin"]["base"] + dmg;
stats["ranged"]["dmgMax"]["base"] = stats["ranged"]["dmgMax"]["base"] + dmg;
end
end
----------------------------------------------
--Scan target's equipment using BonusScanner--
----------------------------------------------
local itemStats = BonusScanner:ScanEquipment(target);
--convert the stats from bonusscanner to a digestable format:
itemStats = ScrubBuster:ConvertBStoSB(itemStats);
--combine bonusscanner-gotten stats with our own stats
for k,v in pairs(itemStats) do
for k2,v2 in pairs(v) do
stats[k][k2]["posMod"] = stats[k][k2]["posMod"] + v2["posMod"];
end
end
--If they're a hunter, we need to crudely guess the IAS their quiver gives.
--No one else *should* be wearing quivers/ammo pouches than hunters.
--[[
if class == "HUNTER" then
local quiverias;
if level >= 60 then
quiverias = 0.15;
elseif level >= 40 then
quiverias = 0.13;
elseif level >= 30 then
quiverias = 0.12;
else
quiverias = 0.1;
end
stats["ranged"]["increasedAttackSpeed"]["posMod"] = (1 + stats["ranged"]["increasedAttackSpeed"]["posMod"]) * (1 + quiverias) - 1;
end
]]
--Get the quiver tier from the special variables if it exists, otherwise don't give them a quiver
--only apply quiver IAS if they have a weapon that benefits from it (bow, xbow, gun)
if special["quiverIAS"] then
local weaponType = weaponStats["ranged"]["weaponType"][2];
if weaponType == "GUN" or weaponType == "BOW" or weaponType == "CROSSBOW" then
stats["ranged"]["increasedAttackSpeed"]["posMod"] = (1 + stats["ranged"]["increasedAttackSpeed"]["posMod"]) * (1 + special["quiverIAS"]) - 1;
end
end
--Add generic special stuff, like Berserker Stance crit, defensive stance damage reduction
if special["warriorStance"] == "defensive" then
local temp = stats["melee"];
temp["mainHandDamageMultiplier"]["mult"] = temp["mainHandDamageMultiplier"]["mult"] * 0.9;
temp["offHandDamageMultiplier"]["mult"] = temp["offHandDamageMultiplier"]["mult"] * 0.9;
stats["ranged"]["damageMultiplier"]["mult"] = stats["ranged"]["damageMultiplier"]["mult"] * 0.9;
elseif special["warriorStance"] == "berserker" then
stats["melee"]["critPercent"]["base"] = stats["melee"]["critPercent"]["base"] + 3;
stats["ranged"]["critPercent"]["base"] = stats["ranged"]["critPercent"]["base"] + 3;
end
if special["druidForm"] == "bear" then
local temptable = {
["isTalent"] = true; --we'll treat this thing like a talent even though it's not
["talentRank"] = 1; --since it'll work this way anyway and we don't have to restructure ou're systems :^)
["func"] = nil;
};
local temptable2 = {
["isTalent"] = true; --also this thing needs two effects, armor and stamina
["talentRank"] = 1;
["func"] = function(rank, stats, weaponStats, itemStats, level, special)
local aura = { ["primary"] = {
["sta"] = { ["mult"] = 1.25 }
} };
return aura;
end
};
if level < 40 then
temptable["func"] = function(rank, stats, weaponStats, itemStats, level, special)
local aura = { ["defense"] = {
["armor"] = { ["base"] = itemStats["defense"]["armor"]["posMod"] * 1.8 }
} };
return aura;
end
else
temptable["func"] = function(rank, stats, weaponStats, itemStats, level, special)
local aura = { ["defense"] = {
["armor"] = { ["base"] = itemStats["defense"]["armor"]["posMod"] * 4 }
} };
return aura;
end
end
table.insert(auras[2], temptable);
table.insert(auras[1], temptable2);
end
local temp = level;
if temp > 60 then temp = 60 end;
if special["druidForm"] == "bear" then
stats["melee"]["mainHandSpeed"]["base"] = 2.50;
stats["melee"]["mainHandDmgMin"]["base"] = temp * 0.85 * 2.50;
stats["melee"]["mainHandDmgMax"]["base"] = temp * 1.25 * 2.50;
stats["melee"]["attackPower"]["posMod"] = stats["melee"]["attackPower"]["posMod"] + temp * 3;
elseif special["druidForm"] == "cat" then
stats["melee"]["mainHandSpeed"]["base"] = 1.00;
stats["melee"]["mainHandDmgMin"]["base"] = temp * 0.85;
stats["melee"]["mainHandDmgMax"]["base"] = temp * 1.25;
stats["melee"]["attackPower"]["posMod"] = stats["melee"]["attackPower"]["posMod"] + temp * 2;
end
--------------------------------------------------
--ADD RACIAL/BUFF/TALENT BONUSES TO STATS--
--------------------------------------------------
--racial bonuses, most of 'em at least (some exceptions like tauren health are added later on)
auras = ScrubBuster:GetRacials(race, class, stats, weaponStats, auras);
--Get talents
auras = ScrubBuster:GetTalents(inspect, class, auras);
--Before going on to secondary stats, add "priority 1" auras, ie. auras that affect primary stats
stats = ScrubBuster:AddAuras(stats, auras[1], weaponStats, itemStats, level, class, special);
--Apply multipliers for primary stats
for k,v in pairs(stats["primary"]) do
v["base"] = v["base"] * v["mult"] + (v["posMod"] * v["mult"] - v["posMod"]);
end
------------------------------
--FIGURE OUT SECONDARY STATS--
------------------------------
--we need to figure out secondary stats gained from primary stats.
--secondary stats being stuff like attack power and such
local tempStr = stats["primary"]["str"]["base"] + stats["primary"]["str"]["posMod"] + stats["primary"]["str"]["negMod"];
local tempAgi = stats["primary"]["agi"]["base"] + stats["primary"]["agi"]["posMod"] + stats["primary"]["agi"]["negMod"];
local tempSta = stats["primary"]["sta"]["base"] + stats["primary"]["sta"]["posMod"] + stats["primary"]["sta"]["negMod"];
local tempInt = stats["primary"]["int"]["base"] + stats["primary"]["int"]["posMod"] + stats["primary"]["int"]["negMod"];
local tempSpi = stats["primary"]["spi"]["base"] + stats["primary"]["spi"]["posMod"] + stats["primary"]["spi"]["negMod"];
--Strength--
if class == "WARRIOR" or class == "SHAMAN" or class == "DRUID" or class == "PALADIN" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + tempStr * 2 - 20;
elseif class == "ROGUE" or class == "HUNTER" or class == "MAGE" or class == "PRIEST" or class == "WARLOCK" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + tempStr - 10;
end
if class == "WARRIOR" or class == "SHAMAN" or class == "PALADIN" then
stats["defense"]["blockValue"]["base"] = stats["defense"]["blockValue"]["base"] + math.floor(tempStr / 20 - 1);
end
--Agility--
if class == "HUNTER" or class == "ROGUE" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + tempAgi - 10;
elseif class == "DRUID" and special["druidForm"] == "cat" then
stats["melee"]["attackPower"]["base"] = stats["melee"]["attackPower"]["base"] + tempAgi;
end
stats["ranged"]["attackPower"]["base"] = stats["ranged"]["attackPower"]["base"] + tempAgi - 10;
stats["defense"]["armor"]["base"] = stats["defense"]["armor"]["base"] + (tempAgi * 2);
stats["melee"]["critPercent"]["base"] = stats["melee"]["critPercent"]["base"] + tempAgi * ScrubBuster.CritPerAgi[level][classID]
stats["ranged"]["critPercent"]["base"] = stats["ranged"]["critPercent"]["base"] + tempAgi * ScrubBuster.CritPerAgi[level][classID]
--dodge from agility uses the same multiplier as crit per agility, except some classes seem to have an extra multiplier
stats["defense"]["dodgePercent"]["base"] = stats["defense"]["dodgePercent"]["base"] + tempAgi * ScrubBuster.CritPerAgi[level][classID] * ScrubBuster.CritPerAgiToDodge[classID];
--Stamina--
stats["resource"]["health"]["base"] = stats["resource"]["health"]["base"] + tempSta * 10 - 180;
--Intellect--
stats["resource"]["mana"]["base"] = stats["resource"]["mana"]["base"] + tempInt * 15 - 280;
stats["spell"]["critPercent"]["base"] = stats["spell"]["critPercent"]["base"] + tempInt * ScrubBuster.SpellCritPerInt[level][classID];
--Spirit--
local tempBaseSpi = tempSpi;
if tempBaseSpi > 50 then tempBaseSpi = 50; end
local tempExtraSpi = tempSpi - tempBaseSpi;
stats["resource"]["healthRegen"]["base"] = stats["resource"]["healthRegen"]["base"] + (tempBaseSpi * ScrubBuster.HealthRegenPerSpi50[level][classID] + tempExtraSpi * ScrubBuster.HealthRegenPerSpi[classID]);
stats["resource"]["manaRegen"]["base"] = stats["resource"]["manaRegen"]["base"] + (0.001 + tempSpi * ScrubBuster.BaseManaRegenPerSpi[level] * (tempInt ^ 0.5)) * 5;
---Now that secondary stats are figured out, add secondary stat auras
stats = ScrubBuster:AddAuras(stats, auras[2], weaponStats, itemStats, level, class, special);
-----------------------
---SORT OUT RATINGS----
-----------------------
--Get IAS from haste rating and add it to melee and ranged IAS
local tempTotalHaste = stats["physical"]["hasteRating"]["base"] + stats["physical"]["hasteRating"]["posMod"] + stats["physical"]["hasteRating"]["negMod"];
local tempIAS = StatLogic:GetEffectFromRating(tempTotalHaste, CR_HASTE_MELEE, level);
tempIAS = tempIAS / 100;
stats["melee"]["increasedAttackSpeed"]["posMod"] = (1 + stats["melee"]["increasedAttackSpeed"]["posMod"]) * (1 + tempIAS) - 1;
stats["ranged"]["increasedAttackSpeed"]["posMod"] = (1 + stats["ranged"]["increasedAttackSpeed"]["posMod"]) * (1 + tempIAS) - 1;
--Get increased cast speed from spellhaste and add it to spell IAS
local tempTotalHaste = stats["spell"]["hasteRating"]["base"] + stats["spell"]["hasteRating"]["posMod"] + stats["spell"]["hasteRating"]["negMod"];
local tempIAS = StatLogic:GetEffectFromRating(tempTotalHaste, CR_HASTE_SPELL, level);
tempIAS = tempIAS / 100;
stats["spell"]["increasedAttackSpeed"]["posMod"] = (1 + stats["spell"]["increasedAttackSpeed"]["posMod"]) * (1 + tempIAS) - 1;
--Get defense from defense rating and add it to defense stat
local tempDefRating = stats["defense"]["defenseRating"]["base"] + stats["defense"]["defenseRating"]["posMod"] + stats["defense"]["defenseRating"]["negMod"];
local tempDefense = math.floor(StatLogic:GetEffectFromRating(tempDefRating, CR_DEFENSE_SKILL, level));
stats["defense"]["defense"]["posMod"] = stats["defense"]["defense"]["posMod"] + tempDefense;
--Get dodge from dodge rating and add it to dodge percent stat
local tempDodgeRating = stats["defense"]["dodgeRating"]["base"] + stats["defense"]["dodgeRating"]["posMod"] + stats["defense"]["dodgeRating"]["negMod"];
local tempDodge = StatLogic:GetEffectFromRating(tempDodgeRating, CR_DODGE, level);
stats["defense"]["dodgePercent"]["posMod"] = stats["defense"]["dodgePercent"]["posMod"] + tempDodge;
--Get parry from parry rating and add it to parry percent stat
local tempParryRating = stats["defense"]["parryRating"]["base"] + stats["defense"]["parryRating"]["posMod"] + stats["defense"]["parryRating"]["negMod"];
local tempParry = StatLogic:GetEffectFromRating(tempParryRating, CR_PARRY, level);
stats["defense"]["parryPercent"]["posMod"] = stats["defense"]["parryPercent"]["posMod"] + tempParry;
--get block from block rating and add it to block percent stat
local tempBlockRating = stats["defense"]["blockRating"]["base"] + stats["defense"]["blockRating"]["posMod"] + stats["defense"]["blockRating"]["negMod"];
local tempBlock = StatLogic:GetEffectFromRating(tempBlockRating, CR_BLOCK, level);
stats["defense"]["blockPercent"]["posMod"] = stats["defense"]["blockPercent"]["posMod"] + tempBlock;
--get melee crit from melee crit rating and add it to melee crit percent stat
local tempCritRating = stats["melee"]["critRating"]["base"] + stats["melee"]["critRating"]["posMod"] + stats["melee"]["critRating"]["negMod"];
local tempCrit = StatLogic:GetEffectFromRating(tempCritRating, CR_CRIT_MELEE, level);
stats["melee"]["critPercent"]["posMod"] = stats["melee"]["critPercent"]["posMod"] + tempCrit;
--get ranged crit from ranged crit rating and add it to ranged crit percent stat
local tempCritRating = stats["ranged"]["critRating"]["base"] + stats["ranged"]["critRating"]["posMod"] + stats["ranged"]["critRating"]["negMod"];
local tempCrit = StatLogic:GetEffectFromRating(tempCritRating, CR_CRIT_RANGED, level);
stats["ranged"]["critPercent"]["posMod"] = stats["ranged"]["critPercent"]["posMod"] + tempCrit;
--get spell crit from spell crit rating and add it to spell crit percent stat
local tempCritRating = stats["spell"]["critRating"]["base"] + stats["spell"]["critRating"]["posMod"] + stats["spell"]["critRating"]["negMod"];
local tempCrit = StatLogic:GetEffectFromRating(tempCritRating, CR_CRIT_SPELL, level);
stats["spell"]["critPercent"]["posMod"] = stats["spell"]["critPercent"]["posMod"] + tempCrit;
--get expertise from expertise rating and add it to expertise stat
local tempExpRating = stats["melee"]["expertiseRating"]["base"] + stats["melee"]["expertiseRating"]["posMod"] + stats["melee"]["expertiseRating"]["negMod"];
local tempExp = math.floor(StatLogic:GetEffectFromRating(tempExpRating, CR_EXPERTISE, level));
stats["melee"]["expertise"]["posMod"] = stats["melee"]["expertise"]["posMod"] + tempExp;
--get physical hit chance from hit rating and add it to hit percent stat
local tempHitRating = stats["physical"]["hitRating"]["base"] + stats["physical"]["hitRating"]["posMod"] + stats["physical"]["hitRating"]["negMod"];
local tempHit = StatLogic:GetEffectFromRating(tempHitRating, 6, level);
stats["physical"]["hitPercent"]["base"] = stats["physical"]["hitPercent"]["base"] + tempHit;
--get spell hit chance from spell hit rating and add it to spell hit percent stat
local tempSpellHitRating = stats["spell"]["hitRating"]["base"] + stats["spell"]["hitRating"]["posMod"] + stats["spell"]["hitRating"]["negMod"];
local tempSpellHit = StatLogic:GetEffectFromRating(tempSpellHitRating, 8, level);
stats["spell"]["hitPercent"]["base"] = stats["spell"]["hitPercent"]["base"] + tempSpellHit;
--Add effect of defense skill on dodge, block and parry, and chance to be critically hit or hit
--this assumes an equal level opponent
local temp = stats["defense"]
local tempDefense = temp["defense"]["base"] + temp["defense"]["posMod"] + temp["defense"]["negMod"];
local tempDefEffect = (tempDefense - level * 5) * 0.04;
temp["dodgePercent"]["base"] = temp["dodgePercent"]["base"] + tempDefEffect;
temp["parryPercent"]["base"] = temp["parryPercent"]["base"] + tempDefEffect;
temp["blockPercent"]["base"] = temp["blockPercent"]["base"] + tempDefEffect;
temp["critReduction"]["base"] = temp["critReduction"]["base"] + tempDefEffect;
temp["hitReduction"]["base"] = temp["hitReduction"]["base"] + tempDefEffect;
--Add effect of resilience on critReduction
local tempResilience = temp["resilience"]["base"] + temp["resilience"]["posMod"] + temp["resilience"]["negMod"];
local tempResEffect = StatLogic:GetEffectFromRating(tempResilience, CR_CRIT_TAKEN_MELEE, level);
temp["critReduction"]["base"] = temp["critReduction"]["base"] + tempResEffect;
------------------------
---REST OF THE THINGS---
------------------------
--priority 3 auras, aka the special needs auras
stats = ScrubBuster:AddAuras(stats, auras[3], weaponStats, itemStats, level, class, special);
--Apply non-primary stat multipliers
for k,v in pairs(stats) do
if k ~= "primary" then
for k2,v2 in pairs(v) do
v2["base"] = v2["base"] * v2["mult"] + (v2["posMod"] * v2["mult"] - v2["posMod"]);
end
end
end
--Add common expertise to mainhand and offhand expertises
local temp = stats["melee"]
temp["mainHandExpertise"]["base"] = temp["mainHandExpertise"]["base"] + temp["expertise"]["base"];
temp["mainHandExpertise"]["posMod"] = temp["mainHandExpertise"]["posMod"] + temp["expertise"]["posMod"];
temp["mainHandExpertise"]["negMod"] = temp["mainHandExpertise"]["negMod"] + temp["expertise"]["negMod"];
temp["offHandExpertise"]["base"] = temp["offHandExpertise"]["base"] + temp["expertise"]["base"];
temp["offHandExpertise"]["posMod"] = temp["offHandExpertise"]["posMod"] + temp["expertise"]["posMod"];
temp["offHandExpertise"]["negMod"] = temp["offHandExpertise"]["negMod"] + temp["expertise"]["negMod"];
--Add common physical hit chance to melee and ranged hit chances
temp["hitPercent"]["base"] = temp["hitPercent"]["base"] + stats["physical"]["hitPercent"]["base"];
temp["hitPercent"]["posMod"] = temp["hitPercent"]["posMod"] + stats["physical"]["hitPercent"]["posMod"];
temp["hitPercent"]["negMod"] = temp["hitPercent"]["negMod"] + stats["physical"]["hitPercent"]["negMod"];
local temp = stats["ranged"];
temp["hitPercent"]["base"] = temp["hitPercent"]["base"] + stats["physical"]["hitPercent"]["base"];
temp["hitPercent"]["posMod"] = temp["hitPercent"]["posMod"] + stats["physical"]["hitPercent"]["posMod"];
temp["hitPercent"]["negMod"] = temp["hitPercent"]["negMod"] + stats["physical"]["hitPercent"]["negMod"];
--Add common melee crit chance to hand specific crit chances
local temp = stats["melee"];
temp["mainHandCritPercent"]["base"] = temp["mainHandCritPercent"]["base"] + temp["critPercent"]["base"];
temp["offHandCritPercent"]["base"] = temp["offHandCritPercent"]["base"] + temp["critPercent"]["base"];
temp["mainHandCritPercent"]["posMod"] = temp["mainHandCritPercent"]["posMod"] + temp["critPercent"]["posMod"];
temp["offHandCritPercent"]["posMod"] = temp["offHandCritPercent"]["posMod"] + temp["critPercent"]["posMod"];
temp["mainHandCritPercent"]["negMod"] = temp["mainHandCritPercent"]["negMod"] + temp["critPercent"]["negMod"];
temp["offHandCritPercent"]["negMod"] = temp["offHandCritPercent"]["negMod"] + temp["critPercent"]["negMod"];
--Add general spell damage to specific school spell damages
local schools = { "holy", "fire", "nature", "frost", "shadow", "arcane" };
local tempBase = stats["spell"]["damage"]["base"];
local tempPosMod = stats["spell"]["damage"]["posMod"];
local tempNegMod = stats["spell"]["damage"]["negMod"];
for i = 1, 6 do
local stat = stats["spell"][schools[i].."Damage"];
stat["base"] = stat["base"] + tempBase;
stat["posMod"] = stat["posMod"] + tempPosMod;
stat["negMod"] = stat["negMod"] + tempNegMod;
end
--do the same for crit chance
local tempBase = stats["spell"]["critPercent"]["base"];
local tempPosMod = stats["spell"]["critPercent"]["posMod"];
local tempNegMod = stats["spell"]["critPercent"]["negMod"];
for i = 1, 6 do
local stat = stats["spell"][schools[i].."CritPercent"];
stat["base"] = stat["base"] + tempBase;
stat["posMod"] = stat["posMod"] + tempPosMod;
stat["negMod"] = stat["negMod"] + tempNegMod;
end
--....and for hit chance
local tempBase = stats["spell"]["hitPercent"]["base"];
local tempPosMod = stats["spell"]["hitPercent"]["posMod"];
local tempNegMod = stats["spell"]["hitPercent"]["negMod"];
for i = 1, 6 do
local stat = stats["spell"][schools[i].."HitPercent"];
stat["base"] = stat["base"] + tempBase;
stat["posMod"] = stat["posMod"] + tempPosMod;
stat["negMod"] = stat["negMod"] + tempNegMod;
end
--Attack power to damage
--AP/14*speed + weapondamage is the final damage as appears on the character sheet
local tempAP = stats["melee"]["attackPower"]["base"] + stats["melee"]["attackPower"]["posMod"] + stats["melee"]["attackPower"]["negMod"];
local tempMHSpeed;
if not weaponStats.mainHand.speed then
tempMHSpeed = 2.00;
else
tempMHSpeed = weaponStats.mainHand.speed;
end
local tempOHSpeed;
if not weaponStats.offHand.speed then
tempOHSpeed = 2.00;
else
tempOHSpeed = weaponStats.offHand.speed;
end
stats["melee"]["mainHandDmgMin"]["base"] = stats["melee"]["mainHandDmgMin"]["base"] + (tempAP / 14 * tempMHSpeed);
stats["melee"]["mainHandDmgMax"]["base"] = stats["melee"]["mainHandDmgMax"]["base"] + (tempAP / 14 * tempMHSpeed);
stats["melee"]["offHandDmgMin"]["base"] = stats["melee"]["offHandDmgMin"]["base"] + (tempAP / 14 * tempOHSpeed);
stats["melee"]["offHandDmgMax"]["base"] = stats["melee"]["offHandDmgMax"]["base"] + (tempAP / 14 * tempOHSpeed);
--Ranged attack power to damage
--same formula as above
if weaponStats["ranged"]["isWeapon"] and weaponStats["ranged"]["weaponType"][2] ~= "WAND" then
local tempRAP = stats["ranged"]["attackPower"]["base"] + stats["ranged"]["attackPower"]["posMod"] + stats["ranged"]["attackPower"]["negMod"];
local tempRangedSpeed;
if not weaponStats.ranged.speed then
tempRangedSpeed = 2.00;
else
tempRangedSpeed = weaponStats.ranged.speed;
end
stats["ranged"]["dmgMin"]["base"] = stats["ranged"]["dmgMin"]["base"] + (tempRAP / 14 * tempRangedSpeed);
stats["ranged"]["dmgMax"]["base"] = stats["ranged"]["dmgMax"]["base"] + (tempRAP / 14 * tempRangedSpeed);
end
--Calculate attack speed after IAS
local tempMeleeIAS = (1 + stats["melee"]["increasedAttackSpeed"]["base"]) * (1 + stats["melee"]["increasedAttackSpeed"]["posMod"]) / (1 + stats["melee"]["increasedAttackSpeed"]["negMod"]);
local tempRangedIAS = (1 + stats["ranged"]["increasedAttackSpeed"]["base"]) * (1 + stats["ranged"]["increasedAttackSpeed"]["posMod"]) / (1 + stats["ranged"]["increasedAttackSpeed"]["negMod"]);
stats["melee"]["mainHandSpeed"]["base"] = stats["melee"]["mainHandSpeed"]["base"] / tempMeleeIAS;
stats["melee"]["offHandSpeed"]["base"] = stats["melee"]["offHandSpeed"]["base"] / tempMeleeIAS;
stats["ranged"]["speed"]["base"] = stats["ranged"]["speed"]["base"] / tempRangedIAS;
--Weapon damage multipliers
local tempMhMax = stats["melee"]["mainHandDmgMax"];
local tempMhMin = stats["melee"]["mainHandDmgMin"];
local tempMhDM = stats["melee"]["mainHandDamageMultiplier"]["mult"];
local tempOhMax = stats["melee"]["offHandDmgMax"];
local tempOhMin = stats["melee"]["offHandDmgMin"];
local tempOhDM = stats["melee"]["offHandDamageMultiplier"]["mult"];
local tempRangedMax = stats["ranged"]["dmgMax"];
local tempRangedMin = stats["ranged"]["dmgMin"];
local tempRangedDM = stats["ranged"]["damageMultiplier"]["mult"];
tempMhMax["base"] = tempMhMax["base"] * tempMhDM;
tempMhMin["base"] = tempMhMin["base"] * tempMhDM;
tempOhMax["base"] = tempOhMax["base"] * tempOhDM;
tempOhMin["base"] = tempOhMin["base"] * tempOhDM;
tempRangedMax["base"] = tempRangedMax["base"] * tempRangedDM;
tempRangedMin["base"] = tempRangedMin["base"] * tempRangedDM;
--Calculate weapon DPS
local tempMhAvg = ((stats["melee"]["mainHandDmgMin"]["base"] + stats["melee"]["mainHandDmgMin"]["posMod"] + stats["melee"]["mainHandDmgMin"]["negMod"]) + (stats["melee"]["mainHandDmgMax"]["base"] + stats["melee"]["mainHandDmgMax"]["posMod"] + stats["melee"]["mainHandDmgMax"]["negMod"])) / 2;
local tempOhAvg = ((stats["melee"]["offHandDmgMin"]["base"] + stats["melee"]["offHandDmgMin"]["posMod"] + stats["melee"]["offHandDmgMin"]["negMod"]) + (stats["melee"]["offHandDmgMax"]["base"] + stats["melee"]["offHandDmgMax"]["posMod"] + stats["melee"]["offHandDmgMax"]["negMod"])) / 2;
local tempRangedAvg = ((stats["ranged"]["dmgMin"]["base"] + stats["ranged"]["dmgMin"]["posMod"] + stats["ranged"]["dmgMin"]["negMod"]) + (stats["ranged"]["dmgMax"]["base"] + stats["ranged"]["dmgMax"]["posMod"] + stats["ranged"]["dmgMax"]["negMod"])) / 2;
if weaponStats["ranged"]["weaponType"][2] == "WAND" then
--wands don't get damage bonuses...
tempRangedAvg = (stats["ranged"]["dmgMin"]["base"] + stats["ranged"]["dmgMax"]["base"]) / 2;
end
stats["melee"]["mainHandDps"]["base"] = tempMhAvg / stats["melee"]["mainHandSpeed"]["base"];
stats["melee"]["offHandDps"]["base"] = tempOhAvg / stats["melee"]["offHandSpeed"]["base"];
stats["ranged"]["dps"]["base"] = tempRangedAvg / stats["ranged"]["speed"]["base"];
--If they can't block or parry, set their block or parry chance to 0
if not canBlock then
stats["defense"]["blockPercent"]["base"] = 0;
stats["defense"]["blockPercent"]["posMod"] = 0;
stats["defense"]["blockPercent"]["negMod"] = 0;
end
if not canParry then
stats["defense"]["parryPercent"]["base"] = 0;
stats["defense"]["parryPercent"]["posMod"] = 0;
stats["defense"]["parryPercent"]["negMod"] = 0;
end
return level, stats, weaponStats, itemStats;
end
function ScrubBuster:GetTalents(inspect, class, auras)
--inspect is bool, false to check player's talents, true to check inspect's talents
--stats and weaponStats are the stats tables from GetStats
--special is the special effects table from GetStats, things like warrior stances and druid forms
--returns the applicable talent auras of the character
--local auras = { [1] = {}, [2] = {}, [3] = {}, [4] = {} };
local numTabs = GetNumTalentTabs(inspect);
local talentBonuses = ScrubBuster.TalentBonuses[class];
for tab = 1, numTabs do
local numTalents = GetNumTalents(tab, inspect);
--local tabName = GetTalentTabInfo(tab, inspect);
for tal = 1, numTalents do
local talentName, _, _, _, rank = GetTalentInfo(tab, tal, inspect);
if rank > 0 then
if talentBonuses[talentName] then
--local talentEffect = talentBonuses[talentName]["func"](rank, stats, weaponStats, itemStats);
local prio = talentBonuses[talentName]["prio"];
local temptable = {
["isTalent"] = true;
["talentRank"] = rank;
["func"] = talentBonuses[talentName]["func"];
};
table.insert(auras[prio], temptable);
--some talents have two effects of different priorities, so we need this
--ugly thing to account for those. There should be no talents with three
--different priorities (thank goodness) so this will suffice
local prio2 = talentBonuses[talentName]["prio2"];
if prio2 then
local temptable = {
["isTalent"] = true;
["talentRank"] = rank;
["func"] = talentBonuses[talentName]["func2"];
};
table.insert(auras[prio2], temptable);
end
end
end
end
end
return auras;
end
function ScrubBuster:CheckLineForDamage(line, dmgtable)
--checks the line (from a tooltip) for damage values, and adds them to the damage table
--returns damagetable with any found damage added to it
local dmg, dmgmin, dmgmax, school;
--check regular physical damage (eg. 50 - 80 Damage)
_, _, dmgmin, dmgmax = string.find(line, sbDamageTemplate);
if dmgmin and dmgmax then
dmgmin, dmgmax = tonumber(dmgmin), tonumber(dmgmax);
dmgtable["MIN"]["PHYSICAL"] = dmgtable["MIN"]["PHYSICAL"] + dmgmin;
dmgtable["MAX"]["PHYSICAL"] = dmgtable["MAX"]["PHYSICAL"] + dmgmax;
end
dmgmin, dmgmax = nil, nil; --reset the vars so they won't fuk up the rest of the func
--check for regular elemental damages (eg. 50 - 80 Fire Damage)
_, _, dmgmin, dmgmax, school = string.find(line, sbElementalDamageTemplate);
if dmgmin and dmgmax and school and (dmgtable["MIN"][string.upper(school)] ~= nil) then
dmgmin, dmgmax = tonumber(dmgmin), tonumber(dmgmax);
school = sbDamageTypes[school];
dmgtable["MIN"][school] = dmgtable["MIN"][school] + dmgmin;
dmgtable["MAX"][school] = dmgtable["MAX"][school] + dmgmax;
end
dmgmin, dmgmax, school = nil, nil, nil;
--check for any extra physical damage
_,_, dmg = string.find(line, sbExtraSingleDamageTemplate);
if dmg then
dmg = tonumber(dmg);
dmgtable["MIN"]["PHYSICAL"] = dmgtable["MIN"]["PHYSICAL"] + dmg; --I think this is how this works
dmgtable["MAX"]["PHYSICAL"] = dmgtable["MAX"]["PHYSICAL"] + dmg;
end
dmg = nil;
--check for any extra elemental damage (dunno what this would catch but can't hurt to catch it)
--oops, this actually catches "+x Spell Damage" things... hackfixed
_, _, dmg, school = string.find(line, sbExtraSingleElementalDamageTemplate);
if dmg and school and (dmgtable["MIN"][string.upper(school)] ~= nil) then
dmg = tonumber(dmg);
school = sbDamageTypes[school];
dmgtable["MIN"][school] = dmgtable["MIN"][school] + dmg;
dmgtable["MAX"][school] = dmgtable["MAX"][school] + dmg;
end
dmg, school = nil, nil;
return dmgtable;
end
function ScrubBuster:ScanWeapTooltip(itemlink)
--Scans the tooltip of the itemlink for weapon stats/buffs, ie. damage, speed, dps, crit rating (for that wep)
--Returns table of damage values, speed, dps as it appears in tooltip, (crit rating??? not right now), weapontype
ScrubBusterTooltip:ClearLines();
ScrubBusterTooltip:SetHyperlink(itemlink)
local leftText, rightText, leftLine, rightLine;
local numlines = ScrubBusterTooltip:NumLines();
local tempweaponclass, tempweaponhand;
local speed; --speed will be nil if it's not found, but that's how we want it
local dps = 0; --default dps is 0 in case it's not found on the item
local weapontype = { };
local isweapon = false;
local damagetable = {
MIN = {
PHYSICAL = 0,
ARCANE = 0,
FIRE = 0,
NATURE = 0,
FROST = 0,
SHADOW = 0,
HOLY = 0
},
MAX = {
PHYSICAL = 0,
ARCANE = 0,
FIRE = 0,
NATURE = 0,
FROST = 0,
SHADOW = 0,
HOLY = 0
},
};
for i = 2, numlines, 1 do --read the lines one by one and get the info we want if it's there
leftText = getglobal("ScrubBusterTooltipTextLeft"..i);
rightText = getglobal("ScrubBusterTooltipTextRight"..i);
leftLine = leftText:GetText();
rightLine = rightText:GetText();
-------------------
--CHECK LEFT LINE--
-------------------
if leftLine then --if lefttext exists, we read it
--from the left we want weapon "handedness", damage, and dps.
--We may also want +crit from sharpening stones, but I'm not sure yet. Needs testing.
--check weapon handedness, only if we don't know it already
if not tempweaponhand then
if leftLine == getglobal("INVTYPE_HOLDABLE") then
tempweaponhand = "OFFHAND";
tempweaponclass = "OFFHANDITEM";
elseif sbWeaponHand[leftLine] then tempweaponhand = sbWeaponHand[leftLine]
end
end
--check weapon DPS if we don't know it yet
if not dps then
_, _, _, dps = string.find(leftLine, sbDPSTemplate);
if not dps then --check the second template
_, _, _, dps = string.find(leftLine, sbDPSTemplate2);
end
end
--check if the line has any damage values and if yes add them to our table
damagetable = ScrubBuster:CheckLineForDamage(leftLine, damagetable);
end
--------------------
--CHECK RIGHT LINE--
--------------------
if rightLine then
--on the right all we care about is weapon class and weapon speed
--check weapon class (eg. axe, sword) if we don't know it yet
if not tempweaponclass then
if sbWeaponClasses[rightLine] then
tempweaponclass = sbWeaponClasses[rightLine]
local notweapons = {
["SHIELD"] = true,
["IDOL"] = true,
["LIBRAM"] = true,
["TOTEM"] = true,
};
if not notweapons[tempweaponclass] then
isweapon = true;
end
end
end
--check weapon speed if we don't know it yet
if not speed then
_, _, speed = string.find(rightLine, sbSpeedTemplate);
if not speed then --if that didn't work, try the other template
_, _, speed = string.find(rightLine, sbSpeedTemplate2);
end
if speed then speed = string.gsub(speed, ",", ".") end
end
end
end
dps = tonumber(dps); --DPS is still a string, and we want a number
speed = tonumber(speed); --same story here.
if not tempweaponclass then tempweaponclass = "UNKNOWN" end
weapontype = { [1] = tempweaponhand, [2] = tempweaponclass };
return damagetable, speed, dps, weapontype, isweapon
end
function ScrubBuster:CombineDamageTable(dmgtable)
--Combines the different damages in the damagetable from weapon tooltip scanning into totals,
--as they would appear in the character sheet under "Damage". Returns dmgmin and dmgmax
local dmgmin, dmgmax = 0, 0;
for k,v in pairs(dmgtable["MIN"]) do
dmgmin = dmgmin + v;
end
for k,v in pairs(dmgtable["MAX"]) do
dmgmax = dmgmax + v;
end
return dmgmin, dmgmax
end
function ScrubBuster:ScanAmmoTooltip(itemlink)
--scans the tooltip of the itemlink (which should be ammo, dummy) for how much damage the ammo does
--returns the DPS increase, and the type of the ammo (bullet/arrow)
ScrubBusterTooltip:ClearLines();
ScrubBusterTooltip:SetHyperlink(itemlink)
local leftText, rightText, leftLine, rightLine;
local numlines = ScrubBusterTooltip:NumLines();
local tempdps, tempschool;
local ammotype;
local dpstable = {
PHYSICAL = 0,
ARCANE = 0,
FIRE = 0,
NATURE = 0,
FROST = 0,
SHADOW = 0,
HOLY = 0
};
for i = 2, numlines, 1 do
leftText = getglobal("ScrubBusterTooltipTextLeft"..i);
rightText = getglobal("ScrubBusterTooltipTextRight"..i);
leftLine = leftText:GetText();
rightLine = rightText:GetText();
if leftLine then
--if leftline exists, check if it has stuff we need, ie. the DPS value of the ammo
_, _, dps = string.find(leftLine, sbAmmoDamageTemplate);
if dps then
dps = tonumber(dps);
dpstable["PHYSICAL"] = dpstable["PHYSICAL"] + dps;
end
dps = nil;
_, _, dps, school = string.find(leftLine, sbAmmoElementalDamageTemplate);
if dps and school then
dps = tonumber(dps);
school = sbDamageTypes[school];
dpstable[school] = dpstable[school] + dps;
end
end
if rightLine then
--if rightline exists, check it for stuff we need, ie. the type of the ammo
if rightLine == "Arrow" then --this is a kinda shitty check that depends on localization
ammotype = "ARROW"; --however, there's no global that would help us here
elseif rightLine == "Bullet" then --just like is the case with weapon types
ammotype = "BULLET";
end
end
end
return dpstable, ammotype;
end
function ScrubBuster:GetRacials(race, class, stats, weaponStats, auras)
--Adds the player's racials to their auras. Takes in the respective stats from GetStats.
--returns the auras table with racials added to it.
if race == "Human" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = {
["melee"] = {
["mainHandExpertise"] = { ["base"] = 0 },
["offHandExpertise"] = { ["base"] = 0}
}
};
if weaponStats.mainHand.hasItem and (weaponStats.mainHand.weaponType[2] == 'SWORD' or weaponStats.mainHand.weaponType[2] == 'MACE') then
aura["melee"]["mainHandExpertise"]["base"] = 5;
end
if weaponStats.offHand.hasItem and (weaponStats.offHand.weaponType[2] == 'SWORD' or weaponStats.offHand.weaponType[2] == 'MACE') then
aura["melee"]["offHandExpertise"]["base"] = 5;
end
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["primary"] = { ["spi"] = { ["mult"] = 1.1 } } };
return aura;
end
};
table.insert(auras[2], effect1);
table.insert(auras[1], effect2);
elseif race == "Orc" then
local effect = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = {
["melee"] = {
["mainHandExpertise"] = { ["base"] = 0 },
["offHandExpertise"] = { ["base"] = 0}
}
};
if weaponStats.mainHand.hasItem and weaponStats.mainHand.weaponType[2] == 'AXE' then
aura["melee"]["mainHandExpertise"]["base"] = 5;
end
if weaponStats.offHand.hasItem and weaponStats.offHand.weaponType[2] == 'AXE' then
aura["melee"]["offHandExpertise"]["base"] = 5;
end
return aura;
end
};
table.insert(auras[2], effect);
elseif race == "Dwarf" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = {
["ranged"] = { ["critPercent"] = { ["base"] = 0 } }
};
if weaponStats.ranged.hasItem and weaponStats.ranged.weaponType[2] == 'GUN' then
aura["ranged"]["critPercent"]["base"] = 1;
end
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["frost"] = { ["posMod"] = 10 } } };
return aura;
end
};
table.insert(auras[2], effect1);
table.insert(auras[1], effect2);
elseif race == "NightElf" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["defense"] = { ["dodgePercent"] = { ["base"] = 1 } } };
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["nature"] = { ["posMod"] = 10 } } };
return aura;
end
};
table.insert(auras[2], effect1);
table.insert(auras[1], effect2);
elseif race == "Scourge" then
local effect = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["shadow"] = { ["posMod"] = 10 } } };
return aura;
end
};
table.insert(auras[1], effect);
elseif race == "Tauren" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["nature"] = { ["posMod"] = 10 } } };
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resource"] = { ["health"] = { ["mult"] = 1.05 } } };
return aura;
end
};
table.insert(auras[1], effect1);
table.insert(auras[2], effect2);
elseif race == "Gnome" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["primary"] = { ["int"] = { ["mult"] = 1.05 } } };
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["arcane"] = { ["posMod"] = 10 } } };
return aura;
end
};
table.insert(auras[1], effect1);
table.insert(auras[1], effect2);
elseif race == "Troll" then
--turns out the health regen racial is actually *rate*, not magnitude.
local effect = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["ranged"] = { ["critPercent"] = { ["base"] = 0 } } };
if weaponStats.ranged.hasItem and (weaponStats.ranged.weaponType[2] == 'BOW' or weaponStats.ranged.weaponType[2] == 'THROWN') then
aura["ranged"]["critPercent"]["base"] = 1;
end
return aura;
end
};
table.insert(auras[2], effect);
elseif race == "BloodElf" then
local effect = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = {
["resist"] = {
["arcane"] = { ["posMod"] = 5 },
["fire"] = { ["posMod"] = 5 },
["nature"] = { ["posMod"] = 5},
["frost"] = { ["posMod"] = 5},
["shadow"] = { ["posMod"] = 5}
}
};
return aura;
end
};
table.insert(auras[1], effect);
elseif race == "Draenei" then
local effect1 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = { ["resist"] = { ["shadow"] = { ["posMod"] = 10 } } };
return aura;
end
};
local effect2 = {
["isRacial"] = true;
["func"] = function(weaponStats, class)
local aura = {
["physical"] = { ["hitPercent"] = { ["base"] = 0 } },
["spell"] = { ["hitPercent"] = { ["base"] = 0 } },
};
if class == "WARRIOR" or class == "PALADIN" or class == "HUNTER" then
aura["physical"]["hitPercent"]["base"] = 1;
elseif class == "PRIEST" or class == "MAGE" or class == "SHAMAN" then
aura["spell"]["hitPercent"]["base"] = 1;
end
return aura;
end
};
table.insert(auras[1], effect1);
table.insert(auras[2], effect2);
end
return auras;
end
|
local assets=
{
Asset("ANIM", "anim/cutstone.zip"),
}
local function fn(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
MakeInventoryPhysics(inst)
inst.AnimState:SetBank("cutstone")
inst.AnimState:SetBuild("cutstone")
inst.AnimState:PlayAnimation("idle")
inst:AddComponent("stackable")
inst.components.stackable.maxsize = TUNING.STACK_SIZE_LARGEITEM
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst:AddComponent("repairer")
inst.components.repairer.repairmaterial = "stone"
inst.components.repairer.healthrepairvalue = TUNING.REPAIR_CUTSTONE_HEALTH
return inst
end
return Prefab( "common/inventory/cutstone", fn, assets)
|
local util = {}
function util.map(t, fn)
local res = {}
for k, v in pairs(t) do res[k] = fn(v, k) end
return res
end
function util.find(t, fn)
local res = {}
for k, v in pairs(t) do
if fn(v, k) then return v end
end
end
function util.filter(t, fn)
local res = {}
for k,v in pairs(t) do
if fn(v) then
table.insert(res, v)
end
end
return res
end
function util.values(t)
local res = {}
for _, value in pairs(t) do
table.insert(res, value)
end
return res
end
function util.compose(f, g)
return function(...) return f(g(...)) end
end
function util.bind1(func, x)
return function(y)
return func(x, y)
end
end
function util.trim(s)
return s:gsub('^%s+', ''):gsub('%s$', ''):gsub('%s%s+', ' ')
end
function util.coerceValue(node, schemaType, variables)
variables = variables or {}
if schemaType.__type == 'NonNull' then
return util.coerceValue(node, schemaType.ofType, variables)
end
if not node then
return nil
end
if node.kind == 'variable' then
return variables[node.name.value]
end
if schemaType.__type == 'List' then
if node.kind ~= 'list' then
error('Expected a list')
end
return util.map(node.values, function(value)
return util.coerceValue(node.values[i], schemaType.ofType, variables)
end)
end
if schemaType.__type == 'InputObject' then
if node.kind ~= 'inputObject' then
error('Expected an input object')
end
return util.map(node.values, function(field)
if not schemaType.fields[field.name] then
error('Unknown input object field "' .. field.name .. '"')
end
return util.coerceValue(field.value, schemaType.fields[field.name].kind, variables)
end)
end
if schemaType.__type == 'Enum' then
if node.kind ~= 'enum' then
error('Expected enum value, got ' .. node.kind)
end
if not schemaType.values[node.value] then
error('Invalid enum value "' .. node.value .. '"')
end
return node.value
end
if schemaType.__type == 'Scalar' then
if schemaType.parseLiteral(node) == nil then
error('Could not coerce "' .. tostring(node.value) .. '" to "' .. schemaType.name .. '"')
end
return schemaType.parseLiteral(node)
end
end
return util
|
updateSystems = {
timerSystem = System ({"timer"},
function(e)
if (e.timer.lifetime > 0) then
e.timer.lifetime -= 1
else
e.timer.trigger()
del(world, e)
end
end
),
motionSystem = System({"pos", "vel"},
function(e)
e.pos.x += e.vel.x
e.pos.y += e.vel.y
end
),
animationSystem = System({"ani"},
function(e)
if (e.ani.loop) then
e.ani.frame += e.ani.framerate
if (e.ani.frame >= e.ani.framecount) then
e.ani.frame = 0
end
else
if (e.ani.frame < e.ani.framecount-1) then
e.ani.frame += e.ani.framerate
end
end
end
),
collisionSystem = System({"id", "pos", "box"},
function(e1)
-- player
if (e1.id.class == "player") then
-- player vs ebullet
local ebullets = getEntitiesBySubclass("ebullet", world)
for e2 in all(ebullets) do
if coll(e1, e2) then
sfx(6)
e1.hp -=1
RectSpark(gecx(e1), gecy(e1), 6, 6, 11)
spawnFragments(gecx(e2), gecy(e2))
del(world, e2)
end
end
-- player vs asteroid/enemy
local enemies = getEntitiesByClass("enemy", world)
for e2 in all(enemies) do
if coll(e1, e2) then
e2.hp = 0
e1.hp -= 1
end
end
-- friendly bullet vs enemy
elseif (e1.id.subclass == "fbullet") then
local enemies = getEntitiesByClass("enemy", world)
for e2 in all(enemies) do
if coll(e1, e2) then
sfx(9)
spawnFragments(gecx(e1), gecy(e1))
del(world, e1)
e2.hp -= 1
e2.hitframe = true
end
end
-- hostile bullet vs asteroid
elseif (e1.id.subclass == "ebullet") then
local asteroids = getEntitiesBySubclass("asteroid", world)
for e2 in all(asteroids) do
if coll(e1, e2) then
sfx(11)
spawnFragments(gecx(e1), gecy(e1))
del(world, e1)
e2.hp -= 1
e2.hitframe = true
end
end
end
end
),
healthSystem = System({"id", "hp"},
function(e)
if e.hp <= 0 then
-- explosion sfx is called from spawnExplosion()
if (e.id.class == "enemy") then
if (e.id.size == "small") then
spawnExplosion("small", gecx(e), gecy(e))
screenshake(5, 0.3)
elseif (e.id.size == "medium") then
spawnExplosion("medium", gecx(e), gecy(e))
screenshake(7, 0.5)
if (e.id.subclass == "asteroid") then
spawn_from_asteroid("medium", gecx(e), gecy(e))
end
elseif (e.id.size == "large") then
spawnExplosion("large", gecx(e), gecy(e))
screenshake(8, 0.5)
if (e.id.subclass == "asteroid") then
spawn_from_asteroid("large", gecx(e), gecy(e))
end
end
sfx(16)
elseif (e.id.class == "player") then
spawnExplosion("large", gecx(e), gecy(e))
screenshake(8, 0.5)
sfx(27)
add(G.carcasses, {x=e.pos.x, y=G.travelledDistance-e.pos.y})
exitGameplay("lose")
end
del(world, e)
end
end
),
keepInScreenSystem = System({"keepInScreen"},
function(e)
-- alternative implementation
-- e.pos.x = min(e.pos.x, 115)
-- e.pos.x = max(e.pos.x, 12)
-- e.pos.y = min(e.pos.y, 115)
-- e.pos.y = max(e.pos.y, 12)
if (e.pos.x > 115) then e.pos.x = 115 end
if (e.pos.x < 12) then e.pos.x = 12 end
if (e.pos.y > 115) then e.pos.y = 115 end
if (e.pos.y < 0) then e.pos.y = 0 end
end
),
outOfBoundsDestroySystem = System({"outOfBoundsDestroy"},
function(e)
if (e.pos.x > 127 + C.BOUNDS_OFFSET_SIDES)
or (e.pos.x < 0 - C.BOUNDS_OFFSET_SIDES)
or (e.pos.y > 127 + C.BOUNDS_OFFSET_BOTTOM)
or (e.pos.y < 0 - C.BOUNDS_OFFSET_TOP) then
del(world, e)
end
end
),
particleSystem = System({"particle"},
function(e)
if (e.particle.lifetime < e.particle.lifetime_max) then
e.particle.lifetime += 1
else
del(world, e)
end
end
),
sparkUpdateSystem = System({"spark"},
function(e)
e.spark.radius += C.SPARK_INCREMENT_RATE
end
),
fragmentUpdateSystem = System({"fragment"},
function(e)
e.fragment.radius *= e.fragment.radius_rate
e.vel.x *= e.fragment.vel_rate
e.vel.y *= e.fragment.vel_rate
if e.fragment.radius <= 0.1 then del(world, e) end
if (abs(e.vel.x) < 0.01 and abs(e.vel.y) < 0.01) then del(world, e) end
end
),
smokeUpdateSystem = System({"smoke"},
function(e)
e.smoke.radius -= C.SMOKE_DECREMENT_RATE
end
),
loopingStarSystem = System({"loopingStar"},
function(e)
if (e.pos.y > 128+C.BOUNDS_OFFSET_SIDES) then
e.pos.x = rnd(128)
e.pos.y = -8
e.vel.y = rnd(1.5)
end
end
),
-- harvesting system
harvesteeSystem = System({"harvestee"},
function(e)
if (e.harvestee.beingHarvested) then
if (e.harvestee.indicatorRadius > 2) then
e.harvestee.indicatorRadius -= 1
else
e.harvestee.indicatorRadius += 1
end
end
-- reset beingHarvested status when player is dead
if (not getPlayer(world)) then
e.harvestee.beingHarvested = false
end
end
),
harvesterSystem = System({"harvester"},
function(e)
asteroids = getEntitiesBySubclass("asteroid", world)
for a in all(asteroids) do
local harvest_distance
if (a.id.size == "large") then
harvest_distance = C.HARVEST_DISTANCE_LARGE
elseif (a.id.size == "medium") then
harvest_distance = C.HARVEST_DISTANCE_MEDIUM
elseif (a.id.size == "small") then
harvest_distance = C.HARVEST_DISTANCE_SMALL
end
if (measureDistance(gecx(e),gecy(e), gecx(a), gecy(a))
<= harvest_distance) then
a.harvestee.beingHarvested = true
if (e.harvester.progress < C.HARVEST_COMPLETE) then
e.harvester.progress +=1
sfx(7)
else
e.harvester.progress = 0
if (e.playerWeapon.ammo < C.PLAYER_AMMO_MAX) then
e.playerWeapon.ammo += 1
sfx(8)
end
end
else
a.harvestee.beingHarvested = false
end
end
end
),
-- enemy weapon system
-- enemy firing and attacking behaviour
enemyWeaponSystem = System({"enemyWeapon"},
function(e)
if (e.enemyWeapon.cooldown > 0) then
e.enemyWeapon.cooldown -= 1;
else
-- riley
-- fires one shot aiming at the player
if (e.enemyWeapon.type == "riley") then
if GameplayState.isRunning then sfx(15) end
local p = getPlayer(world)
if p then -- making sure that player exists
local angle, vx, vy
angle = atan2(gecx(p)-gecx(e), gecy(p)- gecy(e))
vx = C.RILEY_BULLET_VEL * cos(angle)
vy = C.RILEY_BULLET_VEL * sin(angle)
EBullet(gecx(e), gecy(e), vx, vy)
e.enemyWeapon.cooldown = C.RILEY_FIRERATE
end
-- dulce
-- "carpeting bombing" and leaves a line of bullets
elseif (e.enemyWeapon.type == "dulce") then
EBullet(gecx(e), gecy(e), 0, C.DULCE_BULLET_VY)
e.enemyWeapon.cooldown = C.DULCE_FIRERATE
-- hammerhead
-- fires two lateral shot on each side
elseif (e.enemyWeapon.type == "hammerhead") then
if GameplayState.isRunning then sfx(15) end
-- going clockwise from top right
-- right firing
EBullet(e.pos.x+6, e.pos.y+2,
C.HAMMERHEAD_BULLET_VX,
C.HAMMERHEAD_BULLET_VY
)
EBullet(e.pos.x+6, e.pos.y+12,
C.HAMMERHEAD_BULLET_VX,
C.HAMMERHEAD_BULLET_VY
)
-- left firing
EBullet(e.pos.x-2, e.pos.y+2,
-C.HAMMERHEAD_BULLET_VX,
C.HAMMERHEAD_BULLET_VY
)
EBullet(e.pos.x-2, e.pos.y+12,
-C.HAMMERHEAD_BULLET_VX,
C.HAMMERHEAD_BULLET_VY
)
e.enemyWeapon.cooldown = C.HAMMERHEAD_FIRERATE
-- augustus
-- fires three shot in an arc
elseif (e.enemyWeapon.type == "augustus") then
if GameplayState.isRunning then sfx(15) end
-- medial bullet
EBullet(e.pos.x+6, e.pos.y+16, 0, C.AUGUSTUS_BULLET_MEDIAL_VY)
-- lateral bullets
EBullet(e.pos.x+5, e.pos.y+16,
-C.AUGUSTUS_BULLET_LATERAL_VX,
C.AUGUSTUS_BULLET_LATERAL_VY
)
EBullet(e.pos.x+7, e.pos.y+16,
C.AUGUSTUS_BULLET_LATERAL_VX,
C.AUGUSTUS_BULLET_LATERAL_VY
)
e.enemyWeapon.cooldown = C.AUGUSTUS_FIRERATE
-- koltar
-- fires four shot in alternative modes
-- axis aligned and diagonally
elseif (e.enemyWeapon.type == "koltar") then
if GameplayState.isRunning then sfx(18) end
local offset_x, offset_y = 15, 6
-- going clockwise from top
if (e.enemyWeapon.firemode == 0) then
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
0,
-C.KOLTAR_BULLET_VEL
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
C.KOLTAR_BULLET_VEL,
0
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
0,
C.KOLTAR_BULLET_VEL
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
-C.KOLTAR_BULLET_VEL,
0
)
e.enemyWeapon.firemode = 1
elseif (e.enemyWeapon.firemode == 1) then
local magnitude = C.KOLTAR_BULLET_VEL * 0.707
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
magnitude, -magnitude
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
magnitude, magnitude
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
-magnitude, magnitude
)
EBullet(e.pos.x+offset_x, e.pos.y+offset_y,
-magnitude, -magnitude
)
e.enemyWeapon.firemode = 0
end
e.enemyWeapon.cooldown = C.KOLTAR_FIRERATE
end
end
end
),
-- player-related systems
playerWeaponSystem = System({"playerWeapon"},
function(e)
if (e.playerWeapon.cooldown >0) then
e.playerWeapon.cooldown -= 1
end
end
),
controlSystem = System({"playerControl"},
function(e)
-- alternate implementation
-- codes allowed to remain
-- for documentation and educational purpose
-- local speed_value = (btn(4)) and c.player_speed_slow or c.player_speed_fast
-- local angle, speed
-- if (btn(0) or btn(1) or btn(2) or btn (3)) then
-- speed = speed_value
-- else
-- speed = 0
-- end
-- if (btn(0)) then
-- if (btn(2)) then
-- angle = 0.625
-- elseif (btn(3)) then
-- angle = 0.325
-- else
-- angle = 0.5
-- end
-- elseif (btn(1)) then
-- if (btn(2)) then
-- angle = 0.825
-- elseif (btn(3)) then
-- angle = 0.125
-- else
-- angle = 0.0
-- end
-- elseif (btn(2)) then
-- angle = 0.75
-- elseif (btn(3)) then
-- angle = 0.25
-- end
-- e.vel.x = speed * cos(angle)
-- e.vel.y = speed * -sin(angle) -- y axis is inverted
local speed = (btn(C.KEY_B))
and C.PLAYER_SPEED_SLOW
or C.PLAYER_SPEED_FAST
e.vel.x, e.vel.y = 0, 0
if (btn(0)) e.vel.x = -speed
if (btn(1)) e.vel.x = speed
if (btn(2)) e.vel.y = -speed
if (btn(3)) e.vel.y = speed
-- diagonal movement etiquette
if (e.vel.x * e.vel.y ~= 0) then
e.vel.x *= cos(0.125)
e.vel.y *= -sin(0.125) -- y axis is inverted
end
if (btnp(C.KEY_A)) then
if (e.playerWeapon.cooldown <=0
and e.playerWeapon.ammo > 0) then
sfx(5)
FBullet(e.pos.x, e.pos.y-5)
e.playerWeapon.cooldown = C.PLAYER_FIRERATE
e.playerWeapon.ammo -= 1
end
end
end
)
}
|
--Device detection
isError=0
function detectDevice(DeviceName)
DeviceSide="none"
for k,v in pairs(redstone.getSides()) do
if peripheral.getType(v)==DeviceName then
DeviceSide = v
break
end
end
return(DeviceSide)
end
function get_average(t)
local sum = 0
local count = 0
for k,v in pairs(t) do
if type(v) == 'number' then
sum = sum + v
count = count + 1
end
end
return (sum / count)
end
cell="none"
monitor="none"
local peripheralList = peripheral.getNames()
CellSide=detectDevice("cofh_thermalexpansion_energycell")
if CellSide~="none" then
cell=peripheral.wrap(CellSide)
print ("TE Energy cell on the " .. CellSide .. " connected.")
else
CellSide=detectDevice("tile_enderio_blockcapacitorbank_name")
if CellSide~="none" then
cell=peripheral.wrap(CellSide)
print ("EnderIO capacitorbank on the " .. CellSide .. " connected.")
else
for Index = 1, #peripheralList do
if string.find(peripheralList[Index], "cofh_thermalexpansion_energycell") then
cell=peripheral.wrap(peripheralList[Index])
print ("TE Energy cell on wired modem: "..peripheralList[Index].." connected.")
elseif string.find(peripheralList[Index], "tile_enderio_blockcapacitorbank_name") then
cell=peripheral.wrap(peripheralList[Index])
print ("EnderIO capacitorbank on wired modem: "..peripheralList[Index].." connected.")
end
end --for
if cell == "none" then
print("No Energy storage found. Halting script!")
return
end
end
end
MonitorSide=detectDevice("monitor")
if MonitorSide~="none" then
monitor=peripheral.wrap(MonitorSide)
print ("Monitor on the " .. MonitorSide .. " connected.")
else
for Index = 1, #peripheralList do
if string.find(peripheralList[Index], "monitor") then
monitor=peripheral.wrap(peripheralList[Index])
print ("Monitor on wired modem: "..peripheralList[Index].." connected.")
end
end --for
if monitor == "none" then
print ("Warning - No Monitor attached, continuing without.")
end
end
lastVal = 0
iterator = 0
allVals = {}
avg = 0
--Main loop
while true do
--Get storage values
-- monitor.setBackgroundColour((colours.green))
eNow = cell.getEnergyStored("unknown")
eMax = cell.getMaxEnergyStored("unknown")
perc = ((eNow / eMax) * 100 )
diff = 0
if lastVal > 0 then
diff = (eNow - lastVal) / 20
end
table.insert(allVals, diff)
reportTime = false
if (iterator % 5) == 1 then
-- this is a 5 sec loop
reportTime = true
avg = math.floor( get_average(allVals) )
allVals = {}
end
--If monitor is attached, write data on monitor
if monitor ~= "none" then
monitor.clear()
monitor.setTextScale(2)
monitor.setCursorPos(1,1)
monitor.write("Storage:")
monitor.setCursorPos(1,2)
monitor.write(perc.."% RF")
-- monitor.setCursorPos(1,3)
-- monitor.write("Of:")
-- monitor.setCursorPos(1,4)
-- monitor.write(eMax.." RF")
monitor.setCursorPos(1,3)
if avg > 0 then
monitor.setBackgroundColour((colours.green))
monitor.write("RF/t:"..avg)
elseif avg == 0 then
monitor.write("RF/t:"..avg)
else
monitor.setBackgroundColour((colours.red))
monitor.write("RF/t:"..avg)
end
monitor.setBackgroundColour((colours.black))
-- estimate seconds
monitor.setCursorPos(1,4)
remaining = eMax - eNow
if remaining > 0 then
if avg > 0 then
sec = math.floor( (remaining / (avg * 20)) )
hrs = 0
mins = 0
if sec > 60 then
mins = math.floor( (sec / 60) )
sec = sec - (mins * 60)
end
if mins > 60 then
hrs = math.floor( (mins / 60) )
mins = mins - (hrs * 60)
end
if hrs > 0 then
monitor.write("Time left: "..hrs.."h"..mins.."m"..sec.."s")
elseif mins > 0 then
monitor.write("Time left: "..mins.."m"..sec.."s")
else
monitor.write("Time left: "..sec.."s")
end
-- monitor.write("Time left: "..sec.." sec")
else
-- 200 eNow
-- -10 avg
-- 20 seconds
sec = math.floor( eNow / (avg * -20) )
hrs = 0
mins = 0
if sec > 60 then
mins = math.floor( (sec / 60) )
sec = sec - (mins * 60)
end
if mins > 60 then
hrs = math.floor( (mins / 60) )
mins = mins - (hrs * 60)
end
if hrs > 0 then
monitor.write("Time left: "..hrs.."h"..mins.."m"..sec.."s")
elseif mins > 0 then
monitor.write("Time left: "..mins.."m"..sec.."s")
else
monitor.write("Time left: "..sec.."s")
end
end
else
monitor.write("No time remaining.")
end
-- reset cursor
monitor.setCursorPos(1,1)
end
lastVal = cell.getEnergyStored("unknown")
iterator = iterator + 1
sleep(1)
end --while
|
local mh_id = ARGV[1];
local hgetall = function (key)
local bulk = redis.call("HGETALL", key)
local result = {}
local nextkey
for i, v in ipairs(bulk) do
if i % 2 == 1 then
nextkey = v
else
result[nextkey] = v
end
end
return result
end
-- TODO: Mabye do this, to reduce memory usage of the Lua script
-- http://danoyoung.blogspot.ca/2015/12/lua-scripting-with-redis.html, but with HSCAN
local assignations = hgetall("{BAMH}:MH_BRANCH_ASSIGNATIONS")
for i_branch_id, i_mh_id in pairs(assignations) do
if i_mh_id == mh_id or i_mh_id == "UNAVAILABLE" .. mh_id or i_mh_id == "SHUTTINGDOWN" .. mh_id then
redis.call("HDEL", "{BAMH}:MH_BRANCH_ASSIGNATIONS", i_branch_id)
end
end
redis.call("ZREM", "{BAMH}:MH_INSTANCES", mh_id)
redis.call("SREM", "{BAMH}:MH_INSTANCES_DYING", mh_id)
redis.call("SREM", "{BAMH}:MH_INSTANCES_SHUTTINGDOWN", mh_id)
redis.call("DEL", "{BAMH}:MHUSER_MH_FAILURES:" .. mh_id)
redis.call("DEL", "{BAMH}:MH_LIVELINESS:" .. mh_id)
|
local Logger = require("__DedLib__/modules/logger").create{modName = "Generic_Logistic_Chest"}
local DataUtil = require("scripts/data_util")
if Logger.FILE_LOG_LEVEL == "trace" then
Logger:trace_block(DataUtil.dumpLogisticChests())
end
|
ESX = nil
local PlayerData = {}
local isHarvesting = false
local cokeStep = 0
local methStep = 0
local cokeEntrance = 1
local methEntrance = 1
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
PlayerData = ESX.GetPlayerData()
end)
Citizen.Wait(0)
end
TriggerServerEvent('krp_druglabs:getEntrances')
end)
RegisterNetEvent('esx:playerLoaded')
AddEventHandler('esx:playerLoaded', function (xPlayer)
PlayerData = xPlayer
end)
RegisterNetEvent('krp_druglabs:setEntrances')
AddEventHandler('krp_druglabs:setEntrances', function (coke, meth)
cokeEntrance = coke
methEntrance = meth
end)
RegisterNetEvent('krp_druglabs:startProcessing')
AddEventHandler('krp_druglabs:startProcessing', function (type)
if type == 'meth' then
methStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the meth is being mixed')
runScenario("CODE_HUMAN_MEDIC_KNEEL", 'Mixing meth supplies...', Config.MethMixerTime, function()
TriggerEvent('esx:showNotification', 'The meth is now mixed')
methStep = 1
end)
else
cokeStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the coke is being cut')
runScenario("CODE_HUMAN_MEDIC_KNEEL", 'Cutting coke...', Config.CokeCuttingTime, function()
TriggerEvent('esx:showNotification', 'The coke is now cut')
cokeStep = 1
end)
end
end)
-- Draw markers
Citizen.CreateThread(function()
while true do
local sleep = 500
local ped = PlayerPedId()
local playerCoords = GetEntityCoords(ped, true)
-- COKE --
-- coke lab entrance
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeEntrances[cokeEntrance].x, Config.CokeEntrances[cokeEntrance].y, Config.CokeEntrances[cokeEntrance].z, true) <= 3.0 then
DrawText3D(Config.CokeEntrances[cokeEntrance].x, Config.CokeEntrances[cokeEntrance].y, Config.CokeEntrances[cokeEntrance].z + 1.0, 'Press [E] to enter the coke lab')
sleep = 0
if IsControlJustPressed(0, 38) then
enterCokeLab(ped)
end
end
-- coke lab locked entrances --
for i=1, #Config.CokeEntrances, 1 do
if i ~= cokeEntrance then
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeEntrances[i].x, Config.CokeEntrances[i].y, Config.CokeEntrances[i].z, true) <= 3.0 then
DrawText3D(Config.CokeEntrances[i].x, Config.CokeEntrances[i].y, Config.CokeEntrances[i].z + 1.0, 'This coke lab is currently closed')
sleep = 0
end
end
end
-- coke lab exit
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeExit.x, Config.CokeExit.y, Config.CokeExit.z, true) <= 2.0 then
DrawText3D(Config.CokeExit.x, Config.CokeExit.y, Config.CokeExit.z + 1.0, 'Press [E] to leave the coke lab')
sleep = 0
if IsControlJustPressed(0, 38) then
exitCokeLab(ped)
end
end
-- coke supply
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeSupply.x, Config.CokeSupply.y, Config.CokeSupply.z, true) <= 1.0 then
DrawText3D(Config.CokeSupply.x, Config.CokeSupply.y, Config.CokeSupply.z + 1.0, 'Press [E] to purchase black market coke supplies ($' .. Config.CokeSupplyPrice .. ')')
sleep = 0
if IsControlJustPressed(0, 38) then
TriggerServerEvent('krp_druglabs:buySupplies', 'coke')
end
end
-- coke harvest
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeField.x, Config.CokeField.y, Config.CokeField.z, true) <= 20.0 and isHarvesting == false then
DrawText3D(Config.CokeField.x, Config.CokeField.y, Config.CokeField.z + 1.0, 'Press [E] to harvest coke plant')
sleep = 0
if IsControlJustPressed(0, 38) then
isHarvesting = true
TriggerEvent('esx:showNotification', 'Please wait while the coke is being harvested')
runScenario("WORLD_HUMAN_GARDENER_PLANT", 'Harvesting coke...', Config.CokeFieldTime, function()
TriggerServerEvent('krp_druglabs:harvestCoke')
isHarvesting = false
end)
end
end
-- coke cutting (step 1)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeCutting.x, Config.CokeCutting.y, Config.CokeCutting.z, true) <= 2.0 and cokeStep == 0 then
DrawText3D(Config.CokeCutting.x, Config.CokeCutting.y, Config.CokeCutting.z + 0.5, 'Press [E] to cut coke supplies')
sleep = 0
if IsControlJustPressed(0, 38) then
-- check for supplies. if they have supplies then startProcessing is called
TriggerServerEvent('krp_druglabs:checkSupplies', 'coke')
end
end
-- coke weighing (step 2)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokeWeighing.x, Config.CokeWeighing.y, Config.CokeWeighing.z, true) <= 1.0 and cokeStep == 1 then
DrawText3D(Config.CokeWeighing.x, Config.CokeWeighing.y, Config.CokeWeighing.z + 0.5, 'Press [E] to weigh coke supplies')
sleep = 0
if IsControlJustPressed(0, 38) then
cokeStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the coke is being weighed')
runScenario("WORLD_HUMAN_STAND_IMPATIENT",'Weighing coke...', Config.CokeWeighingTime, function()
TriggerEvent('esx:showNotification', 'The coke is now weighed')
cokeStep = 2
end)
end
end
-- coke packaging (step 3)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.CokePackaging.x, Config.CokePackaging.y, Config.CokePackaging.z, true) <= 1.0 and cokeStep == 2 then
DrawText3D(Config.CokePackaging.x, Config.CokePackaging.y, Config.CokePackaging.z + 0.5, 'Press [E] to package coke')
sleep = 0
if IsControlJustPressed(0, 38) then
cokeStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the coke is being packaged')
runScenario("WORLD_HUMAN_STAND_IMPATIENT", 'Packaging coke...', Config.CokePackagingTime, function()
TriggerEvent('esx:showNotification', 'The coke is now packaged')
TriggerServerEvent('krp_druglabs:getDrug', 'coke')
cokeStep = 0
end)
end
end
-- METH --
-- meth lab entrance
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethEntrances[methEntrance].x, Config.MethEntrances[methEntrance].y, Config.MethEntrances[methEntrance].z, true) <= 3.0 then
DrawText3D(Config.MethEntrances[methEntrance].x, Config.MethEntrances[methEntrance].y, Config.MethEntrances[methEntrance].z + 1.0, 'Press [E] to enter the meth lab')
sleep = 0
if IsControlJustPressed(0, 38) then
enterMethLab(ped)
end
end
-- coke lab locked entrances --
for i=1, #Config.MethEntrances, 1 do
if i ~= methEntrance then
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethEntrances[i].x, Config.MethEntrances[i].y, Config.MethEntrances[i].z, true) <= 3.0 then
DrawText3D(Config.MethEntrances[i].x, Config.MethEntrances[i].y, Config.MethEntrances[i].z + 1.0, 'This meth lab is currently closed')
sleep = 0
end
end
end
-- meth lab exit
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethExit.x, Config.MethExit.y, Config.MethExit.z, true) <= 2.0 then
DrawText3D(Config.MethExit.x, Config.MethExit.y, Config.MethExit.z + 1.0, 'Press [E] to leave the meth lab')
sleep = 0
if IsControlJustPressed(0, 38) then
exitMethLab(ped)
end
end
-- meth supply
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethSupply.x, Config.MethSupply.y, Config.MethSupply.z, true) <= 1.0 then
DrawText3D(Config.MethSupply.x, Config.MethSupply.y, Config.MethSupply.z + 1.0, 'Press [E] to purchase black market meth supplies ($' .. Config.MethSupplyPrice .. ')')
sleep = 0
if IsControlJustPressed(0, 38) then
TriggerServerEvent('krp_druglabs:buySupplies', 'meth')
end
end
-- meth mixer (step 1)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethMixer.x, Config.MethMixer.y, Config.MethMixer.z, true) <= 1.0 and methStep == 0 then
DrawText3D(Config.MethMixer.x, Config.MethMixer.y, Config.MethMixer.z + 0.5, 'Press [E] to mix meth supplies')
sleep = 0
if IsControlJustPressed(0, 38) then
-- check for supplies. if they have supplies then startProcessing is called
TriggerServerEvent('krp_druglabs:checkSupplies', 'meth')
end
end
-- meth purifier (step 2)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethPurifier.x, Config.MethPurifier.y, Config.MethPurifier.z, true) <= 1.0 and methStep == 1 then
DrawText3D(Config.MethPurifier.x, Config.MethPurifier.y, Config.MethPurifier.z + 0.5, 'Press [E] to purify meth supplies')
sleep = 0
if IsControlJustPressed(0, 38) then
methStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the meth is being purified')
runScenario("WORLD_HUMAN_STAND_IMPATIENT", 'Purifying meth...', Config.MethPurifierTime, function()
TriggerEvent('esx:showNotification', 'The meth is now purified')
methStep = 2
end)
end
end
-- meth furnace (step 3)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethFurnace.x, Config.MethFurnace.y, Config.MethFurnace.z, true) <= 1.0 and methStep == 2 then
DrawText3D(Config.MethFurnace.x, Config.MethFurnace.y, Config.MethFurnace.z + 0.5, 'Press [E] to cook meth supplies')
sleep = 0
if IsControlJustPressed(0, 38) then
methStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the meth is cooking')
runScenario("WORLD_HUMAN_STAND_IMPATIENT", 'Cooking meth...', Config.MethFurnaceTime, function()
TriggerEvent('esx:showNotification', 'The meth is now cooked')
methStep = 3
end)
end
end
-- meth break and package (step 4)
if GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, Config.MethTable.x, Config.MethTable.y, Config.MethTable.z, true) <= 1.0 and methStep == 3 then
DrawText3D(Config.MethTable.x, Config.MethTable.y, Config.MethTable.z + 0.5, 'Press [E] to break up and package meth')
sleep = 0
if IsControlJustPressed(0, 38) then
methStep = -1
TriggerEvent('esx:showNotification', 'Please wait while the meth is broken up and packaged')
runScenario("WORLD_HUMAN_HAMMERING", 'Breaking up and packaging meth...', Config.MethTableTime, function()
TriggerEvent('esx:showNotification', 'The meth is now broken up and packaged')
TriggerServerEvent('krp_druglabs:getDrug', 'meth')
methStep = 0
end)
end
end
Citizen.Wait(sleep)
end
end)
-- enter/exit functions
function enterMethLab(ped)
DoScreenFadeOut(1000)
Citizen.Wait(1500)
SetEntityCoords(ped, Config.MethExit.x, Config.MethExit.y, Config.MethExit.z)
DoScreenFadeIn(1000)
end
function exitMethLab(ped)
DoScreenFadeOut(1000)
Citizen.Wait(1500)
SetEntityCoords(ped, Config.MethEntrances[methEntrance].x, Config.MethEntrances[methEntrance].y, Config.MethEntrances[methEntrance].z)
Citizen.Wait(1000)
DoScreenFadeIn(1000)
end
function enterCokeLab(ped)
DoScreenFadeOut(1000)
Citizen.Wait(1500)
SetEntityCoords(ped, Config.CokeExit.x, Config.CokeExit.y, Config.CokeExit.z)
DoScreenFadeIn(1000)
end
function exitCokeLab(ped)
DoScreenFadeOut(1000)
Citizen.Wait(1500)
SetEntityCoords(ped, Config.CokeEntrances[cokeEntrance].x, Config.CokeEntrances[cokeEntrance].y, Config.CokeEntrances[cokeEntrance].z)
Citizen.Wait(1000)
DoScreenFadeIn(1000)
end
function runScenario(scenario, label, ticks, cb)
TriggerEvent("mythic_progbar:client:progress", {
name = label,
duration = ticks,
label = label,
useWhileDead = false,
canCancel = false,
controlDisables = {
disableMovement = true,
disableCarMovement = true,
disableMouse = false,
disableCombat = true,
},
animation = {
animDict = nil,
anim = nil,
task = scenario
},
prop = {
model = nil
}
}, function(status)
if not status then
-- Do Something If Event Wasn't Cancelled
end
cb()
end)
end
function DrawText3D(x, y, z, text)
local onScreen,_x,_y=World3dToScreen2d(x,y,z)
local px,py,pz=table.unpack(GetGameplayCamCoords())
local scale = 0.45
if onScreen then
SetTextScale(scale, scale)
SetTextFont(4)
SetTextProportional(1)
SetTextColour(255, 255, 255, 215)
SetTextOutline()
SetTextEntry("STRING")
SetTextCentre(1)
AddTextComponentString(text)
DrawText(_x,_y)
local factor = (string.len(text)) / 370
DrawRect(_x, _y + 0.0150, 0.030 + factor , 0.030, 66, 66, 66, 150)
end
end
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = { {text = 'This weather is killing me. If I only had enough money to retire.'} }
npcHandler:addModule(VoiceModule:new(voices))
-- Travel
local function addTravelKeyword(keyword, cost, destination)
local travelKeyword = keywordHandler:addKeyword({keyword}, StdModule.say, {npcHandler = npcHandler, text = 'Do you seek a passage to ' .. keyword:titleCase() .. ' for |TRAVELCOST|?', cost = cost, discount = 'postman'})
travelKeyword:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, cost = cost, discount = 'postman', destination = destination})
travelKeyword:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'We would like to serve you some time.', reset = true})
end
addTravelKeyword('thais', 200, Position(32310, 32210, 6))
addTravelKeyword('carlin', 185, Position(32387, 31820, 6))
addTravelKeyword('ab\'dendriel', 90, Position(32734, 31668, 6))
addTravelKeyword('darashia', 210, Position(33289, 32480, 6))
addTravelKeyword('port hope', 260, Position(32527, 32784, 6))
addTravelKeyword('liberty bay', 275, Position(32285, 32892, 6))
addTravelKeyword('venore', 185, Position(32954, 32022, 6))
addTravelKeyword('ankrahmun', 230, Position(33092, 32883, 6))
-- Kick
keywordHandler:addKeyword({'kick'}, StdModule.kick, {npcHandler = npcHandler, destination = {Position(32811, 31267, 6), Position(32811, 31270, 6), Position(32811, 31273, 6)}})
-- Basic
keywordHandler:addKeyword({'sail'}, StdModule.say, {npcHandler = npcHandler, text = 'Where do you want to go? To {Thais}, {Carlin}, {Ab\'Dendriel}, {Ankrahmun}, {Darashia}, {Venore}, {Port Hope} or {Liberty Bay}?'})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the captain of this ship.'})
keywordHandler:addKeyword({'captain'}, StdModule.say, {npcHandler = npcHandler, text = 'I am the captain of this ship.'})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'I\'m Karith. I don\'t belong to a caste any longer, and only serve the Yalahari.'})
keywordHandler:addKeyword({'yalahar'}, StdModule.say, {npcHandler = npcHandler, text = 'The city was a marvel to behold. It is certain that it have been the many foreigners that ruined it.'})
npcHandler:setMessage(MESSAGE_GREET, "Hello! Tell me what's on your mind. Time is money.")
npcHandler:setMessage(MESSAGE_FAREWELL, "Good bye.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "Good bye.")
local focusModule = FocusModule:new()
focusModule:addGreetMessage({'hi', 'hello', 'ashari'})
focusModule:addFarewellMessage({'bye', 'farewell', 'asgha thrazi'})
npcHandler:addModule(focusModule)
|
local cwd = (...):gsub("%.[^%.]+$", "") .. "."
return {
name = "game_ruleviolation",
description = "Rule violation interface (Ctrl+Y)",
author = "andrefaramir",
website = "https://github.com/edubart/otclient",
sandboxed = true,
classPath = cwd .. "ruleviolation"
}
|
local icons_status_ok, icons = pcall(require, "nvim-nonicons")
if not icons_status_ok then
return
end
icons.get("file")
|
describe('average', function()
it('errors when its parent errors', function()
local _, onError = observableSpy(Rx.Observable.throw():average())
expect(#onError).to.equal(1)
end)
it('produces a single value representing the average of the values produced by the source', function()
expect(Rx.Observable.fromRange(3, 9, 2):average()).to.produce(6)
expect(Rx.Observable.fromTable({-1, 0, 1}):average()).to.produce(0)
end)
it('produces nothing if there are no values to average', function()
expect(Rx.Observable.empty():average()).to.produce.nothing()
end)
end)
|
require("compiler-sfc/src/compileTemplate")
require("compiler-sfc/src/parse")
test('should work', function()
local source = nil
local result = compileTemplate({filename='example.vue', source=source})
expect(#result.errors):toBe(0)
expect(result.source):toBe(source)
expect(result.code):toMatch()
end
)
test('preprocess pug', function()
local template = parse({filename='example.vue', sourceMap=true}).descriptor.template
local result = compileTemplate({filename='example.vue', source=template.content, preprocessLang=template.lang})
expect(#result.errors):toBe(0)
end
)
test('warn missing preprocessor', function()
local template = parse({filename='example.vue', sourceMap=true}).descriptor.template
local result = compileTemplate({filename='example.vue', source=template.content, preprocessLang=template.lang})
expect(#result.errors):toBe(1)
end
)
test('transform asset url options', function()
local input = {source=, filename='example.vue'}
local = compileTemplate({..., transformAssetUrls={tags={foo={'bar'}}}})
expect(code1):toMatch()
local = compileTemplate({..., transformAssetUrls={foo={'bar'}}})
expect(code2):toMatch()
local = compileTemplate({..., transformAssetUrls=false})
expect(code3).tsvar_not:toMatch()
end
)
test('source map', function()
local template = parse({filename='example.vue', sourceMap=true}).descriptor.template
local result = compileTemplate({filename='example.vue', source=template.content})
expect(result.map):toMatchSnapshot()
end
)
test('template errors', function()
local result = compileTemplate({filename='example.vue', source=})
expect(result.errors):toMatchSnapshot()
end
)
test('preprocessor errors', function()
local template = parse({filename='example.vue', sourceMap=true}).descriptor.template
local result = compileTemplate({filename='example.vue', source=template.content, preprocessLang=template.lang})
expect(#result.errors):toBe(1)
local message = result.errors[0+1]:toString()
expect(message):toMatch()
expect(message):toMatch()
end
)
|
Skada:AddLoadableModule("Power", nil, function(Skada, L)
if Skada.db.profile.modulesBlocked.Power then return end
local mod = Skada:NewModule("power gains")
local MANA = 0
local ENERGY = 3
local FOCUS = 2
local RAGE = 1
local RUNIC = 6
local HOLY = 9
local function log_gain(set, gain)
-- Get the player from set.
local player = Skada:get_player(set, gain.playerid, gain.playername)
if player then
-- Make sure power type exists.
if not player.power[gain.type] then
player.power[gain.type] = {spells = {}, amount = 0}
end
-- Make sure set power type exists.
if not set.power[gain.type] then
set.power[gain.type] = 0
end
-- Add to player total.
player.power[gain.type].amount = player.power[gain.type].amount + gain.amount
-- Also add to set total gain.
set.power[gain.type] = set.power[gain.type] + gain.amount
-- Create spell if it does not exist.
if not player.power[gain.type].spells[gain.spellid] then
player.power[gain.type].spells[gain.spellid] = 0
end
player.power[gain.type].spells[gain.spellid] = player.power[gain.type].spells[gain.spellid] + gain.amount
end
end
local gain = {}
local function SpellEnergize(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
-- Healing
local spellId, spellName, spellSchool, samount, overEnergize, powerType = ...
gain.playerid = srcGUID
gain.playername = srcName
gain.spellid = spellId
gain.spellname = spellName
gain.amount = samount
gain.overenergize = overEnergize
gain.type = tonumber(powerType)
Skada:FixPets(gain)
log_gain(Skada.current, gain)
log_gain(Skada.total, gain)
end
-- Prototypes for the modes
local basemod = {}
local basemod_mt = { __index = basemod }
local playermod = {}
local playermod_mt = { __index = playermod }
function basemod:Create(power, modename, playermodename, modeicon)
local pmode = {
metadata = {},
name = playermodename
}
setmetatable(pmode, playermod_mt)
local instance = {
playermod = pmode,
metadata = {
showspots = true,
click1 = pmode,
icon = modeicon
},
name = modename
}
instance.power = power
pmode.power = power
setmetatable(instance, basemod_mt)
return instance
end
function basemod:GetName()
return self.name
end
function basemod:Update(win, set)
local nr = 1
local max = 0
for i, player in ipairs(set.players) do
if player.power[self.power] then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = player.id
d.label = player.name
d.value = player.power[self.power].amount
if self.power == MANA then
d.valuetext = Skada:FormatNumber(player.power[self.power].amount)
else
d.valuetext = player.power[self.power].amount
end
d.class = player.class
d.role = player.role
if player.power[self.power].amount > max then
max = player.power[self.power].amount
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
function basemod:AddToTooltip(set, tooltip)
end
function basemod:GetSetSummary(set)
return Skada:FormatNumber(set.power[self.power] or 0)
end
function playermod:GetName()
return self.name
end
function playermod:Enter(win, id, label)
self.playerid = id
self.title = label
end
-- Detail view of a player.
function playermod:Update(win, set)
-- View spells for this player.
-- View spells for this player.
local player = Skada:find_player(set, self.playerid)
local nr = 1
local max = 0
if player then
for spellid, amount in pairs(player.power[self.power].spells) do
local name, rank, icon, cost, isFunnel, powerType, castTime, minRange, maxRange = GetSpellInfo(spellid)
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = spellid
d.label = name
d.value = amount
if self.power == MANA then
d.valuetext = Skada:FormatNumber(amount)..(" (%02.1f%%)"):format(amount / player.power[self.power].amount * 100)
else
d.valuetext = amount..(" (%02.1f%%)"):format(amount / player.power[self.power].amount * 100)
end
d.icon = icon
d.spellid = spellid
if amount > max then
max = amount
end
nr = nr + 1
end
end
win.metadata.hasicon = true
win.metadata.maxvalue = max
end
local manamod = basemod:Create(MANA, L["Mana gained"], L["Mana gain spell list"], "Interface\\Icons\\Inv_misc_ancient_mana")
local energymod = basemod:Create(ENERGY, L["Energy gained"], L["Energy gain sources"], "Interface\\Icons\\Ability_rogue_sprint")
local runicmod = basemod:Create(RUNIC, L["Runic power gained"], L["Runic power gain sources"], "Interface\\Icons\\Ability_deathknight_runicimpowerment")
local ragemod = basemod:Create(RAGE, L["Rage gained"], L["Rage gain sources"], "Interface\\Icons\\Ability_warrior_rampage")
local holymod = basemod:Create(HOLY, L["Holy power gained"], L["Holy power gain sources"], "Interface\\Icons\\Ability_paladin_beaconoflight")
local focusmod = basemod:Create(FOCUS, L["Focus gained"], L["Focus gain sources"], "Interface\\Icons\\Ability_hunter_focusedaim")
function mod:OnEnable()
Skada:RegisterForCL(SpellEnergize, 'SPELL_ENERGIZE', {src_is_interesting = true})
Skada:RegisterForCL(SpellEnergize, 'SPELL_PERIODIC_ENERGIZE', {src_is_interesting = true})
Skada:AddMode(manamod, L["Power gains"])
Skada:AddMode(energymod, L["Power gains"])
Skada:AddMode(ragemod, L["Power gains"])
Skada:AddMode(runicmod, L["Power gains"])
Skada:AddMode(holymod, L["Power gains"])
Skada:AddMode(focusmod, L["Power gains"])
end
function mod:OnDisable()
Skada:RemoveMode(manamod)
Skada:RemoveMode(energymod)
Skada:RemoveMode(ragemod)
Skada:RemoveMode(runicmod)
Skada:RemoveMode(holymod)
end
-- Called by Skada when a new player is added to a set.
function manamod:AddPlayerAttributes(player)
if not player.power then
player.power = {}
end
end
-- Called by Skada when a new set is created.
function manamod:AddSetAttributes(set)
if not set.power then
set.power = {}
end
end
end)
|
local M = {}
function M.config()
rvim.builtin.nvimtree = {
active = true,
on_config_done = nil,
setup = {
disable_netrw = true,
hijack_netrw = true,
open_on_setup = false,
auto_close = true,
open_on_tab = false,
update_focused_file = {
enable = true,
},
diagnostics = {
enable = true,
icons = {
hint = "",
info = "",
warning = "",
error = "",
},
},
view = {
width = 30,
side = "left",
auto_resize = false,
mappings = {
custom_only = false,
},
},
},
show_icons = {
git = true,
folders = true,
files = true,
folder_arrows = true,
tree_width = 30,
},
ignore = { ".git", "node_modules", ".cache" },
quit_on_open = false,
hide_dotfiles = true,
git_hl = true,
root_folder_modifier = ":~",
allow_resize = true,
ignore_ft_on_setup = {"dashboard"},
auto_ignore_ft = { "dashboard" },
icons = {
default = "",
symlink = "",
git = {
unstaged = "",
staged = "S",
unmerged = "",
renamed = "➜",
deleted = "",
untracked = "U",
ignored = "◌",
},
folder = {
default = "",
open = "",
empty = "",
empty_open = "",
symlink = "",
},
},
}
end
function M.setup()
local tree_cb = require'nvim-tree.config'.nvim_tree_callback
rvim.builtin.nvimtree.setup.view.mappings.list = {
{ key = { "l", "<CR>", "o" }, cb = tree_cb "edit" },
{ key = "h", cb = tree_cb "close_node" },
{ key = "s", cb = tree_cb "vsplit" },
{ key = "t", cb = tree_cb("tabnew")},
}
rvim.builtin.which_key.mappings["<C-n>"] = { "<cmd>NvimTreeToggle<CR>", "Explorer" }
require("nvim-tree").setup(rvim.builtin.nvimtree.setup)
end
function M.on_open()
if package.loaded["bufferline.state"] and rvim.builtin.nvimtree.setup.view.side == "left" then
require("bufferline.state").set_offset(rvim.builtin.nvimtree.setup.view.width + 1, "")
end
end
function M.on_close()
local buf = tonumber(vim.fn.expand "<abuf>")
local ft = vim.api.nvim_buf_get_option(buf, "filetype")
if ft == "NvimTree" and package.loaded["bufferline.state"] then
require("bufferline.state").set_offset(0)
end
end
function M.change_tree_dir(dir)
local lib_status_ok, lib = pcall(require, "nvim-tree.lib")
if lib_status_ok then
lib.change_dir(dir)
end
end
return M
|
--AI parameter constants
AI_THINK_INTERVAL = 1 -- The interval in seconds between two think ticks
--AI state constants
AI_STATE_IDLE = 0
AI_STATE_AGGRESSIVE = 1
AI_STATE_RETURNING = 2
AI_STATE_WALKING = 3
--Define the HumanKingAI class
HumanKingAI = {}
HumanKingAI.__index = HumanKingAI
--[[ Create an instance of the HumanKingAI class for some unit
with some parameters. ]]
function HumanKingAI:MakeInstance( unit, params )
--Construct an instance of the HumanKingAI class
setmetatable( self, HumanKingAI )
--Set the core fields for this AI
self.unit = unit --The unit this AI is controlling
self.state = AI_STATE_IDLE --The initial state
self.stateThinks = { --Add thinking functions for each state
[AI_STATE_IDLE] = Dynamic_Wrap(HumanKingAI, 'IdleThink'),
[AI_STATE_AGGRESSIVE] = Dynamic_Wrap(HumanKingAI, 'AggressiveThink'),
[AI_STATE_RETURNING] = Dynamic_Wrap(HumanKingAI, 'ReturningThink')
}
--Set parameters values as fields for later use
self.spawnPos = params.spawnPos
self.aggroRange = params.aggroRange
self.leashRange = params.leashRange
--Start thinking
Timers:CreateTimer(function()
return self:GlobalThink()
end)
--Return the constructed instance
return self
end
--[[ The high-level thinker this AI will do every tick, selects the correct
state-specific think function and executes it. ]]
function HumanKingAI:GlobalThink()
--If the unit is dead, stop thinking
if not self.unit:IsAlive() then
return nil
end
--Execute the think function that belongs to the current state
self.stateThinks[ self.state ]( self )
--Reschedule this thinker to be called again after a short duration
return AI_THINK_INTERVAL
end
--[[ Think function for the 'Idle' state. ]]
function HumanKingAI:IdleThink()
--Find any enemy units around the AI unit inside the aggroRange
local units = FindUnitsInRadius( self.unit:GetTeam(), self.unit:GetAbsOrigin(), nil,
self.aggroRange, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_ALL, DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER, false )
--If one or more units were found, start attacking the first one
if #units > 0 then
self.unit:MoveToTargetToAttack( units[1] ) --Start attacking
self.aggroTarget = units[1]
self.state = AI_STATE_AGGRESSIVE --State transition
return true
end
--State behavior
--Whistle a tune
end
--[[ Think function for the 'Aggressive' state. ]]
function HumanKingAI:AggressiveThink()
--Check if the unit has walked outside its leash range
if ( self.spawnPos - self.unit:GetAbsOrigin() ):Length() > self.leashRange then
self.unit:MoveToPosition( self.spawnPos ) --Move back to the spawnpoint
self.state = AI_STATE_RETURNING --Transition the state to the 'Returning' state(!)
return true --Return to make sure no other code is executed in this state
end
--Check if the unit's target is still alive (self.aggroTarget will have to be set when transitioning into this state)
if not self.aggroTarget:IsAlive() then
self.unit:MoveToPosition( self.spawnPos ) --Move back to the spawnpoint
self.state = AI_STATE_RETURNING --Transition the state to the 'Returning' state(!)
return true --Return to make sure no other code is executed in this state
end
--State behavior
--Here we can just do any behaviour you want to repeat in this state
end
--[[ Think function for the 'Returning' state. ]]
function HumanKingAI:ReturningThink()
--Check if the AI unit has reached its spawn location yet
if (self.spawnPos - self.unit:GetAbsOrigin()):Length() < 10 then
--Go into the idle state
self.state = AI_STATE_IDLE
return true
end
local orderMoveToSpawnPosition = {
UnitIndex = self.unit:GetEntityIndex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_MOVE,
Position = self.spawnPos,
Queue = true
}
ExecuteOrderFromTable(orderMoveToSpawnPosition)
end
|
local resource_autoplace = require('resource-autoplace');
local noise = require('noise');
local util = require("__bzcarbon__.data-util");
if util.me.use_rough_diamond() then
data:extend({
{
type = "autoplace-control",
category = "resource",
name = "diamond",
richness = true,
order = "b-e"
},
{
type = "noise-layer",
name = "diamond"
},
{
type = "resource",
icon_size = 64, icon_mipmaps = 3,
name = "diamond",
icon = "__bzcarbon__/graphics/icons/rough-diamond.png",
flags = {"placeable-neutral"},
order="a-b-a",
map_color = {r=0.30, g=0.54, b=0.92},
minable =
{
mining_particle = "diamond-particle",
mining_time = 15,
result = "rough-diamond"
},
collision_box = {{ -0.1, -0.1}, {0.1, 0.1}},
selection_box = {{ -0.5, -0.5}, {0.5, 0.5}},
autoplace = resource_autoplace.resource_autoplace_settings{
name = "diamond",
order = "b-z",
base_density = 0.5,
base_spots_per_km2 = 0.5,
has_starting_area_placement = false,
regular_rq_factor_multiplier = 0.6,
},
stage_counts = {15000, 9500, 5500, 2900, 1300, 400, 150, 80},
stages =
{
sheet =
{
filename = "__bzcarbon__/graphics/entity/ores/diamond.png",
priority = "extra-high",
size = 64,
frame_count = 8,
variation_count = 8,
hr_version =
{
filename = "__bzcarbon__/graphics/entity/ores/hr-diamond.png",
priority = "extra-high",
size = 128,
frame_count = 8,
variation_count = 8,
scale = 0.5
}
}
},
},
{
type = "item",
name = "rough-diamond",
icon_size = 64, icon_mipmaps = 3,
icon = "__bzcarbon__/graphics/icons/rough-diamond.png",
pictures = {
{filename="__bzcarbon__/graphics/icons/rough-diamond.png", size=64, scale=0.25},
{filename="__bzcarbon__/graphics/icons/rough-diamond-1.png", size=64, scale=0.25},
{filename="__bzcarbon__/graphics/icons/rough-diamond-2.png", size=64, scale=0.25},
{filename="__bzcarbon__/graphics/icons/rough-diamond-3.png", size=64, scale=0.25},
},
subgroup = "raw-resource",
order = "t-c-a",
stack_size = util.get_stack_size(50)
},
})
end
|
local MusicEditing = require "MusicEditing"
local MusicAnalysis = require "MusicAnalysis"
local Song = MusicEditing.Song
local Track = MusicEditing.Track
local Event = MusicEditing.Event
local NoteOnOffEvent = MusicEditing.NoteOnOffEvent
local ArrangementContext = MusicEditing.ArrangementContext
local Helper = MusicEditing.Helper
local helporversion = false
local songExport = nil
local melodySong = nil
local arguments = {input = nil, style = nil, output = nil, settings = nil}
local style = nil
local settings = nil
function readFlags(flag, argnum) -- called by readArguments(), help to process the flags & cmds one by one
if (flag == "-i" or flag == "--input")
then
flag = "input"
if (arguments[flag] == nil)
then
arguments[flag] = arg[argnum+1]
if (not pcall(Song.buildFromFile, arguments[flag]))
then
print("Error: " .. arguments[flag] .. " not found or the file is invalid!")
return false
end
melodySong = Song.buildFromFile(arguments[flag])
argnumber = argnumber + 1
else
print("Repeated input flag!")
return false
end
elseif (flag == "-s" or flag == "--style")
then
flag = "style"
if (arguments[flag] == nil)
then
arguments[flag] = arg[argnum+1]
if (not pcall(dofile, arguments[flag]))
then
print("Error! " .. arguments[flag] .. " not found or the file is invalid!")
return false
end
style = dofile(arguments[flag])
argnumber = argnumber + 1
else
print("Repeated style flag!")
return false
end
elseif (flag == "-o" or flag == "--output")
then
flag = "output"
if (arguments[flag] == nil)
then
arguments[flag] = arg[argnum+1]
songExport = arguments[flag]
argnumber = argnumber + 1
--print("o")
else
print("Repeated output flag!")
return false
end
elseif (flag == "-c" or flag == "--settings")
then
flag = "settings"
if (arguments[flag] == nil)
then
arguments[flag] = arg[argnum+1]
if (not pcall(dofile, arguments[flag]))
then
print("Error: " .. arguments[flag] .. " not found or the file is invalid!")
return false
end
settings = dofile(arguments[flag])
if (settings.sectionSeparation == nil)
then
print("sectionSeparation is missing! It is compulsory!")
return false
end
argnumber = argnumber + 1
--print("c")
else
print("Repeated settings flag!")
return false
end
elseif (flag == "-h" or flag == "-v" or flag == "--version" or flag == "--help")
then
helporversion = true
if (argnum ~= 1 or arg[2] ~= nil)
then
print("Please use " .. flag .. " flag in single argument!")
return false
elseif (flag == "-h" or flag == "--help")
then
print("-h, --help (Please use it in a single argument)\n",
"-v, --version (Please use it in a single argument)\n",
"-i, --input MELODY_FILE_PATH\n",
"-s, --style STYLE_FILE_PATH\n",
"-o, --output OUTPUT_FILE_PATH\n",
"-c, --settings SETTINGS_FILE_PATH\n",
"Example: Lua main.lua -i melody.mid -o arrangement.mid -s style.lua -c settings.lua")
return false
else
print("Version 1.0")
return false
end
else
print("This flag is not available!")
return false
end
return true
end
function readArguments() -- 2nd function it will read the FULL arguments in the cmd, and split the flag to let readFlags() do it
if (arg[9] ~= nil)
then
print("Too much arguments!")
return false
elseif (arg[1] == nil)
then
print("Please input proper argument for input and output! Use command \"-h\" or \"--help\" for more details")
return false
else
argnumber = 1
while (argnumber <= 8 and arg[argnumber] ~= nil)
do
local canContinue = readFlags(arg[argnumber], argnumber)
argnumber = argnumber + 1
if (not canContinue)
then
return false
end
end
end
if (not (arguments["input"] ~= nil and arguments["style"] ~= nil and arguments["output"] ~= nil and arguments["settings"] ~= nil))
then
if (helporversion == false)
then
if (arguments["input"] == nil)
then
print("Input is missing!")
end
if (arguments["output"] == nil)
then
print("Output is missing!")
end
if (arguments["style"] == nil)
then
print("Style file is missing!")
end
if (arguments["settings"] == nil)
then
print("Settings file is missing!")
end
return false
end
end
return true
end
function mainRun() --main part for the running of program, after checking it is error-free
-- local melodySong = Song.buildFromFile("country-road-melody-short.mid")
-- local melodySong = Song.buildFromFile("Debug/tempo-test.mid")
-- local melodySong = Song.buildFromFile("c_major_scale.mid")
-- local melodySong = Song.buildFromFile("offset-2.mid")
local melodyTrack = melodySong:getTracks()[#melodySong:getTracks()]
local analyser = MusicAnalysis.MusicAnalyser.new(melodyTrack)
local key = analyser:estimateKey()
local chordProgression = analyser:estimateChordProgression()
-- local n2p = Helper.pitchNumberToName
-- for i = 1, #chordProgression do
-- for j = 1, #chordProgression[i] do
-- io.write(n2p(chordProgression[i][j]) .. "\t")
-- end
-- io.write("\n")
-- end
local song = Song.new(
melodySong:getTimeDivision(),
settings.timeSignature or melodySong:getTimeSignature(),
settings.tempo or melodySong:getTempo()
)
local p2n = Helper.pitchNameToNumber
local chordG = { p2n("G"), p2n("B"), p2n("D") }
local chordEm = { p2n("E"), p2n("G"), p2n("B") }
local chordD = { p2n("D"), p2n("F#"), p2n("A") }
local chordC = { p2n("C"), p2n("E"), p2n("G") }
local chordF = { p2n("F"), p2n("A"), p2n("C") }
local chordC7 = { p2n("C"), p2n("E"), p2n("G"), p2n("A#") }
local arrangementContext = ArrangementContext.new(
song,
melodyTrack,
settings.key or key,
settings.chordProgression or chordProgression,
settings.sectionSeparation,
Song.buildFromFile(style.resourceFilename)
)
style.arrange(arrangementContext)
song:export(arguments["output"])
print("Successfully saved as " .. arguments["output"] .. ".")
end
-- Program Execution
if (readArguments() == true)
then
mainRun()
end
|
local Robot = {}
function build_name()
return string.char(math.random(65,90))..string.char(math.random(65,90))..math.random(100,999)
end
function name_exists(names,name)
if (names.length ~=nil) then
for i = 1, #names do
if names[i] == name then
return true
end
end
end
return false
end
function Robot:new()
self.__index = self
local names = {}
local name = build_name()
if (name_exists(names, name)) then
name = build_name()
end
names[#names] = name
return setmetatable({ name = name, names = names }, self)
end
function Robot:reset()
local name = build_name()
local names = self.names
if (name_exists(names, name)) then
name = build_name()
end
names[#names] = name
self.names = names
self.name = name
end
return Robot
|
local LuaQtHelper = require("LuaQtHelper")
require("QtWidgets")
-- local ui_LoginWindow = require("ui_LoginWindow")
local ui_LoginWindow = loadstring(require("uic").run("loginwindow.ui"))()
local LoginWindow = {
className = "LoginWindow",
superClass = QWidget,
}
local function newLoginWindow(mo, parent)
local self = QWidget.newExtended(mo, parent)
self.ui = ui_LoginWindow.setupUi(self)
self:connect(self.ui.btn_Login, "2clicked(bool)", "1doLogin(bool)")
self:connect(self.ui.edit_ID, "2cursorPositionChanged(int,int)", "1testPosition(int,int)")
return self
end
LuaQtHelper.addConstructor(LoginWindow, {"QWidget*"}, newLoginWindow)
LuaQtHelper.addSignal(LoginWindow, "void", "logined", {})
LuaQtHelper.addSlot(LoginWindow, "void", "doLogin", {"bool"}, function(self, ...)
print(...)
self:logined()
end)
LuaQtHelper.addSlot(LoginWindow, "void", "testPosition", {"int", "int"}, function(self, ...)
print(...)
self:logined()
end)
LoginWindow = LuaQtHelper.defineQtClass(LoginWindow)
return LoginWindow
|
local Util = { }
local fs = _G.fs
local http = _G.http
local os = _G.os
local term = _G.term
local textutils = _G.textutils
function Util.tryTimed(timeout, f, ...)
local c = os.clock()
repeat
local ret = f(...)
if ret then
return ret
end
until os.clock()-c >= timeout
end
function Util.tryTimes(attempts, f, ...)
local result
for _ = 1, attempts do
result = { f(...) }
if result[1] then
return unpack(result)
end
end
return unpack(result)
end
function Util.throttle(fn)
local ts = os.clock()
local timeout = .095
return function(...)
local nts = os.clock()
if nts > ts + timeout then
os.sleep(0)
ts = os.clock()
if fn then
fn(...)
end
end
end
end
function Util.tostring(pattern, ...)
local function serialize(tbl, width)
local str = '{\n'
for k, v in pairs(tbl) do
local value
if type(v) == 'table' then
value = string.format('table: %d', Util.size(v))
else
value = tostring(v)
end
str = str .. string.format(' %s: %s\n', k, value)
end
--if #str < width then
--str = str:gsub('\n', '') .. ' }'
--else
str = str .. '}'
--end
return str
end
if type(pattern) == 'string' then
return string.format(pattern, ...)
elseif type(pattern) == 'table' then
return serialize(pattern, term.current().getSize())
end
return tostring(pattern)
end
function Util.print(pattern, ...)
print(Util.tostring(pattern, ...))
end
function Util.getVersion()
local version
if _G._CC_VERSION then
version = tonumber(_G._CC_VERSION:match('[%d]+%.?[%d][%d]'))
end
if not version and _G._HOST then
version = tonumber(_G._HOST:match('[%d]+%.?[%d][%d]'))
end
return version or 1.7
end
function Util.getMinecraftVersion()
local mcVersion = _G._MC_VERSION or 'unknown'
if _G._HOST then
local version = _G._HOST:match('%S+ %S+ %((%S.+)%)')
if version then
mcVersion = version:match('Minecraft (%S+)') or version
end
end
return mcVersion
end
function Util.checkMinecraftVersion(minVersion)
local version = Util.getMinecraftVersion()
local function convert(v)
local m1, m2, m3 = v:match('(%d)%.(%d)%.?(%d?)')
return tonumber(m1) * 10000 + tonumber(m2) * 100 + (tonumber(m3) or 0)
end
return convert(version) >= convert(tostring(minVersion))
end
function Util.signum(num)
if num > 0 then
return 1
elseif num < 0 then
return -1
else
return 0
end
end
function Util.clamp(lo, num, hi)
if num <= lo then
return lo
elseif num >= hi then
return hi
else
return num
end
end
-- http://lua-users.org/wiki/SimpleRound
function Util.round(num, idp)
local mult = 10^(idp or 0)
return Util.signum(num) * math.floor(math.abs(num) * mult + 0.5) / mult
end
function Util.randomFloat(max, min)
min = min or 0
max = max or 1
return (max-min) * math.random() + min
end
--[[ Table functions ]] --
function Util.clear(t)
local keys = Util.keys(t)
for _,k in pairs(keys) do
t[k] = nil
end
end
function Util.empty(t)
return not next(t)
end
function Util.key(t, value)
for k,v in pairs(t) do
if v == value then
return k
end
end
end
function Util.keys(t)
local keys = { }
for k in pairs(t) do
keys[#keys+1] = k
end
return keys
end
function Util.merge(obj, args)
if args then
for k,v in pairs(args) do
obj[k] = v
end
end
return obj
end
function Util.deepMerge(obj, args)
if args then
for k,v in pairs(args) do
if type(v) == 'table' then
if not obj[k] then
obj[k] = { }
end
Util.deepMerge(obj[k], v)
else
obj[k] = v
end
end
end
end
-- remove table entries if passed function returns false
function Util.prune(t, fn)
for _,k in pairs(Util.keys(t)) do
local v = t[k]
if type(v) == 'table' then
t[k] = Util.prune(v, fn)
end
if not fn(t[k]) then
t[k] = nil
end
end
return t
end
function Util.transpose(t)
local tt = { }
for k,v in pairs(t) do
tt[v] = k
end
return tt
end
function Util.contains(t, value)
for k,v in pairs(t) do
if v == value then
return k
end
end
end
function Util.find(t, name, value)
for k,v in pairs(t) do
if v[name] == value then
return v, k
end
end
end
function Util.findAll(t, name, value)
local rt = { }
for _,v in pairs(t) do
if v[name] == value then
table.insert(rt, v)
end
end
return rt
end
function Util.shallowCopy(t)
if not t then error('Util.shallowCopy: invalid table', 2) end
local t2 = { }
for k,v in pairs(t) do
t2[k] = v
end
return t2
end
function Util.deepCopy(t)
if type(t) ~= 'table' then
return t
end
--local mt = getmetatable(t)
local res = {}
for k,v in pairs(t) do
if type(v) == 'table' then
v = Util.deepCopy(v)
end
res[k] = v
end
--setmetatable(res,mt)
return res
end
-- http://snippets.luacode.org/?p=snippets/Filter_a_table_in-place_119
function Util.filterInplace(t, predicate)
local j = 1
for i = 1,#t do
local v = t[i]
if predicate(v) then
t[j] = v
j = j + 1
end
end
while t[j] ~= nil do
t[j] = nil
j = j + 1
end
return t
end
function Util.filter(it, f)
local ot = { }
for k,v in pairs(it) do
if f(v) then
ot[k] = v
end
end
return ot
end
function Util.reduce(t, fn, acc)
for _, v in pairs(t) do
fn(acc, v)
end
return acc
end
function Util.size(list)
if type(list) == 'table' then
local length = 0
for _ in pairs(list) do
length = length + 1
end
return length
end
return 0
end
local function isArray(value)
-- dubious
return type(value) == "table" and (value[1] or next(value) == nil)
end
function Util.removeByValue(t, e)
for k,v in pairs(t) do
if v == e then
if isArray(t) then
table.remove(t, k)
else
t[k] = nil
end
break
end
end
end
function Util.any(t, fn)
for _,v in pairs(t) do
if fn(v) then
return true
end
end
end
function Util.every(t, fn)
for _,v in pairs(t) do
if not fn(v) then
return false
end
end
return true
end
function Util.each(list, func)
for index, value in pairs(list) do
func(value, index, list)
end
end
function Util.rpairs(t)
local tkeys = Util.keys(t)
local i = #tkeys
return function()
local key = tkeys[i]
local k,v = key, t[key]
i = i - 1
if v then
return k, v
end
end
end
-- http://stackoverflow.com/questions/15706270/sort-a-table-in-lua
function Util.spairs(t, order)
local keys = Util.keys(t)
-- if order function given, sort by it by passing the table and keys a, b,
-- otherwise just sort the keys
if order then
table.sort(keys, function(a,b) return order(t[a], t[b]) end)
else
table.sort(keys)
end
-- return the iterator function
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], t[keys[i]]
end
end
end
function Util.first(t, order)
local keys = Util.keys(t)
if order then
table.sort(keys, function(a,b) return order(t[a], t[b]) end)
else
table.sort(keys)
end
return keys[1], t[keys[1]]
end
--[[ File functions ]]--
function Util.readFile(fname)
local f = fs.open(fname, "r")
if f then
local t = f.readAll()
f.close()
return t
end
end
function Util.writeFile(fname, data)
if not fname or not data then error('Util.writeFile: invalid parameters', 2) end
local file = io.open(fname, "w")
if not file then
error('Unable to open ' .. fname, 2)
end
file:write(data)
file:close()
end
function Util.readLines(fname)
local file = fs.open(fname, "r")
if file then
local t = {}
local line = file.readLine()
while line do
table.insert(t, line)
line = file.readLine()
end
file.close()
return t
end
end
function Util.writeLines(fname, lines)
local file = fs.open(fname, 'w')
if file then
for _,line in ipairs(lines) do
file.writeLine(line)
end
file.close()
return true
end
end
function Util.readTable(fname)
local t = Util.readFile(fname)
if t then
return textutils.unserialize(t)
end
end
function Util.writeTable(fname, data)
Util.writeFile(fname, textutils.serialize(data))
end
function Util.loadTable(fname)
local fc = Util.readFile(fname)
if not fc then
return false, 'Unable to read file'
end
local s, m = loadstring('return ' .. fc, fname)
if s then
s, m = pcall(s)
if s then
return m
end
end
return s, m
end
--[[ loading and running functions ]] --
function Util.httpGet(url, headers)
local h, msg = http.get(url, headers)
if h then
local contents = h.readAll()
h.close()
return contents
end
return h, msg
end
function Util.download(url, filename)
local contents, msg = Util.httpGet(url)
if not contents then
error(string.format('Failed to download %s\n%s', url, msg), 2)
end
if filename then
Util.writeFile(filename, contents)
end
return contents
end
function Util.loadUrl(url, env) -- loadfile equivalent
local c, msg = Util.httpGet(url)
if not c then
return c, msg
end
return load(c, url, nil, env)
end
function Util.runUrl(env, url, ...) -- os.run equivalent
setmetatable(env, { __index = _G })
local fn, m = Util.loadUrl(url, env)
if fn then
return pcall(fn, ...)
end
return fn, m
end
function Util.run(env, path, ...)
if type(env) ~= 'table' then error('Util.run: env must be a table', 2) end
setmetatable(env, { __index = _G })
local fn, m = loadfile(path, env)
if fn then
return pcall(fn, ...)
end
return fn, m
end
function Util.runFunction(env, fn, ...)
setfenv(fn, env)
setmetatable(env, { __index = _G })
return pcall(fn, ...)
end
--[[ String functions ]] --
function Util.toBytes(n)
if not tonumber(n) then error('Util.toBytes: n must be a number', 2) end
if n >= 1000000 or n <= -1000000 then
return string.format('%sM', math.floor(n/1000000 * 10) / 10)
elseif n >= 10000 or n <= -10000 then
return string.format('%sK', math.floor(n/1000))
elseif n >= 1000 or n <= -1000 then
return string.format('%sK', math.floor(n/1000 * 10) / 10)
end
return tostring(n)
end
function Util.insertString(str, istr, pos)
return str:sub(1, pos - 1) .. istr .. str:sub(pos)
end
function Util.split(str, pattern)
if not str then error('Util.split: Invalid parameters', 2) end
pattern = pattern or "(.-)\n"
local t = {}
local function helper(line) table.insert(t, line) return "" end
helper((str:gsub(pattern, helper)))
return t
end
function Util.matches(str, pattern)
pattern = pattern or '%S+'
local t = { }
for s in str:gmatch(pattern) do
table.insert(t, s)
end
return t
end
function Util.startsWith(s, match)
return string.sub(s, 1, #match) == match
end
function Util.widthify(s, len)
s = s or ''
local slen = #s
if slen < len then
s = s .. string.rep(' ', len - #s)
elseif slen > len then
s = s:sub(1, len)
end
return s
end
-- http://snippets.luacode.org/?p=snippets/trim_whitespace_from_string_76
function Util.trim(s)
return s:find'^%s*$' and '' or s:match'^%s*(.*%S)'
end
-- trim whitespace from left end of string
function Util.triml(s)
return s:match'^%s*(.*)'
end
-- trim whitespace from right end of string
function Util.trimr(s)
return s:find'^%s*$' and '' or s:match'^(.*%S)'
end
-- end http://snippets.luacode.org/?p=snippets/trim_whitespace_from_string_76
-- word wrapping based on:
-- https://www.rosettacode.org/wiki/Word_wrap#Lua and
-- http://lua-users.org/wiki/StringRecipes
local function paragraphwrap(text, linewidth, res)
linewidth = linewidth or 75
local spaceleft = linewidth
local line = { }
for word in text:gmatch("%S+") do
local len = #word + 1
--if colorMode then
-- word:gsub('()@([@%d])', function(pos, c) len = len - 2 end)
--end
if len > spaceleft then
table.insert(res, table.concat(line, ' '))
line = { word }
spaceleft = linewidth - len - 1
else
table.insert(line, word)
spaceleft = spaceleft - len
end
end
table.insert(res, table.concat(line, ' '))
return table.concat(res, '\n')
end
-- end word wrapping
function Util.wordWrap(str, limit)
local longLines = Util.split(str)
local lines = { }
for _,line in ipairs(longLines) do
paragraphwrap(line, limit, lines)
end
return lines
end
function Util.args(arg)
local options, args = { }, { }
local k = 1
while k <= #arg do
local v = arg[k]
if string.sub(v, 1, 1) == '-' then
local opt = string.sub(v, 2)
options[opt] = arg[k + 1]
k = k + 1
else
table.insert(args, v)
end
k = k + 1
end
return options, args
end
-- http://lua-users.org/wiki/AlternativeGetOpt
local function getopt( arg, options )
local tab = {}
for k, v in ipairs(arg) do
if type(v) == 'string' then
if string.sub( v, 1, 2) == "--" then
local x = string.find( v, "=", 1, true )
if x then tab[ string.sub( v, 3, x-1 ) ] = string.sub( v, x+1 )
else tab[ string.sub( v, 3 ) ] = true
end
elseif string.sub( v, 1, 1 ) == "-" then
local y = 2
local l = string.len(v)
local jopt
while ( y <= l ) do
jopt = string.sub( v, y, y )
if string.find( options, jopt, 1, true ) then
if y < l then
tab[ jopt ] = string.sub( v, y+1 )
y = l
else
tab[ jopt ] = arg[ k + 1 ]
end
else
tab[ jopt ] = true
end
y = y + 1
end
end
end
end
return tab
end
function Util.showOptions(options)
print('Arguments: ')
for _, v in pairs(options) do
print(string.format('-%s %s', v.arg, v.desc))
end
end
function Util.getOptions(options, args, ignoreInvalid)
local argLetters = ''
for _,o in pairs(options) do
if o.type ~= 'flag' then
argLetters = argLetters .. o.arg
end
end
local rawOptions = getopt(args, argLetters)
for k,ro in pairs(rawOptions) do
local found = false
for _,o in pairs(options) do
if o.arg == k then
found = true
if o.type == 'number' then
o.value = tonumber(ro)
elseif o.type == 'help' then
Util.showOptions(options)
return false
else
o.value = ro
end
end
end
if not found and not ignoreInvalid then
print('Invalid argument')
Util.showOptions(options)
return false
end
end
return true, Util.size(rawOptions)
end
return Util
|
local Modules = script.Parent.Parent.Parent.Parent
local Roact = require(Modules.Roact)
local withTheme = require(Modules.StudioComponents).withTheme
local function BaseProperty(props)
return withTheme(function(theme)
return Roact.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderSizePixel = 1,
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
Size = UDim2.new(1, 0, 0, 25),
ZIndex = props.ZIndex,
}, {
UIPadding = Roact.createElement("UIPadding", {
PaddingLeft = UDim.new(0, 25),
}),
Key = Roact.createElement("TextLabel", {
BackgroundTransparency = 1,
Size = UDim2.new(0.5, 0, 1, 0),
Text = props.Text,
TextColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainText),
TextXAlignment = Enum.TextXAlignment.Left,
}),
ValueContainer = Roact.createElement("Frame", {
BackgroundColor3 = theme:GetColor(Enum.StudioStyleGuideColor.MainBackground),
BorderSizePixel = 1,
BorderColor3 = theme:GetColor(Enum.StudioStyleGuideColor.Border),
Size = UDim2.new(0.5, 0, 1, 0),
Position = UDim2.new(0.5, 0, 0, 0),
}, {
Value = Roact.oneChild(props[Roact.Children]),
}),
})
end)
end
return BaseProperty
|
--Config and constants
return {
GLASSES_TERMINAL_ADDRESS = "67b6edd8-fe6f-49d9-9b6f-93c91ff2015e",
PLAYER_NAME = "shBLOCK",
RESOLUTION = {
width = 640,
height = 360
},
EASING_FUNCTIONS = {
BACK = "back",
BOUNCE = "bounce",
CIRC = "circ",
CUBIC = "cubic",
ELASTIC = "elastic",
EXPO = "expo",
LINEAR = "linear",
QUAD = "quad",
QUART = "quart",
QUINT = "quint",
SINE = "sine"
},
EASING_TYPES = {
IN = "in",
OUT = "out",
INOUT = "inout"
},
EASING_MODES = {
DEFAULT = "default",
LOOP = "loop",
REPEAT = "repeat"
},
EASING_VARIABLES = {
TRANSLATION = {X = "x", Y = "y", Z = "z"},
AUTO_TRANSLATION = {X = "x", Y = "y", Z = "z"},
ROTATION = {DEGREE = "deg"},
SCALE = {X = "x", Y = "y", Z = "z"},
COLOR = {RED = "r", GREEN = "g", BLUE = "b", ALPHA = "a"}
},
ALIGNMENT = {
HORIZONTAL = {
LEFT = "left",
CENTER = "center",
RIGHT = "right"
},
VERTICAL = {
TOP = "top",
MIDDLE = "middle",
BOTTOM = "bottom"
}
}
}
|
-------------------------------------------------------------------------------
--- enhance vector, based hump's vector
-------------------------------------------------------------------------------
local HVector = require('klib/vendor/hump/vector')
local Vector = HVector.Vector
Vector.normalize_inplace = Vector.normalizeInplace
local function _from_pos(position)
if #position == 2 then
return { x = position[1] or 0, y = position[2] or 0 }
else
return { x = position.x or 0, y = position.y or 0 }
end
end
local function from_position(position)
local vector = _from_pos(position)
return setmetatable(vector, Vector)
end
local function from_position2(x, y)
return setmetatable({ x = x, y = y }, Vector)
end
local function from_distance(from, to)
local f = _from_pos(from)
local t = _from_pos(to)
local v = { x = t.x - f.x, y = t.y - f.y }
return setmetatable(v, Vector)
end
local function new(...)
local args = { ... }
if #args == 1 then
return from_position(args[1])
elseif #args == 2 then
if type(args[1]) == 'table' and type(args[2]) == 'table' then
return from_distance(args[1], args[2])
else
return from_position2(args[1], args[2])
end
end
end
function Vector:direction()
local x = self.x
local y = self.y
local absx = math.abs(x)
local absy = math.abs(y)
if x == 0 and y == 0 then
return nil
end
if x > 0 then
if absx >= 2 * absy then
return defines.direction.east
elseif absx >= absy / 2 then
if y > 0 then
return defines.direction.southeast
else
return defines.direction.northeast
end
else
if y > 0 then
return defines.direction.south
else
return defines.direction.north
end
end
else
if absx >= 2 * absy then
return defines.direction.west
elseif absx >= absy / 2 then
if y > 0 then
return defines.direction.southwest
else
return defines.direction.northwest
end
else
if y > 0 then
return defines.direction.south
else
return defines.direction.north
end
end
end
end
function Vector:orthogonal()
-- x1x2 + y1y2 = 0
return new(-self.y, self.x)
end
function Vector:start_point(end_point)
return {x = end_point.x - self.x, y = end_point.y - self.y}
end
function Vector:end_point(start_point)
return {x = start_point.x + self.x, y = start_point.y + self.y}
end
return setmetatable({
from_polar = HVector.fromPolar,
from_position = from_position,
from_position2 = from_position2,
from_distance = from_distance,
random_direction = HVector.randomDirection,
isvector = HVector.isvector,
zero = HVector.zero,
}, {
__call = function(_, ...)
return new(...)
end
})
|
function stop_sounds(keys) keys.caster:StopSound("Hero_Pudge.Rot") end
function damage_target(keys)
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
local base_damage = ability:GetLevelSpecialValueFor("base_damage",
ability_level)
local damage_table = {
victim = target,
attacker = caster,
damage = base_damage,
damage_type = DAMAGE_TYPE_MAGICAL
}
ApplyDamage(damage_table)
local target_damage_percent = ability:GetLevelSpecialValueFor(
"target_damage_percent", ability_level) /
100
local target_percent_damage = caster:GetMaxHealth() * target_damage_percent
damage_table = {
victim = target,
attacker = caster,
damage = target_percent_damage,
damage_type = DAMAGE_TYPE_MAGICAL
}
ApplyDamage(damage_table)
end
function damage_self(keys)
local caster = keys.caster
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
local self_damage_percent = ability:GetLevelSpecialValueFor(
"self_damage_percent", ability_level) / 100
local self_percent_damage = caster:GetHealth() * self_damage_percent
local damage_table = {
victim = caster,
attacker = caster,
damage = self_percent_damage,
damage_type = DAMAGE_TYPE_MAGICAL
}
ApplyDamage(damage_table)
end
|
return {
"icons/skill_mag1-1",
"icons/skill_mag1-2",
"icons/skill_mag12-1",
"icons/skill_mag12-2",
"icons/skill_mag15-1",
"icons/skill_mag15-2",
"icons/skill_mag18-1",
"icons/skill_mag21-2",
"icons/skill_mag24-1",
"icons/skill_mag24-2",
"icons/skill_mag27-2",
"icons/skill_mag3-1",
"icons/skill_mag3-2",
"icons/skill_mag30-2",
"icons/skill_mag36-1",
"icons/skill_mag42-2",
"icons/skill_mag45-2",
"icons/skill_mag48-2",
"icons/skill_mag54-1",
"icons/skill_mag6-1",
"icons/skill_mag6-2",
"icons/skill_mag60-2",
"icons/skill_mag69-1",
"icons/skill_mag72-1",
"icons/skill_mag9-2",
"icons/skill_mag_new15-1",
"icons/skill_mag_new15-2",
"icons/skill_mag_new15-3",
"icons/skill_mag_new15-4",
"icons/skill_mag_new15-5",
"icons/skill_mag_new20-1",
"icons/skill_mag_new20-2",
"icons/skill_mag_new20-3",
"icons/skill_mag_new20-4",
"icons/skill_mag_new20-5",
"icons/skill_mag_new35-1",
"icons/skill_mag_new35-2",
"icons/skill_mag_new35-3",
"icons/skill_mag_new35-4",
"icons/skill_mag_new35-5",
"icons/skill_mag_new40-1",
"icons/skill_mag_new40-2",
"icons/skill_mag_new40-3",
"icons/skill_mag_new40-4",
"icons/skill_mag_new40-5",
"icons/skill_mag_new45-1",
"icons/skill_mag_new45-10",
"icons/skill_mag_new45-2",
"icons/skill_mag_new45-3",
"icons/skill_mag_new45-4",
"icons/skill_mag_new45-5",
"icons/skill_mag_new45-6",
"icons/skill_mag_new45-7",
"icons/skill_mag_new45-8",
"icons/skill_mag_new45-9",
"icons/skill_mag_new50-1",
"icons/skill_mag_new50-10",
"icons/skill_mag_new50-11",
"icons/skill_mag_new50-12",
"icons/skill_mag_new50-13",
"icons/skill_mag_new50-14",
"icons/skill_mag_new50-15",
"icons/skill_mag_new50-2",
"icons/skill_mag_new50-3",
"icons/skill_mag_new50-4",
"icons/skill_mag_new50-5",
"icons/skill_mag_new50-6",
"icons/skill_mag_new50-7",
"icons/skill_mag_new50-8",
"icons/skill_mag_new50-9",
"icons/skill_mag_new60-1",
"icons/skill_mag_new60-2",
"icons/skill_mag_new60-3",
"icons/skill_mag_new60-4",
"icons/elf_skill/skill_mag_dru60",
"icons/elf_skill/skill_mag_dru70",
"icons/elf_skill/skill_mag_kni60",
"icons/elf_skill/skill_mag_kni70",
"icons/elf_skill/skill_mag_new15-6",
"icons/elf_skill/skill_mag_new15-7",
"icons/elf_skill/skill_mag_new20-6",
"icons/elf_skill/skill_mag_new20-7",
"icons/elf_skill/skill_mag_new25-1",
"icons/elf_skill/skill_mag_new25-2",
"icons/elf_skill/skill_mag_new30-1",
"icons/elf_skill/skill_mag_new30-2",
"icons/elf_skill/skill_mag_new30-3",
"icons/elf_skill/skill_mag_new30-4",
"icons/elf_skill/skill_mag_new35-1",
"icons/elf_skill/skill_mag_new35-2",
"icons/elf_skill/skill_mag_new35-3",
"icons/elf_skill/skill_mag_new35-4",
"icons/elf_skill/skill_mag_new40-1",
"icons/elf_skill/skill_mag_new40-2",
"icons/elf_skill/skill_mag_new40-3",
"icons/elf_skill/skill_mag_new40-4",
"icons/elf_skill/skill_mag_new45-1",
"icons/elf_skill/skill_mag_new45-2",
"icons/elf_skill/skill_mag_new50-1",
"icons/elf_skill/skill_mag_new50-2",
"icons/elf_skill/skill_mag_pri60",
"icons/elf_skill/skill_mag_pri70",
"icons/elf_skill/skill_mag_ran60",
"icons/elf_skill/skill_mag_ran70",
"icons/elf_skill/skill_mag_thi60",
"icons/elf_skill/skill_mag_thi70",
"icons/elf_skill/skill_mag_war60",
"icons/elf_skill/skill_mag_war70",
"icons/elf_skill/skill_mag_ward60",
"icons/elf_skill/skill_mag_ward70",
"icons/dwarf_skill/skill_mag_har15-1",
"icons/dwarf_skill/skill_mag_har20-1",
"icons/dwarf_skill/skill_mag_har25-1",
"icons/dwarf_skill/skill_mag_har30-1",
"icons/dwarf_skill/skill_mag_har35-1",
"icons/dwarf_skill/skill_mag_har40-1",
"icons/dwarf_skill/skill_mag_har45-1",
"icons/dwarf_skill/skill_mag_har50-1",
"icons/dwarf_skill/skill_mag_har60-1",
"icons/dwarf_skill/skill_mag_har70-1",
"icons/dwarf_skill/skill_mag_new15-1",
"icons/dwarf_skill/skill_mag_new20-1",
"icons/dwarf_skill/skill_mag_new25-1",
"icons/dwarf_skill/skill_mag_new30-1",
"icons/dwarf_skill/skill_mag_new35-1",
"icons/dwarf_skill/skill_mag_new40-1",
"icons/dwarf_skill/skill_mag_new45-1",
"icons/dwarf_skill/skill_mag_new50-1",
"icons/dwarf_skill/skill_mag_psy15-1",
"icons/dwarf_skill/skill_mag_psy20-1",
"icons/dwarf_skill/skill_mag_psy25-1",
"icons/dwarf_skill/skill_mag_psy30-1",
"icons/dwarf_skill/skill_mag_psy35-1",
"icons/dwarf_skill/skill_mag_psy40-1",
"icons/dwarf_skill/skill_mag_psy45-1",
"icons/dwarf_skill/skill_mag_psy50-1",
"icons/dwarf_skill/skill_mag_psy60-1",
"icons/dwarf_skill/skill_mag_psy70-1",
}
|
--Opens the host file explorer in the current active folder
if select(1,...) == "-?" then
printUsage(
"folder","Opens the host file explorer in the current active folder"
)
return
end
local term = require("terminal")
openAppData("/drives/"..term.getdrive()..term.getdirectory())
|
/*
* @package : rlib
* @module : rnet
* @author : Richard [http://steamcommunity.com/profiles/76561198135875727]
* @copyright : (C) 2018 - 2020
* @since : 1.1.0
* @website : https://rlib.io
* @docs : https://docs.rlib.io
*
* MIT License
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* standard tables and localization
*/
rlib = rlib or { }
local base = rlib
local mf = base.manifest
local prefix = mf.prefix
local script = mf.name
/*
* lib includes
*/
local helper = base.h
local access = base.a
local konsole = base.k
/*
* pkg declarations
*/
local manifest =
{
author = 'richard',
desc = 'network library',
build = 032620,
version = { 2, 0, 0 },
debug_id = 'rnet.debug.delay',
}
/*
* module declarations
*/
local dcat = 9
local ncat = 10
/*
* localizations
*/
local math = math
local module = module
local sf = string.format
/*
* enums
*
* RNET_UINT and RNET_INT allow for a specified num of bits to be written and read
*
* int : –2147483648 to 2147483647
* uint : 0 to 4294967295
*/
RNET_STR = 1
RNET_FLOAT = 2
RNET_BOOL = 3
RNET_TBL = 4
RNET_CLR = 5
RNET_UINT = 6
RNET_UINT4 = 7
RNET_UINT8 = 8
RNET_UINT16 = 9
RNET_UINT32 = 10
RNET_INT = 11
RNET_INT4 = 12
RNET_INT8 = 13
RNET_INT16 = 14
RNET_INT32 = 15
RNET_VEC = 16
RNET_PLY = 17
RNET_ENT = 18
RNET_BIT = 19
RNET_ID = 20 -- uint32 || item ids
RNET_UID32 = 21 -- str || pl steam32
RNET_UID64 = 22 -- str || pl steam64
RNET_UID64D = 23 -- double || pl steam64
RNET_DATE = 24 -- uint32 || timestamps
RNET_IDX = 50 -- development only
/*
* enum definitions
*
* determines how each net Read/Write should be handled
*/
local netconst_lib =
{
[ RNET_STR ] =
{
read = function( ) return net.ReadString( ) end,
write = function( val ) net.WriteString( val ) end,
},
[ RNET_FLOAT ] =
{
read = function( ) return net.ReadFloat( ) end,
write = function( val ) net.WriteFloat( val ) end,
},
[ RNET_BOOL ] =
{
read = function( ) return net.ReadBool( ) end,
write = function( val ) net.WriteBool( val ) end,
},
[ RNET_TBL ] =
{
read = function( ) return net.ReadTable( ) end,
write = function( val ) net.WriteTable( istable( val ) and val or { } ) end,
},
[ RNET_CLR ] =
{
read = function( ) return net.ReadColor( ) end,
write = function( val ) net.WriteColor( IsColor( val ) and val or Color( 0, 0, 0, 255 ) ) end,
},
[ RNET_UINT ] =
{
read = function( bits ) return net.ReadUInt( bits ) end,
write = function( val, bits ) net.WriteUInt( val, bits ) end,
},
[ RNET_UINT4 ] =
{
read = function( ) return net.ReadUInt( 4 ) end,
write = function( val ) net.WriteUInt( val, 4 ) end,
},
[ RNET_UINT8 ] =
{
read = function( ) return net.ReadUInt( 8 ) end,
write = function( val ) net.WriteUInt( val, 8 ) end,
},
[ RNET_UINT16 ] =
{
read = function( ) return net.ReadUInt( 16 ) end,
write = function( val ) net.WriteUInt( val, 16 ) end,
},
[ RNET_UINT32 ] =
{
read = function( ) return net.ReadUInt( 32 ) end,
write = function( val ) net.WriteUInt( val, 32 ) end,
},
[ RNET_INT ] =
{
read = function( bits ) return net.ReadInt( bits ) end,
write = function( val, bits ) net.WriteInt( val, bits ) end,
},
[ RNET_INT4 ] =
{
read = function( ) return net.ReadInt( 4 ) end,
write = function( val ) net.WriteInt( val, 4 ) end,
},
[ RNET_INT8 ] =
{
read = function( ) return net.ReadInt( 8 ) end,
write = function( val ) net.WriteInt( val, 8 ) end,
},
[ RNET_INT16 ] =
{
read = function( ) return net.ReadInt( 16 ) end,
write = function( val ) net.WriteInt( val, 16 ) end,
},
[ RNET_INT32 ] =
{
read = function( ) return net.ReadInt( 32 ) end,
write = function( val ) net.WriteInt( val, 32 ) end,
},
[ RNET_VEC ] =
{
read = function( ) return net.ReadVector( ) end,
write = function( val ) net.WriteVector( isvector( val ) and val or Vector( 0, 0, 0 ) ) end,
},
[ RNET_PLY ] =
{
read = function( ) return Player( net.ReadUInt( 16 ) ) end,
write = function( val ) net.WriteUInt( IsValid( val ) and val:UserID( ) or 0, 16 ) end,
},
[ RNET_ENT ] =
{
read = function( ) return net.ReadEntity( ) end,
write = function( val ) net.WriteEntity( helper.ok.any( val ) and val ) end,
},
[ RNET_BIT ] =
{
read = function( ) return net.ReadBit( ) end,
write = function( val ) net.WriteBit( val ) end,
},
[ RNET_ID ] =
{
read = function( ) return net.ReadUInt( 32 ) end,
write = function( val ) net.WriteUInt( val, 32 ) end,
},
[ RNET_UID32 ] =
{
read = function( ) return net.ReadString( ) end,
write = function( val ) net.WriteString( val ) end,
},
[ RNET_UID64 ] =
{
read = function( ) return net.ReadString( ) end,
write = function( val ) net.WriteString( val ) end,
},
[ RNET_UID64D ] =
{
read = function( ) return net.ReadDouble( ) end,
write = function( val ) net.WriteDouble( val ) end,
},
[ RNET_DATE ] =
{
read = function( ) return net.ReadUInt( 32 ) end,
write = function( val ) net.WriteUInt( val, 32 ) end,
},
}
/*
* Localized translation func
*/
local function lang( ... )
return base:lang( ... )
end
/*
* call id
*
* @source : lua\autorun\libs\_calls
* @param : str id
*/
local function call_id( id )
local ret = isfunction( rlib.call ) and rlib:call( 'net', id ) or id
return ret
end
/*
* prefix :: create id
*/
local function pref( id, suffix )
local affix = istable( suffix ) and suffix.id or isstring( suffix ) and suffix or prefix
affix = affix:sub( -1 ) ~= '.' and string.format( '%s.', affix ) or affix
id = isstring( id ) and id or 'noname'
id = id:gsub( '[%c%s]', '.' )
return string.format( '%s%s', affix, id )
end
/*
* prefix :: handle
*/
local function pid( str, suffix )
local state = ( isstring( suffix ) and suffix ) or ( base and mf.prefix ) or false
return pref( str, state )
end
/*
* define module
*/
module( 'rnet', package.seeall )
/*
* local declarations
*/
local pkg = rnet
local pkg_name = _NAME or 'rnet'
/*
* required tables
*/
cfg = cfg or { }
sys = sys or { }
index = index or { }
directory = directory or { }
execute = execute or { }
routing = routing or { }
routing.save = routing.save or { }
send = { }
/*
* net :: debugging
*
* determines if debugging mode is enabled
*/
cfg.debug = cfg.debug or false
/*
* returns directory table
*/
function get_directory( )
return istable( directory ) and directory or { }
end
/*
* returns index table
*/
function get_index( )
return istable( index ) and index or { }
end
/*
* reroute network functions
*
* @param : func old_fn
* @param : func new_fn
*/
local function act_route( old_fn, new_fn )
if not isfunction( old_fn ) or not isfunction( new_fn ) then
base:log( dcat, '[ %s ] bad arg type for func [ %s ]', pkg_name, debug.getinfo( 1, 'n' ).name )
return false
end
execute[ new_fn ] = old_fn
return new_fn
end
/*
* rnet :: reroute
*
* redirects netlib funcs to allow for prints to output to console and for logs to catch any data
* being transferred
* : enable rnet:route( bEnable )
* : disable rnet:route( )
*
* @param : bool bEnable
*/
function rnet:route( bEnable )
local restore = routing.save or { }
if not bEnable then
if sys.nrouter_enabled then
net.Start = restore[ 'start' ] or net.Start
net.Receive = restore[ 'receive' ] or net.Receive
net.Incoming = restore[ 'incoming' ] or net.Incoming
sys.nrouter_enabled = false
base:log( ncat, '[%s] Rerouting disabled', pkg_name )
return false
else
base:log( ncat, '[%s] Rerouting is currently not enabled', pkg_name )
return false
end
end
execute = execute or { }
if not sys.nrouter_f or sys.nrouter_f == nil then sys.nrouter_f = true end
if sys.nrouter_f then
restore[ 'start' ] = not restore[ 'start' ] and net.Start or restore[ 'start' ]
restore[ 'receive' ] = not restore[ 'receive' ] and net.Receive or restore[ 'receive' ]
restore[ 'incoming' ] = not restore[ 'incoming' ] and net.Incoming or restore[ 'incoming' ]
net.Start = act_route( net.Start, function( name, unreliable )
execute[ net.Start ]( name, unreliable )
base:log( dcat, 'net.Start :: [ %s ]', name )
end )
net.Receive = act_route( net.Receive, function( name, callback )
execute[ net.Receive ]( name, callback )
base:log( dcat, 'net.Receive :: [ %s ]', name )
end )
sys.nrouter_enabled, sys.nrouter_f = true, false
end
function net.Incoming( len, client )
local i = net.ReadHeader( )
local name = util.NetworkIDToString( i )
if not name then
base:log( dcat, 'net.Incoming :: unpooled msg id for [ #%d ]', i )
return false
end
local func = net.Receivers[ name:lower( ) ]
if not func then
base:log( dcat, 'net.Incoming :: receiving func missing for [ %s ] net msg [ #%d ]', name, i )
return false
end
len = len - 16
base:log( dcat, 'net.Incoming :: [ %s ] ( %d ) received ( %.2f kb ( %d b ) )', name, i, len / 8 / 1024, len / 8 )
func( len, client )
end
base:log( dcat, 'netlib functions being rerouted for debugging' )
end
/*
* status
*
* check status of routing
*/
function route_status( )
local status = sys.nrouter_enabled and 'enabled' or 'disabled'
base:log( ncat, 'routing [ %s ]', status )
end
/*
* make_id
*
* creates a new id for directory / index entries
*
* @param : tbl src
* @return : int
*/
local function make_id( src )
if not src or not istable( src ) then
base:log( dcat, 'cannot make id from invalid table' )
return false
end
local id = table.Count( src ) + 1
return id or 1
end
/*
* rnet :: create
*
* creates a new netmsg data value
*
* @ex : rnet.create( 'network_string' )
* rnet.create( call( 'net', 'network_string' ) )
*
* @alias : new
*
* @param : str id
*/
function create( id )
if not isstring( id ) then
base:log( dcat, 'canceling net create - missing id' )
return
end
id = call_id( id )
local n_id = make_id( index )
directory =
{
id = id,
nid = n_id,
params = { },
}
base:log( dcat, 'created netlib entry [ %s ] [ %i ]', id, n_id )
end
new = create
/*
* rnet :: write
*
* used to specify a new item to pass through the netmsg
*
* bits
* :: number 1 to 32
* 1 = bit
* 4 = nibble
* 8 = byte
* 16 = short
* 32 = long
*
* @ex : pass string: rnet.write( 'item_name', RNET_STR )
* pass int: rnet.write( 'item_name', RNET_INT, 4 )
*
* @param : str name
* @param : con enum
* @param : int bits
*/
function write( name, enum, bits )
local gid = make_id( directory.params )
bits = bits and math.Clamp( bits, 0, 32 ) or 0
directory.params[ name ] =
{
id = gid,
enum = enum,
bits = bits
}
end
add = write
/*
* rnet :: register
*
* called after setting up a new network entry
*
* @ex : rnet.register( )
*/
function register( )
local id = directory.id
if not isstring( id ) then
base:log( dcat, 'cannot register with invalid id' )
return false
end
index[ id ] = table.Copy( directory )
if SERVER then
util.AddNetworkString( id )
base:log( dcat, 'registered id [ %s ]', id )
end
end
run = register
/*
* rnet :: read
*
* fetches the specified const from net const table
*
* @param : int const
* @param : int bits
* @return : tbl
*/
local function read( const, bits )
if not netconst_lib[ const ] then
base:log( dcat, 'invalid read type specified' )
return false
end
local result = netconst_lib[ const ].read( bits )
return result
end
/*
* rnet :: call / get
*
* requires id (str)
*
* a, b are shiftable between bool / func
* a specifies a bool for silencing the konsole or can be specified as a function but debugging
* will return a response in the console
*
* @param : str id
* @param : bool, func a
* @param : func b
*/
function call( id, a, b )
local bSilenced = false
local action
/*
* check :: a, b exist
*/
if not a and not b then
base:log( dcat, 'canceling netmsg call -- missing params for id [ %s ]', id )
return false
end
/*
* get net id
*
* utilizes rlib.call
*/
id = call_id( id )
/*
* a false but b provided
*/
if not a and isfunction( b ) then
action = b
elseif isfunction( a ) then
action = a
elseif isbool( a ) and isfunction( b ) then
bSilenced = a and true or false
action = b
end
net.Receive( id, function( len, ply )
local obj, data = index[ id ], { }
for item, param in SortedPairsByMemberValue( obj.params, 'id' ) do
local bits = param and param.bits or 0
data[ item ] = read( param.enum, bits )
end
if not action or not isfunction( action ) then
base:log( dcat, 'call :: net.Receive :: [ %s ] :: missing action', id )
return false
end
action( data, ply )
if not bSilenced then
base:log( dcat, 'call :: net.Receive :: [ %s ] :: %i b', id, len / 8 )
end
end )
end
get = call
/*
* rnet :: setup
*
* runs during rnet prep to setup network structure including params and read/write bit sizes (if applic)
*
* @param : con const
* @param : str val
* @param : int bits
*/
local function setup( const, val, bits )
netconst_lib[ const ].write( val, bits )
end
/*
* rnet :: prepare
*
* data are the items that will be passed through the netmsg
*
* @param : str id
* @param : tbl data
* @param : bool bSilence
*/
local function prepare( id, data, bSilence )
if not isstring( id ) then
base:log( dcat, 'prepare :: cannot prep an invalid id' )
return
end
id = call_id( id )
local obj = index[ id ]
if not istable( obj ) then
base:log( dcat, 'prepare [ %s ] :: cannot prep an unregistered object -- check for valid module / lib hook [ %s ]', id, 'rnet.register' )
return
end
net.Start( id )
for item, param in SortedPairsByMemberValue( obj.params, 'id' ) do
local bits = param and param.bits or 0
setup( param.enum, data[ item ], bits )
end
if not bSilence then
local sent = net.BytesWritten( )
base:log( dcat, 'prepare [ %s ] :: %i b', id, sent )
end
end
if SERVER then
/*
* rnet :: send :: player
*
* sends netmsg to specified player
*
* @ex : rnet.send.player( ply, 'netmsg_str_id', { item_id = id } )
* : rnet.send.player( ply, 'netmsg_str_id' )
*
* @param : ply pl
* @param : str id
* @param : tbl data
* @param : bool bSilence
*/
function send.player( pl, id, data, bSilence )
if not helper.ok.ply( pl ) and not istable( pl ) then
base:log( dcat, '[ %s ] :: [ %s ] :: invalid pl', debug.getinfo( 1, 'n' ).name, id )
return false
end
if not id then
local trcback = debug.traceback( )
base:log( dcat, 'bad rnet id specified\n%s', trcback )
return
end
local bSilenced = bSilence and true or false
id = call_id( id )
prepare( id, data, bSilenced )
net.Send( pl )
end
/*
* rnet :: send :: all
*
* sends broadcasted netmsg to all players
*
* @ex : rnet.send.all( 'netmsg_str_id', { item_id = id } )
* : rnet.send.all( 'netmsg_str_id' )
*
* @param : str id
* @param : tbl data
* @param : bool bSilence
*/
function send.all( id, data, bSilence )
if not id then
local trcback = debug.traceback( )
base:log( dcat, 'bad rnet id specified\n%s', trcback )
return
end
local bSilenced = bSilence and true or false
id = call_id( id )
prepare( id, data, bSilenced )
net.Broadcast( )
end
/*
* rnet :: send :: pvs
*
* sends msg to players that can potentially see this position
*
* @ex : rnet.send.pvs( pos, 'netmsg_str_id', { item_id = id } )
* : rnet.send.pvs( Vector( 0, 0, 0 ), 'netmsg_str_id' )
*
* @param : vec vec
* @param : str id
* @param : tbl data
* @param : bool bSilence
*/
function send.pvs( vec, id, data, bSilence )
if not isvector( vec ) then
base:log( dcat, '[ %s ] :: [ %s ] :: invalid PVS vector', debug.getinfo( 1, 'n' ).name, id )
return false
end
if not id then
local trcback = debug.traceback( )
base:log( dcat, 'bad rnet id specified\n%s', trcback )
return
end
local bSilenced = bSilence and true or false
prepare( id, data, bSilenced )
net.SendPVS( vec )
end
/*
* rnet :: send :: pas
*
* adds all plys that can potentially hear sounds from this position.
*
* @ex : rnet.send.pas( pos, 'netmsg_str_id', { item_id = id } )
* : rnet.send.pas( Vector( 0, 0, 0 ), 'netmsg_str_id' )
*
* @param : vec vec
* @param : str id
* @param : tbl data
* @param : bool bSilence
*/
function send.pas( vec, id, data, bSilence )
if not isvector( vec ) then
base:log( dcat, '[ %s ] :: [ %s ] :: invalid PAS vector', debug.getinfo( 1, 'n' ).name, id )
return false
end
if not id then
local trcback = debug.traceback( )
base:log( dcat, 'bad rnet id specified\n%s', trcback )
return
end
local bSilenced = bSilence and true or false
prepare( id, data, bSilenced )
net.SendPAS( vec )
end
else
/*
* rnet :: send.server
*
* sends netmsg to server
*
* @ex : rnet.send.server( 'netmsg_str_id', { item_id = id } )
* : rnet.send.server( 'netmsg_str_id' )
*
* @param : str id
* @param : tbl data
*/
function send.server( id, data )
if not id then
local trcback = debug.traceback( )
base:log( dcat, 'bad rnet id specified\n%s', trcback )
return
end
prepare( id, data )
net.SendToServer( )
end
end
/*
* scope :: server
*/
if SERVER then
/*
* network strings
*/
util.AddNetworkString( 'rnet.eff.add' )
util.AddNetworkString( 'rnet.eff.rem' )
/*
* effect :: add
*
* adds a particle
*
* @ex : rnet.fx_add( 'particle_name', self, self:GetAngles( ), self:GetPos( ), nil, 1 )
* rnet.fx_add( 'particle_name', ent, Vector( x, x, x ), Vector( x, x, x ), 'sound/path.wav', 1, 4 )
* rnet.fx_add( 'particle_name', self )
*
* @params : eff name of particle
* snd sound file to attach
* parent parent ent
* ang vector angle
* pos vector position
* attach_id id of the attachment to be used in the way specified by the attachType
* attach_type attachment type using PATTACH_Enums
* : 0 PATTACH_ABSORIGIN
* : 1 PATTACH_ABSORIGIN_FOLLOW
* : 2 PATTACH_CUSTOMORIGIN
* : 3 PATTACH_POINT
* : 4 PATTACH_POINT_FOLLOW
* : 5 PATTACH_WORLDORIGIN
*
* @param : str eff
* @param : ent parent
* @param : vec ang
* @param : vec pos
* @param : str snd
* @param : int attach_id
* @param : int attach_type
*/
function fx_add( eff, parent, ang, pos, snd, attach_id, attach_type )
if not isstring( eff ) then return end
if not IsValid( parent ) then return end
local fx = { }
fx.eff = eff
fx.parent = parent
fx.ang = isvector( ang ) and ang or IsValid( parent ) and parent:GetAngles( )
fx.pos = isvector( pos ) and pos or IsValid( parent ) and parent:GetPos( )
fx.snd = isstring( snd ) and snd or nil
fx.attach_id = isnumber( attach_id ) and attach_id or 1
fx.attack_type = isnumber( attach_type ) and attach_type or attach_type or 4
rnet.send.all( 'rnet.eff.add', { src = fx } )
end
/*
* effect :: remove
*
* removes a particle
*
* @ex : rnet.fx_rem( self, 'particle_name', nil )
* rnet.fx_rem( Vector( x, x, x ), 'particle_name', 'sound/file.wav' )
*
* @param : vec, ent parent
* @param : str eff
* @param : str snd
*/
function fx_rem( parent, eff, snd )
if not helper.ok.ent( parent ) and not isvector( parent ) then return end
local pos = isvector( parent ) and parent or helper.ok.ent( parent ) and parent:GetPos( ) or Vector( 0, 0, 0 )
local fx = { }
fx.eff = eff
fx.parent = parent
fx.snd = snd
rnet.send.all( 'rnet.eff.rem', { src = fx } )
end
end
/*
* scope :: client
*/
if CLIENT then
/*
* rnet :: effect :: add
*
* @param : tbl data
*/
local function fx_eff_add( data )
local fx = data.src
if not fx then return end
if fx.parent == nil then return end
if not IsValid( fx.parent ) then return end
if fx.snd then
fx.parent:EmitSound( fx.snd )
end
if fx.eff then
if fx.attach then
ParticleEffectAttach( fx.eff, fx.attach_type or 4 , fx.parent, fx.attach_id )
else
ParticleEffect( fx.eff, fx.pos, fx.ang, fx.parent )
end
end
end
rnet.call( 'rnet.eff.add', fx_eff_add )
/*
* rnet :: effect :: remove
*
* @param : tbl data
*/
local function fx_eff_rem( data )
local fx = data.src
if not fx then return end
if fx.parent == nil then return end
if not IsValid( fx.parent ) then return end
if fx.snd then
fx.parent:StopSound( fx.snd )
end
if fx.eff then
fx.parent:StopParticlesNamed( fx.eff )
end
end
rnet.call( 'rnet.eff.rem', fx_eff_rem )
end
/*
* rcc :: debug
*
* toggles rnet debug mode
*/
function rcc.call:RNet_Debug( ply, cmd, args )
/*
* permissions
*/
local ccmd = base.calls:get( 'commands', 'rnet_debug' )
if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then
access:deny_consoleonly( ply, script, ccmd.id )
return
end
if not access:bIsRoot( ply ) then
access:deny_permission( ply, script, ccmd.id )
return
end
local time_id = manifest.debug_id
local status = args and args[ 1 ] or false
local dur = args and args[ 2 ] or 300
if status and status ~= 'status' then
local param_status = helper.util:toggle( status )
if param_status then
if timex.exists( time_id ) then
local remains = timex.secs.sh_cols_steps( timex.remains( time_id ) ) or 0
base:log( 4, lang( 'debug_enabled_already', remains ) )
return
end
if dur and not helper:bIsNum( dur ) then
base:log( ncat, lang( 'debug_err_duration' ) )
return
end
cfg.debug = true
base:log( ncat, lang( 'debug_set_enabled_dur', dur ) )
konsole:send( ply, 1, lang( 'debug_set_enabled_dur', dur ) )
timex.create( time_id, dur, 1, function( )
base:log( ncat, lang( 'debug_auto_disable' ) )
cfg.debug = false
end )
else
timex.expire( time_id )
base:log( ncat, lang( 'debug_set_disabled' ) )
cfg.debug = false
end
else
if cfg.debug then
if timex.exists( time_id ) then
local remains = timex.secs.sh_cols_steps( timex.remains( time_id ) ) or 0
base:log( ncat, lang( 'debug_enabled_time', remains ) )
else
base:log( ncat, lang( 'debug_enabled' ) )
end
return
else
base:log( ncat, lang( 'debug_disabled' ) )
end
base:log( ncat, lang( 'rnet_debug_help_info_1' ) )
base:log( ncat, lang( 'rnet_debug_help_info_2' ) )
end
end
/*
* rcc :: refresh
*
* refreshes rnet
*/
function rcc.call:RNet_Refresh( ply, cmd, args )
/*
* permissions
*/
local ccmd = base.calls:get( 'commands', 'rnet_refresh' )
if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then
access:deny_consoleonly( ply, script, ccmd.id )
return
end
if not access:bIsRoot( ply ) then
access:deny_permission( ply, script, ccmd.id )
return
end
/*
* reload all rnet registration hooks
*/
if not rcore then
base.msg:route( ply, false, pkg_name, 'cannot reload rnet registration hooks -- rcore missing' )
return
end
/*
* loop rcore modules
*/
for k, v in pairs( rcore.modules ) do
if not v.enabled then continue end
local suffix = rcore:modules_prefix( v )
local id = sf( '%srnet.register', suffix )
rhook.run.gmod( id )
if rnet.cfg.debug then
base:log( dcat, 'registered module [ %s ]', id )
end
end
base.msg:route( ply, false, pkg_name, 'reloaded all rnet packages' )
end
/*
* rcc :: index
*
* returns index for rnet
*/
function rcc.call:RNet_Index( ply, cmd, args )
/*
* permissions
*/
local ccmd = base.calls:get( 'commands', 'rnet_index' )
if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then
access:deny_consoleonly( ply, script, ccmd.id )
return
end
if not access:bIsRoot( ply ) then
access:deny_permission( ply, script, ccmd.id )
return
end
/*
* functionality
*/
local output = sf( '\n\n [ %s ] :: %s :: index', script, pkg_name )
base:console ( ply, output )
base:console ( ply, '\n--------------------------------------------------------------------------------------------' )
helper.p_table ( index )
base:console ( ply, '\n--------------------------------------------------------------------------------------------' )
end
/*
* rcc :: reroute netmsg
*
* after being activated, all net msgs sent and received will be logged in the console.
*/
function rcc.call:RNet_Router( ply, cmd, args )
/*
* permissions
*/
local ccmd = base.calls:get( 'commands', 'rnet_router' )
if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then
access:deny_consoleonly( ply, script, ccmd.id )
return
end
if not access:bIsRoot( ply ) then
access:deny_permission( ply, script, ccmd.id )
return
end
/*
* functionality
*/
local arg_toggle = args and args[ 1 ]
arg_toggle = helper.util:toggle( arg_toggle )
if not rnet then
base:log( 2, '%s module not found, cannot toggle routing', pkg_name )
return false
end
rnet:route( arg_toggle )
end
/*
* concommand :: base command
*
* base package command
*/
function rcc.call:RNet( ply, cmd, args )
/*
* permissions
*/
local ccmd = base.calls:get( 'commands', 'rnet' )
if ( ccmd.scope == 1 and not base.con:Is( ply ) ) then
access:deny_consoleonly( ply, script, ccmd.id )
return
end
if not access:bIsRoot( ply ) then
access:deny_permission( ply, script, ccmd.id )
return
end
base.msg:route( ply, false, pkg_name, script .. ' package' )
base.msg:route( ply, false, pkg_name, 'v' .. rlib.get:ver2str( manifest.version ) .. ' build-' .. manifest.build )
base.msg:route( ply, false, pkg_name, 'developed by ' .. manifest.author )
base.msg:route( ply, false, pkg_name, manifest.desc .. '\n' )
end
/*
* make id
*
* creates a package specific id
* returns only package name if str missing
*
* @param : str str
*/
local function new_id( str )
str = isstring( str ) and str ~= '' and str or false
if not str then
return pkg_name
end
return pid( str, pkg_name )
end
/*
* register new commands
*/
local function register_commands( )
local pkg_commands =
{
[ pkg_name ] =
{
enabled = true,
warn = true,
id = new_id( ),
desc = 'returns package information',
scope = 2,
clr = Color( 255, 255, 0 ),
assoc = function( ... )
rcc.call:RNet( ... )
end,
},
[ pkg_name .. '_debug' ] =
{
enabled = true,
warn = true,
id = new_id( 'debug' ),
desc = 'toggles rnet debugging which must be enabled to view netmsg outputs',
scope = 1,
clr = Color( 255, 255, 0 ),
assoc = function( ... )
rcc.call:RNet_Debug( ... )
end,
},
[ pkg_name .. '_refresh' ] =
{
enabled = true,
warn = true,
id = new_id( 'refresh' ),
desc = 'reload all module rnet registration hooks',
scope = 1,
clr = Color( 255, 255, 0 ),
assoc = function( ... )
rcc.call:RNet_Refresh( ... )
end,
},
[ pkg_name .. '_router' ] =
{
enabled = true,
warn = true,
id = new_id( 'router' ),
desc = 'toggles debug mode network routing',
scope = 1,
clr = Color( 255, 255, 0 ),
assoc = function( ... )
rcc.call:RNet_Router( ... )
end,
},
[ pkg_name .. '_index' ] =
{
enabled = true,
warn = true,
id = new_id( 'index' ),
desc = 'returns rnet index',
scope = 1,
clr = Color( 255, 255, 0 ),
assoc = function( ... )
rcc.call:RNet_Index( ... )
end,
},
}
base.calls.commands:Register( pkg_commands )
end
hook.Add( pid( 'cmd.register' ), pid( '__rnet.cmd.register' ), register_commands )
/*
* localized netlibs
*/
local function register_rnet_libs( )
timer.Simple( 5, function( )
create ( 'rnet.eff.add' )
write ( 'src', RNET_TBL )
register ( )
create ( 'rnet.eff.rem' )
write ( 'src', RNET_TBL )
register ( )
end )
end
register_rnet_libs( )
/*
* register package
*/
local function register_pkg( )
if not istable( _M ) then return end
base.package:Register( _M )
end
hook.Add( pid( 'pkg.register' ), pid( '__rnet.pkg.register' ), register_pkg )
/*
* module info :: manifest
*/
function pkg:manifest( )
return self.__manifest
end
/*
* __tostring
*/
function pkg:__tostring( )
return self:_NAME( )
end
/*
* create new class
*/
function pkg:loader( class )
class = class or { }
self.__index = self
return setmetatable( class, self )
end
/*
* __index / manifest declarations
*/
pkg.__manifest =
{
__index = _M,
name = _NAME,
build = manifest.build,
version = manifest.version,
author = manifest.author,
desc = manifest.desc
}
pkg.__index = pkg
|
-- WARNING: this program will not break branches, make sure that your tree will
-- not make branches. you can achieve this by puting your tree in a room with
-- an appropiatly highted roof (6 blocks high I believe) or by using a tree
-- type which doesn't make branches
local fuel = { ["minecraft:coal"] = true, ["minecraft:lava_bucket"] = true, ["chisel:block_charcoal"] = true, ["chisel:block_charcoal1"] = true, ["chisel:block_charcoal2"] = true }
local maxWaitTime = 120
local targetFuelLevel = 500
-- TODO: offer to delete things on error when the only way to continue is to delete .LAMA etc.
local leaves = "minecraft:leaves"
local logs = "minecraft:log"
local saplings = "minecraft:sapling"
local chest = "minecraft:chest"
local trappedChest = "minecraft:trapped_chest"
local scanner = peripheral.find("plethora:scanner")
local lama = {} -- TODO: extract to module
local lamaInit = false
do
--[[ The MIT License (MIT)
-- Copyright (c) 2015 KingofGamesYami
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to
-- deal in the Software without restriction, including without limitation the
-- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-- sell copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions: The above copyright
-- notice and this permission notice shall be included in all copies or
-- substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-- IN THE SOFTWARE.
--]]
-- Converted to be Require compatible by Lupus590 and released under the same MIT license.
-- Look for REQUIRE_COMPAT in comments, the connected multi line comments are removed original stuff with the replacement under that.
-- REQUIRE_COMPAT
--Copy the default turtle directory
local turtle = {}
for k, v in pairs( _G.turtle ) do
turtle[ k ] = v
end
--copy default gps
local gps = {}
for k, v in pairs( _G.gps ) do
gps[ k ] = v
end
if not fs.isDir( ".lama" ) then
local _, blockInfoDown = turtle.inspectDown()
local _, blockInfoForwards = turtle.inspect()
if blockInfoDown and blockInfoDown.name == chest and blockInfoForwards and (blockInfoForwards.name == logs or blockInfoForwards.name == saplings) then
lamaInit = true
else
error("Not in the right location, this is not home. A sapling or log is used for orientation, try planting one if you are sure this is right.", 0)
end
fs.makeDir( ".lama" )
end
-- REQUIRE_COMPAT
_G.LAMA = {}
local env = lama
local fuel = {}
local facing = {}
local position = {}
--Fuel tracking
fuel.load = function() --loading fuel data
if fs.exists( ".lama/fuel" ) then --if we've got previous data, we want to use it
local file = fs.open( ".lama/fuel", "r" )
fuel.amount = tonumber( file.readAll() )
file.close()
else --otherwise, use the current fuel level
fuel.amount = turtle.getFuelLevel()
end
end
fuel.save = function() --save fuel data
local file = fs.open( ".lama/fuel", "w" )
file.write( fuel.amount )
file.close()
end
--facing tracking
facing.turnRight = function() --changes the facing clockwise (on a compass) once
if facing.face == "north" then
facing.face = "east"
elseif facing.face == "east" then
facing.face = "south"
elseif facing.face == "south" then
facing.face = "west"
elseif facing.face == "west" then
facing.face = "north"
end
end
facing.save = function() --saves facing and current movement direction
local file = fs.open( ".lama/facing", "w" )
file.write( textutils.serialize( {facing.face, facing.direction} ) )
file.close()
end
facing.load = function() --loads facing / current movement direction
if fs.exists( ".lama/facing" ) then --if we have previous data, we use it
local file = fs.open( ".lama/facing", "r" )
facing.face, facing.direction = unpack( textutils.unserialize( file.readAll() ) )
file.close()
else --otherwise, try to locate via gps
local x, y, z = gps.locate(1)
if x and turtle.forward() then
local newx, newy, newz = gps.locate(1)
if not newx then --we didn't get a location
facing.face = "north" --default
elseif newx > x then
facing.face = "east"
elseif newx < x then
facing.face = "west"
elseif newz > z then
facing.face = "south"
elseif newz < z then
facing.face = "north"
end
else
facing.face = "north" --we couldn't move forward, something was obstructing
end
end
end
--position tracking
position.save = function() --saves position (x, y, z)
position.update() --update the position based on direction and fuel level, then save it to a file
local file = fs.open( ".lama/position", "w" )
file.write( textutils.serialize( { position.x, position.y, position.z } ) )
file.close()
end
position.load = function() --loads position (x, y z)
if fs.exists( ".lama/position" ) then --if we have previous data, use it
local file = fs.open( ".lama/position", "r" )
position.x, position.y, position.z = unpack( textutils.unserialize( file.readAll() ) )
file.close()
else --otherwise try for gps coords
local x, y, z = gps.locate(1)
if x then
position.x, position.y, position.z = x, y, z
else --now we assume 1,1,1
position.x, position.y, position.z = 1, 1, 1
end
end
end
position.update = function() --updates the position of the turtle
local diff = fuel.amount - turtle.getFuelLevel()
if diff > 0 then --if we've spent fuel (ei moved), we'll need to move that number in a direction
if facing.direction == 'east' then
position.x = position.x + diff
elseif facing.direction == "west" then
position.x = position.x - diff
elseif facing.direction == "south" then
position.z = position.z + diff
elseif facing.direction == "north" then
position.z = position.z - diff
elseif facing.direction == "up" then
position.y = position.y + diff
elseif facing.direction == "down" then
position.y = position.y - diff
end
end
fuel.amount = turtle.getFuelLevel() --update the fuel amount
fuel.save() --save the fuel amount
end
--direct opposite compass values, mainly for env.back
local opposite = {
["north"] = "south",
["south"] = "north",
["east"] = "west",
["west"] = "east",
}
env.forward = function() --basically, turtle.forward
if facing.direction ~= facing.face then --if we were going a different direction before
position.save() --save out position
facing.direction = facing.face --update the direction
facing.save() --save the direction
end
return turtle.forward() --go forward, return result
end
env.back = function() --same as env.forward, but going backwards
if facing.direction ~= opposite[ facing.face ] then
position.save()
facing.direction = opposite[ facing.face ]
facing.save()
end
return turtle.back()
end
env.up = function() --turtle.up
if facing.direction ~= "up" then --if we were going a different direction
position.save() --save our position
facing.direction = "up" --set the direction to up
facing.save() --save the direction
end
return turtle.up() --go up, return result
end
env.down = function() --env.up, but for going down
if facing.direction ~= "down" then
position.save()
facing.direction = "down"
facing.save()
end
return turtle.down()
end
env.turnRight = function() --turtle.turnRight
position.save() --save the position (x,y,z)
facing.turnRight() --update our compass direction
facing.save() --save it
return turtle.turnRight() --return the result
end
env.turnLeft = function() --env.turnRight, but the other direction
position.save()
facing.turnRight() --going clockwise 3 times is the same as
facing.turnRight() --going counterclockwise once
facing.turnRight()
facing.save()
return turtle.turnLeft()
end
env.refuel = function( n ) --needed because we depend on fuel level
position.update() --update our position
if turtle.refuel( n ) then --if we refueled then
fuel.amount = turtle.getFuelLevel() --set our amount to the current level
fuel.save() --save that amount
return true
end
return false --otherwise, return false
end
env.overwrite = function( t ) --writes env values into the table given
t = t or _G.turtle --or, if no value was given, _G.turtle
for k, v in pairs( env ) do
t[ k ] = v
end
end
env.getPosition = function() --returns the current position of the turtle
position.update() --first we should update the position (otherwise it'll give coords of the last time we did this)
return position.x, position.y, position.z, facing.face
end
env.setPosition = function( x, y, z, face ) --sets the current position of the turtle
position.x = x
position.y = y
position.z = z
facing.face = face or facing.face --default the the current facing if it's not provided
position.save() --save our new position
facing.save() --save the way we are facing
end
--overwrite gps.locate
_G.gps.locate = function( n, b )
local x, y, z, facing = env.getPosition()
return x, y, z
end
facing.load()
position.load()
fuel.load()
fuel.save()
position.save()
facing.save()
-- REQUIRE_COMPAT
_G.LAMA = env
end
lama.overwrite()
if lamaInit then
lama.setPosition(0, 0, 0, "north") -- we don't care if this is true globally, we just want to be able to find it again
end
local movementStack = {} -- TODO: extract to module
do
local fileLocation = ".movementStack"
local stack
do
local f = fs.open(fileLocation, "r")
local s = f and f.readAll()
stack = s and textutils.unserialise(s)
end
stack = stack or {n = 0}
local inverter = {
["forward"] = turtle.back,
["back"] = turtle.forward,
["turnLeft"] = turtle.turnRight,
["turnRight"] = turtle.turnLeft,
["up"] = turtle.down,
["down"] = turtle.up,
}
local function saveStack()
io.open(fileLocation, "w"):write(textutils.serialise(stack)):close()
end
-- TODO: don't save if we didn't move (this could be the source of us getting lost)
function movementStack.pushForward()
stack.n = stack.n+1
stack[stack.n] = "forward"
saveStack()
return turtle.forward()
end
function movementStack.pushBack()
stack.n = stack.n+1
stack[stack.n] = "back"
saveStack()
return turtle.back()
end
function movementStack.pushTurnRight()
stack.n = stack.n+1
stack[stack.n] = "turnRight"
saveStack()
return turtle.turnRight()
end
function movementStack.pushTurnLeft()
stack.n = stack.n+1
stack[stack.n] = "TurnLeft"
saveStack()
return turtle.TurnLeft()
end
function movementStack.pushUp()
stack.n = stack.n+1
stack[stack.n] = "up"
saveStack()
return turtle.up()
end
function movementStack.pushDown()
stack.n = stack.n+1
stack[stack.n] = "down"
saveStack()
return turtle.down()
end
function movementStack.pop() -- TODO: inteligently look several ahead and simplify rotations
if stack.n-1 < 0 then
error("got lost", 0)
end
local moveToUndo = stack[stack.n]
stack[stack.n] = nil
stack.n = stack.n-1
--[[if moveToUndo == "turnRight" or moveToUndo == "turnLeft" and stack[stack.n] == moveToUndo and stack[stack.n-1] == moveToUndo and stack[stack.n-2] == moveToUndo then -- doesn't work, makes it go to the wrong place
stack[stack.n] = nil
stack[stack.n-1] = nil
stack[stack.n-2] = nil
stack.n = stack.n-2
return movementStack.pop()
end]]
local undoFunction = inverter[moveToUndo] --or function() end
saveStack()
return undoFunction()
end
function movementStack.hasMovements()
return stack.n > 0
end
end
local veinMine -- TODO: smartly mine all the leaves - traveling salesman problem algorithm with plethora block scanner
-- TODO: extract to module?
do
local function isDesireable()
local ok, item = turtle.inspect()
return ok and item.name == leaves
end
local function isDesireableUp()
local ok, item = turtle.inspectUp()
return ok and item.name == leaves
end
local function isDesireableDown()
local ok, item = turtle.inspectDown()
return ok and item.name == leaves
end
function veinMine()
for i = 1, 4 do
if isDesireable() then
turtle.dig()
movementStack.pushForward()
veinMine()
if not movementStack.pop() then error("Bad pop movement.") end
end
movementStack.pushTurnRight()
end
if isDesireableUp() then
turtle.digUp()
movementStack.pushUp()
veinMine()
if not movementStack.pop() then error("Bad pop movement.") end
end
if isDesireableDown() then
turtle.digDown()
movementStack.pushDown()
veinMine()
if not movementStack.pop() then error("Bad pop movement.") end
end
for i = 1, 4 do
if not movementStack.pop() then error("Bad pop movement.") end
end
end
end
local checkpoint = {}
do
--[[
-- @Name: Checkpoint
-- @Author: Lupus590
-- @License: MIT
-- @URL: https://github.com/CC-Hive/Checkpoint
--
-- If you are interested in the above format: http://www.computercraft.info/forums2/index.php?/topic/18630-rfc-standard-for-program-metadata-for-graphical-shells-use/
--
-- Includes stack tracing code from SquidDev's Mildly Better Shell (Also known as MBS): http://www.computercraft.info/forums2/index.php?/topic/29253-mildly-better-shell-various-extensions-to-the-default-shell/
--
-- Checkpoint doesn't save your program's data, it must do that itself. Checkpoint only helps it to get to roughly the right area of code to resume execution.
--
-- One may want to have a table with needed data in which gets passed over checkpoints with each checkpoint segment first checking that this table exists and loading it from a file if it doesn't and the last thing it does before reaching the checkpoint is saving this table to that file.
--
-- Checkpoint's License:
--
-- The MIT License (MIT)
--
-- Copyright (c) 2018 Lupus590
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to
-- deal in the Software without restriction, including without limitation the
-- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-- sell copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions: The above copyright
-- notice and this permission notice shall be included in all copies or
-- substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
-- IN THE SOFTWARE.
--
--
-- MBS's License:
--
-- The MIT License (MIT)
--
-- Copyright (c) 2017 SquidDev
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--
--]]
local function argChecker(position, value, validTypesList, level)
-- check our own args first, sadly we can't use ourself for this
if type(position) ~= "number" then
error("argChecker: arg[1] expected number got "..type(position),2)
end
-- value could be anything, it's what the caller wants us to check for them
if type(validTypesList) ~= "table" then
error("argChecker: arg[3] expected table got "..type(validTypesList),2)
end
if not validTypesList[1] then
error("argChecker: arg[3] table must contain at least one element",2)
end
for k, v in ipairs(validTypesList) do
if type(v) ~= "string" then
error("argChecker: arg[3]["..tostring(k).."] expected string got "..type(v),2)
end
end
if type(level) ~= "nil" and type(level) ~= "number" then
error("argChecker: arg[4] expected number or nil got "..type(level),2)
end
level = level and level + 1 or 3
-- check the client's stuff
for k, v in ipairs(validTypesList) do
if type(value) == v then
return
end
end
local expectedTypes
if #validTypesList == 1 then
expectedTypes = validTypesList[1]
else
expectedTypes = table.concat(validTypesList, ", ", 1, #validTypesList - 1) .. " or " .. validTypesList[#validTypesList]
end
error("arg["..tostring(position).."] expected "..expectedTypes
.." got "..type(value), level)
end
local checkpointFile = ".checkpoint"
local checkpoints = {}
local checkpointTrace = {}
local nextLabel
local useStackTracing = true -- sets default for the API, program can set at runtime with third arg to checkpoint.run
local intentionalError -- true if traceback function belives the error is intentional, false otherwise, nil if traceback has not be generated
-- MBS Stack Tracing
local function traceback(x)
-- Attempt to detect error() and error("xyz", 0).
-- This probably means they're erroring the program intentionally and so we
-- shouldn't display anything.
if x == nil or (type(x) == "string" and not x:find(":%d+:")) then
intentionalError = true
return x
end
intentionalError = false
if type(debug) == "table" and type(debug.traceback) == "function" then
return debug.traceback(tostring(x), 2)
else
local level = 3
local out = { tostring(x), "stack traceback:" }
while true do
local _, msg = pcall(error, "", level)
if msg == "" then
break
end
out[#out + 1] = " " .. msg
level = level + 1
end
return table.concat(out, "\n")
end
end
local function trimTraceback(target, marker)
local ttarget, tmarker = {}, {}
for line in target:gmatch("([^\n]*)\n?") do
ttarget[#ttarget + 1] = line
end
for line in marker:gmatch("([^\n]*)\n?") do
tmarker[#tmarker + 1] = line
end
local t_len, m_len = #ttarget, #tmarker
while t_len >= 3 and ttarget[t_len] == tmarker[m_len] do
table.remove(ttarget, t_len)
t_len, m_len = t_len - 1, m_len - 1
end
return ttarget
end
-- ENd of MBS Stack Tracing
function checkpoint.add(label, callback, ...)
argChecker(1, label, {"string"})
argChecker(2, callback, {"function"})
checkpoints[label] = {callback = callback, args = table.pack(...), }
end
function checkpoint.remove(label) -- this is intended for debugging, users can use it to make sure that their programs don't loop on itself when it's not meant to
argChecker(1, label, {"string"})
if not checkpoints[label] then
error("Bad arg[1], no known checkpoint with label "..tostring(label), 2)
end
checkpoints[label] = nil
end
function checkpoint.reach(label)
argChecker(1, label, {"string"})
if not checkpoints[label] then
error("Bad arg[1], no known checkpoint with label '"..tostring(label)
.."'. You may want to check spelling, scope and such.", 2)
end
local f = fs.open(checkpointFile,"w")
f.writeLine(label)
f.close()
nextLabel = label
end
function checkpoint.run(defaultLabel, fileName, stackTracing) -- returns whatever the last callback returns (xpcall stuff stripped if used)
argChecker(1, defaultLabel, {"string"})
argChecker(2, fileName, {"string", "nil"})
argChecker(3, stackTracing, {"boolean", "nil"})
if not checkpoints[defaultLabel] then
error("Bad arg[1], no known checkpoint with label "
..tostring(defaultLabel), 2)
end
if stackTracing ~= nil then
useStackTracing = stackTracing
end
checkpointFile = fileName or checkpointFile
nextLabel = defaultLabel
if fs.exists(checkpointFile) then
local f = fs.open(checkpointFile, "r")
nextLabel = f.readLine()
f.close()
if not checkpoints[nextLabel] then
error("Found checkpoint file '"..fileName.."' containing unknown label '"
..nextLabel.."'. Are your sure that this is the right file "
.."and that nothing is changing it?", 0)
end
end
local returnValues
while nextLabel ~= nil do
local l = nextLabel
checkpointTrace[#checkpointTrace+1] = nextLabel
nextLabel = nil
if useStackTracing then
-- The following line is horrible, but we need to capture the current traceback and run
-- the function on the same line.
intentionalError = nil
returnValues = table.pack(xpcall(function() return checkpoints[l].callback(table.unpack(checkpoints[l].args, 1, checkpoints[l].args.n)) end, traceback))
local ok = table.remove(returnValues, 1)
if not ok then
local trace = traceback("checkpoint.lua"..":1:")
local errorMessage = ""
if returnValues[1] ~= nil then
trace = trimTraceback(returnValues[1], trace)
local max, remaining = 15, 10
if #trace > max then
for i = #trace - max, 0, -1 do
table.remove(trace, remaining + i)
end
table.insert(trace, remaining, " ...")
end
errorMessage = table.concat(trace, "\n")
if intentionalError == false and errorMessage ~= "Terminated" then
errorMessage = errorMessage
.."\n\nCheckpoints ran in this instance:\n "
..table.concat(checkpointTrace, "\n ").." <- error occured in\n"
end
end
error(errorMessage, 0)
end -- if not ok
else
returnValues = table.pack(checkpoints[l].callback(table.unpack(checkpoints[l].args, 1, checkpoints[l].args.n)))
end
end
-- we have finished the program, delete the checkpointFile so that the program starts from the beginning if ran again
if fs.exists(checkpointFile) then
fs.delete(checkpointFile)
end
return table.unpack(returnValues, 1, returnValues.n)
end
end
local function progressivlyLongerWaitFor(callback, maxWaitTime)
if type(callback) ~= "function" then
error("bad arg[1], expected function got "..type(callback), 2)
end
if maxWaitTime ~= nil and type(maxWaitTime) ~= "number" then
error("bad arg[2], expected number or nil got "..type(maxWaitTime), 2)
end
maxWaitTime = maxWaitTime or math.huge
local sleepTime = 0
while not callback() do
sleepTime = math.min(sleepTime + math.floor(sleepTime/2) +1, maxWaitTime)
os.sleep(sleepTime)
end
end
local function waitForTree()
local function callback()
local _, blockData = turtle.inspect()
return blockData and (blockData.name == logs)
end
progressivlyLongerWaitFor(callback, maxWaitTime)
checkpoint.reach("climbTreeFirst")
end
checkpoint.add("waitForTree", waitForTree)
local function climbTree(chopWoodNext)
local _, blockData = turtle.inspect()
while blockData and blockData.name == logs and turtle.up() do
_, blockData = turtle.inspect()
end
while ((not blockData) or blockData.name ~= logs) and turtle.down() do
_, blockData = turtle.inspect()
end
if chopWoodNext then
checkpoint.reach("chopWood")
else
checkpoint.reach("clearLeaves")
end
end
checkpoint.add("climbTreeFirst", climbTree)
checkpoint.add("climbTreeSecond", climbTree, true)
-- TODO: remove the bounce after clearing the leaves
local function unsafeClearLeaves()
veinMine()
while movementStack.hasMovements() do -- TODO: remove the extra spinning
movementStack.pop()
veinMine()
end
end
local logMode = false
local function tryForwards()
while not turtle.forward() do
if turtle.getFuelLevel == 0 then
error("Out of fuel.", 0)
end
local _, blockData = turtle.inspect()
if blockData and blockData.name == leaves then
turtle.dig()
elseif blockData and blockData.name == logs then
if logMode then
error("Even LAMA is lost, delete the .lama folder and reset the turtle.", 0)
end
logMode = true
turtle.turnRight()
tryForwards()
turtle.turnLeft()
tryForwards()
tryForwards()
turtle.turnLeft()
tryForwards()
turtle.turnRight()
logMode = false
elseif blockData then
error("Unknown obstruction. LAMA could be lost, delete the .lama folder and reset the turtle if you belive that it is.", 0)
end
end
end
local function clearLeaves()
local ok, msg = pcall(unsafeClearLeaves)
if not ok then --msg == "Terminated" or msg == "Bad pop movement." or msg == "got lost"
error(msg, 0)
end
local x, y, z, f = lama.getPosition()
if x ~= 0 or y <0 or y > 10 or z ~= 0 then
-- east = +x
-- north = -z
while x > 0 do
while f ~= "west" do
turtle.turnRight()
x, y, z, f = lama.getPosition()
end
tryForwards()
x, y, z, f = lama.getPosition()
end
x, y, z, f = lama.getPosition()
while x < 0 do
while f ~= "east" do
turtle.turnRight()
x, y, z, f = lama.getPosition()
end
tryForwards()
x, y, z, f = lama.getPosition()
end
x, y, z, f = lama.getPosition()
while z < 0 do
while f ~= "south" do
turtle.turnRight()
x, y, z, f = lama.getPosition()
end
tryForwards()
x, y, z, f = lama.getPosition()
end
x, y, z, f = lama.getPosition()
while z > 0 do
while f ~= "north" do
turtle.turnRight()
x, y, z, f = lama.getPosition()
end
tryForwards()
x, y, z, f = lama.getPosition()
end
x, y, z, f = lama.getPosition()
while y > 0 do
while not turtle.down() do
if turtle.getFuelLevel == 0 then
error("Out of fuel.", 0)
end
local _, blockData = turtle.inspectDown()
if blockData and blockData.name == leaves then
turtle.digDown()
elseif blockData and blockData.name == logs then
error("Even LAMA is lost, delete the .lama folder and reset the turtle.", 0)
elseif blockData then
error("Unknown obstruction. LAMA could be lost, delete the .lama folder and reset the turtle if you belive that it is.", 0)
end
end
x, y, z, f = lama.getPosition()
end
if y ~= 0 then
error("Even LAMA is lost, delete the .lama folder and reset the turtle.", 0)
end
x, y, z, f = lama.getPosition()
while f ~= "north" do
turtle.turnRight()
x, y, z, f = lama.getPosition()
end
checkpoint.reach("climbTreeFirst")
return
end
checkpoint.reach("climbTreeSecond")
end
checkpoint.add("clearLeaves", clearLeaves)
local function chopWood()
climbTree(true)
local _, blockData = turtle.inspect()
while blockData and blockData.name == logs do
turtle.dig()
turtle.down()
_, blockData = turtle.inspect()
end
checkpoint.reach("plantSapling")
end
checkpoint.add("chopWood", chopWood)
local function plantSapling()
for i = 1, 16 do
turtle.select(i)
local item = turtle.getItemDetail()
if item and item.name == saplings then
turtle.place()
break
end
end
checkpoint.reach("refuelAndOffLoad")
end
checkpoint.add("plantSapling", plantSapling)
local function refuelAndOffLoad()
local function dump()
while turtle.getItemCount() > 0 do
if not turtle.dropDown() then
print("output full, sleeping")
progressivlyLongerWaitFor(turtle.dropDown, maxWaitTime)
end
end
end
local saplingSlot
for i = 1, 16 do
turtle.select(i)
local item = turtle.getItemDetail()
if item and item.name == saplings then
if saplingSlot then
turtle.transferTo(saplingSlot)
dump()
else
saplingSlot = i
end
elseif item and fuel[item.name] then
else
dump()
end
end
while turtle.getFuelLevel() < targetFuelLevel do
local _, block = turtle.inspect()
while block.name ~= chest and block.name ~= trappedChest do
turtle.turnLeft()
_, block = turtle.inspect()
end
for i = 1, 16 do
turtle.select(i)
local item = turtle.getItemDetail()
if item and fuel[item.name] then
while turtle.getFuelLevel() < targetFuelLevel and turtle.refuel(1) do end
end
item = turtle.getItemDetail()
if item and not (item.name == saplings or fuel[item.name]) then
dump()
end
end
local item = turtle.getItemDetail()
if not (item and fuel[item.name]) then
turtle.suck()
end
while turtle.getFuelLevel() < targetFuelLevel and turtle.refuel(1) do
local item = turtle.getItemDetail()
if item and not fuel[item.name] then
dump()
end
turtle.suck(turtle.getItemSpace())
end
item = turtle.getItemDetail()
if item and not fuel[item.name] then
dump()
end
if turtle.getFuelLevel() < targetFuelLevel then
sleep(maxWaitTime)
end
end
local _, block = turtle.inspect()
while block.name ~= logs and block.name ~= saplings do
turtle.turnRight()
_, block = turtle.inspect()
end
checkpoint.reach("waitForTree")
end
checkpoint.add("refuelAndOffLoad", refuelAndOffLoad)
checkpoint.run("plantSapling")
|
local class = require 'middleclass'
local Object = class.Object
local Voxel = require 'core/voxel/Voxel'
local UndefinedVoxel = require 'core/voxel/UndefinedVoxel'
local GlobalEventSource = require 'core/GlobalEventSource'
local VoxelDictionary = {
classes = {},
idToClass = nil
}
function VoxelDictionary.registerClass( voxelClass )
assert(Object.isSubclassOf(voxelClass, Voxel),
'Voxel classes must inherit the voxel base class.')
assert(not VoxelDictionary.idToClass,
'Voxel classes must be registered before assigning IDs to them.')
table.insert(VoxelDictionary.classes, voxelClass)
end
--- Work out correct IDs for registered voxel classes.
-- Must be called only *once* after all voxel classes have been registered.
function VoxelDictionary._assignIds()
assert(not VoxelDictionary.idToClass,
'Voxel class IDs have already been assigned.')
local idToClass = {}
idToClass[0] = UndefinedVoxel
-- For now, this will just be implemented super simple:
for i, v in ipairs(VoxelDictionary.classes) do
idToClass[i] = v
v.static.id = i
end
VoxelDictionary.idToClass = idToClass
end
function VoxelDictionary.getClassFromId( id )
local idToClass = VoxelDictionary.idToClass
assert(idToClass, 'VoxelDictionary.assignIds() was not called yet.')
local voxelClass = idToClass[id]
assert(voxelClass, 'No voxel class matches!')
return voxelClass
end
GlobalEventSource:addEventTarget('resources loaded', VoxelDictionary, function()
VoxelDictionary._assignIds()
end)
return VoxelDictionary
|
local fireBug = Action()
function fireBug.onUse(player, item, fromPosition, target, toPosition, isHotkey)
local chance = math.random(10)
if chance > 4 then -- Success 6% chance
if target.itemid == 182 then -- Destroy spider webs/North - South
toPosition:sendMagicEffect(CONST_ME_HITBYFIRE)
target:transform(188)
target:decay()
elseif target.itemid == 183 then -- Destroy spider webs/East - West
toPosition:sendMagicEffect(CONST_ME_HITBYFIRE)
target:transform(189)
target:decay()
elseif target.itemid == 5465 then -- Burn Sugar Cane
toPosition:sendMagicEffect(CONST_ME_FIREAREA)
target:transform(5464)
target:decay()
elseif target.itemid == 2114 then -- Light up empty coal basins
toPosition:sendMagicEffect(CONST_ME_HITBYFIRE)
target:transform(2113)
end
elseif chance == 2 then -- It removes the firebug 1% chance
item:remove(1)
toPosition:sendMagicEffect(CONST_ME_POFF)
elseif chance == 1 then -- It explodes on the user 1% chance
doTargetCombatHealth(0, player, COMBAT_FIREDAMAGE, -5, -5, CONST_ME_HITBYFIRE)
player:say('OUCH!', TALKTYPE_MONSTER_SAY)
item:remove(1)
else
toPosition:sendMagicEffect(CONST_ME_POFF) -- It fails, but don't get removed 3% chance
end
return true
end
fireBug:id(5467)
fireBug:register()
|
function onCreate() --omg roblox (real)
makeLuaSprite('stageback', 'stageback', -600, -300);
setLuaSpriteScrollFactor('stageback', 0.9, 0.9);
makeLuaSprite('stagefront', 'stagefront', -650, 600);
setLuaSpriteScrollFactor('stagefront', 0.9, 0.9);
scaleObject('stagefront', 1.1, 1.1);
makeLuaSprite('stagecurtains', 'stagecurtains', -500, -300);
setLuaSpriteScrollFactor('stagecurtains', 1.3, 1.3);
scaleObject('stagecurtains', 0.9, 0.9);
addLuaSprite('stageback', false);
addLuaSprite('stagefront', false);
addLuaSprite('stagecurtains', false);
close(true);
end
|
--------------------------------------------------------------------------
-- This class is responsible for actively managing the actions of
-- Lmod. It is responsible finding and loading or unloading a
-- modulefile. It is also responsible for reloading modules when
-- the module path changes. Finally it is responsible for finding
-- modulefiles for "avail"
--
-- @classmod Master
require("strict")
--------------------------------------------------------------------------
-- Lmod License
--------------------------------------------------------------------------
--
-- Lmod is licensed under the terms of the MIT license reproduced below.
-- This means that Lmod is free software and can be used for both academic
-- and commercial purposes at absolutely no cost.
--
-- ----------------------------------------------------------------------
--
-- Copyright (C) 2008-2014 Robert McLay
--
-- Permission is hereby granted, free of charge, to any person obtaining
-- a copy of this software and associated documentation files (the
-- "Software"), to deal in the Software without restriction, including
-- without limitation the rights to use, copy, modify, merge, publish,
-- distribute, sublicense, and/or sell copies of the Software, and to
-- permit persons to whom the Software is furnished to do so, subject
-- to the following conditions:
--
-- The above copyright notice and this permission notice shall be
-- included in all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
-- BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
--
--------------------------------------------------------------------------
local concatTbl = table.concat
local getenv = os.getenv
local sort = table.sort
local systemG = _G
local removeEntry = table.remove
require("TermWidth")
require("fileOps")
require("string_utils")
require("loadModuleFile")
require("utils")
local BeautifulTbl = require('BeautifulTbl')
local ColumnTable = require('ColumnTable')
local Default = '(D)'
local M = {}
local MName = require("MName")
local ModuleStack = require("ModuleStack")
local Optiks = require("Optiks")
local Spider = require("Spider")
local Var = require("Var")
local dbg = require("Dbg"):dbg()
local hook = require("Hook")
local lfs = require("lfs")
local posix = require("posix")
local pack = (_VERSION == "Lua 5.1") and argsPack or table.pack
local load = (_VERSION == "Lua 5.1") and loadstring or load
------------------------------------------------------------------------
-- a private ctor that is used to construct a singleton.
s_master = {}
local function new(self,safe)
local o = {}
setmetatable(o,self)
self.__index = self
o.safe = safe
return o
end
local searchTbl = {'.lua', '', '/default', '/.version'}
local numSearch = 4
local numSrchLatest = 2
--------------------------------------------------------------------------
-- This local function is used to find a default file
-- that maybe in symbolic link chain. This returns
-- the absolute path.
-- @param path A directory path
local function followDefault(path)
if (path == nil) then return nil end
dbg.start{"followDefault(path=\"",path,"\")"}
local attr = lfs.symlinkattributes(path)
local result = path
if (attr == nil) then
result = nil
elseif (attr.mode == "link") then
local rl = posix.readlink(path)
local a = {}
local n = 0
for s in path:split("/") do
n = n + 1
a[n] = s or ""
end
a[n] = ""
local i = n
for s in rl:split("/") do
if (s == "..") then
i = i - 1
else
a[i] = s
i = i + 1
end
end
result = concatTbl(a,"/")
end
dbg.print{"result: ",result,"\n"}
dbg.fini("followDefault")
return result
end
--------------------------------------------------------------------------
-- This local function is very similar to
-- [[find_module_file]]. The idea is that
-- an advanced user wants to inherit a compiler
-- module and/or an mpi stack module. They want
-- to inherit the system compiler but add to the
-- MODULEPATH. This routine does a similar search
-- for the module. It searches for the original
-- module in pathA and then searches again. Only
-- after finding the same named module does it
-- return.
local function find_inherit_module(fullModuleName, oldFn)
dbg.start{"find_inherit_module(",fullModuleName,",",oldFn, ")"}
local t = {fn = nil, modFullName = nil, modName = nil, default = 0}
local mt = systemG.MT:mt()
local mname = MName:new("load", fullModuleName)
local sn = mname:sn()
local localDir = true
local pathA = mt:locationTbl(sn)
if (pathA == nil or #pathA == 0) then
dbg.fini("find_inherit_module")
return t
end
local fn, result, rstripped
local foundOld = false
local oldFn_stripped = oldFn:gsub("%.lua$","")
for ii, vv in ipairs(pathA) do
local mpath = vv.mpath
fn = pathJoin(vv.file, mname:version())
result = nil
dbg.print{"ii: ",ii," mpath: ",mpath," vv.file: ",vv.file," fn: ",fn,"\n"}
for i = 1, #searchTbl do
local f = fn .. searchTbl[i]
local attr = lfs.attributes(f)
local readable = posix.access(f,"r")
dbg.print{'(1) fn: ',fn," f: ",f,"\n"}
if (readable and attr and attr.mode == "file") then
result = f
rstripped = result:gsub("%.lua$","")
break
end
end
dbg.print{"(2) result: ", result, " foundOld: ", foundOld,"\n"}
if (foundOld) then
break
end
if (result and rstripped == oldFn_stripped) then
foundOld = true
result = nil
end
dbg.print{"(3) result: ", result, " foundOld: ", foundOld,"\n"}
end
dbg.print{"fullModuleName: ",fullModuleName, " fn: ", result,"\n"}
t.modFullName = fullModuleName
t.fn = result
dbg.fini("find_inherit_module")
return t
end
--------------------------------------------------------------------------
-- This function marks a module name as loaded and saves
-- it to LOADEDMODULES and _LMFILES_. This is only for
-- compatibility with TCL/C module.
local function registerLoaded(full, fn)
local modList = "LOADEDMODULES"
local modFn = "_LMFILES_"
local nodups = true
local priority = 0
local sep = ":"
if (varTbl[modList] == nil) then
varTbl[modList] = Var:new(modList, nil, sep)
end
varTbl[modList]:append(full, nodups, priority)
if (varTbl[modFn] == nil) then
varTbl[modFn] = Var:new(modFn, nil, sep)
end
varTbl[modFn]:append(fn, nodups, priority)
end
--------------------------------------------------------------------------
-- This function marks a module name as unloaded and
-- saves it to LOADEDMODULES and _LMFILES_. This is
-- only for compatibility with TCL/C module.
local function registerUnloaded(full, fn)
local modList = "LOADEDMODULES"
local modFn = "_LMFILES_"
local where = "all"
local sep = ":"
local priority = 0
if (varTbl[modList] == nil) then
varTbl[modList] = Var:new(modList, nil, sep)
end
varTbl[modList]:remove(full, where, priority)
if (varTbl[modFn] == nil) then
varTbl[modFn] = Var:new(modFn, nil, sep)
end
varTbl[modFn]:remove(fn, where, priority)
end
--------------------------------------------------------------------------
-- Singleton Ctor.
-- @param self A Master object.
-- @param safe A flag.
function M.master(self, safe)
dbg.start{"Master:master(safe: ",safe,")"}
if (next(s_master) == nil) then
MT = systemG.MT
s_master = new(self, safe)
end
dbg.fini("Master:master")
return s_master
end
--------------------------------------------------------------------------
-- This local function returns the name of the
-- filename and the full name of the module file.
-- If the user gives the short name and it is
-- loaded then that version is used not the default
-- module file for the one named. Otherwise
-- find_module_file is used.
-- @param mname A MName object
local function access_find_module_file(mname)
local mt = MT:mt()
local sn = mname:sn()
if (sn == mname:usrName() and mt:have(sn,"any")) then
local full = mt:fullName(sn)
return mt:fileName(sn), full or ""
end
local t = mname:find()
local full = t.modFullName or ""
local fn = t.fn
return fn, full
end
--------------------------------------------------------------------------
-- This member function is engine that runs the user
-- commands "help", "whatis" and "show". In each case
-- mcp is set to MC_Access, MC_Access and MC_Show,
-- respectively. Using that value of mcp, the
-- modulefile is found and evaluated by loadModuleFile.
-- This causes the help, or whatis or showing the
-- modulefile as the user requested.
-- @param self A Master object.
function M.access(self, ...)
local masterTbl = masterTbl()
local shell = s_master.shell
local mt = MT:mt()
local mStack = ModuleStack:moduleStack()
local prtHdr = systemG.prtHdr
local a = {}
local shellN = s_master.shell:name()
local help = (systemG.help ~= dbg.quiet) and "-h" or nil
local result, t
local A = ShowResultsA
local arg = pack(...)
for i = 1, arg.n do
local moduleName = arg[i]
local mname = MName:new("load", moduleName)
local fn, full = access_find_module_file(mname)
systemG.ModuleFn = fn
systemG.ModuleName = full
if (fn and isFile(fn)) then
A[#A+1] = prtHdr()
dbg.print{"RTM(2) #A:",#A,"\n"}
if (masterTbl.rawDisplay) then
local f = io.open(fn, "r")
local whole = f:read("*all")
f:close()
A[#A+1] = whole
else
mStack:push(full, moduleName, mname:sn(), fn)
local mList = concatTbl(mt:list("both","active"),":")
loadModuleFile{file=fn,help=help, shell=shellN, mList = mList,
reportErr=true}
mStack:pop()
A[#A+1] = "\n"
dbg.print{"RTM(3) #A:",#A,"\n"}
end
else
a[#a+1] = moduleName
end
end
shell:echo(concatTbl(A,""))
if (#a > 0) then
setWarningFlag()
io.stderr:write("Failed to find the following module(s): \"",
concatTbl(a,"\", \""),"\" in your MODULEPATH\n")
io.stderr:write("Try: \n",
" \"module spider ", concatTbl(a," "), "\"\n",
"\nto see if the module(s) are available across all ",
"compilers and MPI implementations.\n")
end
end
--------------------------------------------------------------------------
-- Load the module that has the same name as the
-- one on the top of mStack. This way a user
-- can "inherit" the contents of a system module
-- instead of copying.
function M.inheritModule()
dbg.start{"Master:inherit()"}
local mt = MT:mt()
local shellN = s_master.shell:name()
local mStack = ModuleStack:moduleStack()
local myFn = mStack:fileName()
local myUsrN = mStack:usrName()
local sn = mStack:sn()
local mFull = mStack:fullName()
dbg.print{"myFn: ", myFn,"\n"}
dbg.print{"mFull: ", mFull,"\n"}
local fnI
if (mode() == "unload") then
dbg.print{"here before pop\n"}
fnI = mt:popInheritFn(sn)
dbg.print{"fnI: ",fnI,"\n"}
else
local t = find_inherit_module(mFull,myFn)
fnI = t.fn
end
dbg.print{"fn: ", fnI,"\n"}
if (fnI == nil) then
LmodError("Failed to inherit: ",mFull,"\n")
else
local mList = concatTbl(mt:list("both","active"),":")
mStack:push(mFull, myUsrN, sn, fnI)
loadModuleFile{file=fnI,mList = mList, shell=shellN,
reportErr=true}
mStack:pop()
end
if (mode() == "load") then
mt:pushInheritFn(sn,fnI)
end
dbg.fini("Master:inherit")
end
--------------------------------------------------------------------------
-- Load all requested modules. Each module is unloaded
-- if it is currently loaded.
-- @param mA An array of MName objects.
-- @return An array of true/false values indicating success or not.
function M.load(mA)
local mStack = ModuleStack:moduleStack()
local shellN = s_master.shell:name()
local mt = MT:mt()
local a = {}
dbg.start{"Master:load(mA)"}
a = {}
for i = 1,#mA do
local mname = mA[i]
local moduleName = mname:usrName()
local sn = mname:sn()
local loaded = false
local t = mname:find()
local fn = t.fn
dbg.print{"Master:load: i: ",i,", sn: ", sn, ", fn: ", t.fn,"\n"}
if (mt:have(sn,"active")) then
dbg.print{"Master:load reload module: \"",moduleName,
"\" as it is already loaded\n"}
local mcp_old = mcp
mcp = MCP
dbg.print{"Setting mcp to ", mcp:name(),"\n"}
local ma = {}
ma[1] = mA[i]
mcp:unload(ma)
local aa = mcp:load(ma)
mcp = mcp_old
dbg.print{"Setting mcp to ", mcp:name(),"\n"}
loaded = aa[1]
elseif (fn) then
dbg.print{"Master:loading: \"",moduleName,"\" from f: \"",fn,"\"\n"}
local mList = concatTbl(mt:list("both","active"),":")
mt:add(t, "pending")
mt:beginOP()
mStack:push(t.modFullName, moduleName, sn, fn)
loadModuleFile{file=fn, shell = shellN, mList = mList, reportErr=true}
mt:setStatus(sn, "active")
hook.apply("load",t)
mStack:pop()
mt:endOP()
dbg.print{"Making ", t.modName, " active\n"}
registerLoaded(t.modFullName, fn)
dbg.print{"Marked: ",t.modFullName," as loaded\n"}
loaded = true
end
a[#a+1] = loaded
if (not mcp.familyStackEmpty()) then
local b = {}
while (not mcp.familyStackEmpty()) do
local b_old, b_new = mcp.familyStackPop()
LmodMessage("\nLmod is automatically replacing \"", b_old.fullName,
"\" with \"", b_new.fullName, "\"\n" )
local umA = {MName:new("mt", b_old.sn) , MName:new("mt", b_new.sn) }
local lmA = {MName:new("load", b_new.usrName)}
b[#b+1] = {umA = umA, lmA = lmA}
end
for i = 1,#b do
mcp:unload_usr(b[i].umA)
mcp:load(b[i].lmA)
end
end
end
if (M.safeToUpdate() and mt:safeToCheckZombies() and mStack:empty()) then
dbg.print{"Master:load calling reloadAll()\n"}
M.reloadAll()
end
dbg.fini("Master:load")
return a
end
--------------------------------------------------------------------------
-- Loop over all active modules and reload each one.
-- Since only the "shell" functions are active and all
-- other Lmod functions are inactive because mcp is now
-- MC_Refresh, there is no need to unload and reload the
-- modulefiles. Just call loadModuleFile() to redefine
-- the aliases/shell functions in a subshell.
function M.refresh()
local mStack = ModuleStack:moduleStack()
local mt = MT:mt()
local shellN = s_master.shell:name()
local mcp_old = mcp
mcp = MasterControl.build("refresh","load")
dbg.start{"Master:refresh()"}
local activeA = mt:list("short","active")
for i = 1,#activeA do
local sn = activeA[i]
local fn = mt:fileName(sn)
local usrName = mt:usrName(sn)
local full = mt:fullName(sn)
local mList = concatTbl(mt:list("both","active"),":")
if (isFile(fn)) then
mStack:push(full, usrName, sn, fn)
dbg.print{"loading: ",sn," fn: ", fn,"\n"}
loadModuleFile{file = fn, shell = shellN, mList = mList,
reportErr=true}
mStack:pop()
end
end
mcp = mcp_old
dbg.print{"Setting mcp to : ",mcp:name(),"\n"}
dbg.fini("Master:refresh")
end
--------------------------------------------------------------------------
-- Loop over all modules in MT to see if they still
-- can be seen. We check every active module to see
-- if the file associated with loaded module is the
-- same as [[find_module_file()]] reports. If not
-- then it is unloaded and an attempt is made to reload
-- it. Each inactive module is re-loaded if possible.
function M.reloadAll()
local mt = MT:mt()
dbg.start{"Master:reloadAll()"}
local mcp_old = mcp
mcp = MCP
dbg.print{"Setting mcp to ", mcp:name(),"\n"}
local same = true
local a = mt:list("userName","any")
for i = 1, #a do
local v = a[i]
local sn = v.sn
if (mt:have(sn, "active")) then
dbg.print{"module sn: ",sn," is active\n"}
dbg.print{"userName: ",v.name,"\n"}
local mname = MName:new("userName", v.name)
local t = mname:find()
local fn = mt:fileName(sn)
local fullName = t.modFullName
local userName = v.name
if (t.fn ~= fn) then
dbg.print{"Master:reloadAll t.fn: \"",t.fn or "nil","\"",
" mt:fileName(sn): \"",fn or "nil","\"\n"}
dbg.print{"Master:reloadAll Unloading module: \"",sn,"\"\n"}
local ma = {}
ma[1] = mname
mcp:unload(ma)
dbg.print{"Master:reloadAll Loading module: \"",userName or "nil","\"\n"}
local loadA = mcp:load(ma)
dbg.print{"Master:reloadAll: fn: \"",fn or "nil",
"\" mt:fileName(sn): \"", tostring(mt:fileName(sn)), "\"\n"}
if (loadA[1] and fn ~= mt:fileName(sn)) then
same = false
dbg.print{"Master:reloadAll module: ",fullName," marked as reloaded\n"}
end
end
else
dbg.print{"module sn: ", sn, " is inactive\n"}
local fn = mt:fileName(sn)
local name = v.name -- This name is short for default and
-- Full for specific version.
dbg.print{"Master:reloadAll Loading module: \"", name, "\"\n"}
local ma = {}
ma[1] = MName:new("load",name)
local aa = mcp:load(ma)
if (aa[1] and fn ~= mt:fileName(sn)) then
dbg.print{"Master:reloadAll module: ", name, " marked as reloaded\n"}
end
same = not aa[1]
end
end
for i = 1, #a do
local v = a[i]
local sn = v.sn
if (not mt:have(sn, "active")) then
local t = { modFullName = v.full, modName = sn, default = v.defaultFlg}
dbg.print{"Master:reloadAll module: ", sn, " marked as inactive\n"}
mt:add(t, "inactive")
end
end
mcp = mcp_old
dbg.print{"Setting mpc to ", mcp:name(),"\n"}
dbg.fini("Master:reloadAll")
return same
end
--------------------------------------------------------------------------
-- *safe* is set during ctor. It is controlled by the command table in lmod.
-- @return the internal safe flag.
function M.safeToUpdate()
return s_master.safe
end
--------------------------------------------------------------------------
-- Unload modulefile(s) via the module names.
-- @param mA An array of MName objects.
-- @return An array of true/false values indicating success or not.
function M.unload(mA)
local mStack = ModuleStack:moduleStack()
local mt = MT:mt()
local a = {}
local shellN = s_master.shell:name()
dbg.start{"Master:unload(mA)"}
local mcp_old = mcp
mcp = MasterControl.build("unload")
dbg.print{"Setting mcp to ", mcp:name(),"\n"}
for i = 1, #mA do
local mname = mA[i]
local moduleName = mname:usrName()
local sn = mname:sn()
dbg.print{"Trying to unload: ", moduleName, " sn: ", sn,"\n"}
if (mt:have(sn,"inactive")) then
dbg.print{"Removing inactive module: ", moduleName, "\n"}
mt:remove(sn)
registerUnloaded(mt:fullName(sn), mt:fileName(sn))
a[#a + 1] = true
elseif (mt:have(sn,"active")) then
dbg.print{"Mark ", moduleName, " as pending\n"}
mt:setStatus(sn,"pending")
local mList = concatTbl(mt:list("both","active"),":")
local f = mt:fileName(sn)
local fullModuleName = mt:fullName(sn)
local isSticky = mt:haveProperty(sn, "lmod", "sticky")
if (isSticky) then
mt:addStickyA(sn)
dbg.print{"sn: ", sn, " Sticky: ",isSticky,"\n"}
end
dbg.print{"Master:unload: \"",fullModuleName,"\" from f: ",f,"\n"}
mt:beginOP()
dbg.print{"changePATH: ", mt._changePATHCount, "\n"}
mStack:push(fullModuleName, moduleName, sn, f)
loadModuleFile{file=f, mList=mList, shell=shellN, reportErr=false}
mStack:pop()
mt:endOP()
dbg.print{"changePATH: ", mt._changePATHCount, "\n"}
dbg.print{"calling mt:remove(\"",sn,"\")\n"}
local t = {fn = mt:fileName(sn), modFullName = mt:fullName(sn) }
mt:remove(sn)
registerUnloaded(fullModuleName, f)
hook.apply("unload",t)
a[#a + 1] = true
else
a[#a + 1] = false
end
end
dbg.print{"changePATH: ", mt._changePATHCount, " Zombie state: ",mt:zombieState(),
" mStack:empty(): ",mStack:empty(),"\n"}
if (M.safeToUpdate() and mt:safeToCheckZombies() and mStack:empty()) then
dbg.print{"In unload calling Master.reload\n"}
M.reloadAll()
dbg.print{"changePATH: ", mt._changePATHCount, " Zombie state: ",mt:zombieState(),
" mStack:empty(): ",mStack:empty(),"\n"}
end
mcp = mcp_old
dbg.print{"Setting mcp to ", mcp:name(),"\n"}
dbg.fini("Master:unload")
return a
end
--------------------------------------------------------------------------
-- Once the purge or unload happens, the sticky modules are reloaded.
-- @param self A Master object
-- @param force If true then don't reload.
function M.reload_sticky(self, force)
dbg.start{"Master:reload_sticky()"}
-- Try to reload any sticky modules.
if (masterTbl().force or force) then
dbg.fini("Master:reload_sticky")
return
end
local mt = MT:mt()
local stuckA = {}
local unstuckA = {}
local stickyA = mt:getStickyA()
local mcp_old = mcp
mcp = MCP
local reload = false
for i = 1, #stickyA do
local entry = stickyA[i]
local mname = MName:new("entryT",entry)
local t = mname:find()
if (t.fn == entry.FN) then
local ma = {}
ma[1] = mname
mcp:load(ma)
end
local sn = mname:sn()
if (not mt:have(sn,"active")) then
local j = #unstuckA+1
unstuckA[j] = { string.format("%3d)",j) , mname:usrName() }
else
reload = true
end
end
mcp = mcp_old
if (reload) then
io.stderr:write("\nThe following modules were not unloaded:\n")
io.stderr:write(" (Use \"module --force purge\" to unload all):\n\n")
local b = mt:list("fullName","active")
local a = {}
for i = 1, #b do
a[#a+1] = {" " .. tostring(i) .. ")", b[i] }
end
local ct = ColumnTable:new{tbl=a, gap=0}
io.stderr:write(ct:build_tbl(),"\n")
end
if (#unstuckA > 0) then
io.stderr:write("\nThe following sticky modules could not be reloaded:\n")
local ct = ColumnTable:new{tbl=unstuckA, gap=0}
io.stderr:write(ct:build_tbl(),"\n")
end
dbg.fini("Master:reload_sticky")
end
--------------------------------------------------------------------------
-- All these routines from here to the end are part of "avail"
--------------------------------------------------------------------------
--------------------------------------------------------------------------
-- Find the default module for the current directory *mpath*.
-- @param mpath A single directory that is part of MODULEPATH
-- @param sn The short name.
-- @param versionA An array of versions for *sn*.
-- @return A table describing the default.
local function findDefault(mpath, sn, versionA)
dbg.start{"Master.findDefault(mpath=\"",mpath,"\", "," sn=\"",sn,"\")"}
local mt = MT:mt()
local t = {}
local marked = false
local localDir = true
local path = abspath(pathJoin(mpath,sn))
local default = abspath_localdir(pathJoin(path, "default"))
if (not isFile(default)) then
marked = true
else
local dfltA = {"/.modulerc", "/.version" }
local vf = false
for i = 1, #dfltA do
local n = dfltA[i]
local vFn = pathJoin(path,n)
if (isFile(vFn)) then
vf = versionFile(n, sn, vFn)
break;
end
end
if (vf) then
marked = true
default = pathJoin(path,vf)
--dbg.print{"(1) f: ",f," default: ", default, "\n"}
if (default == nil) then
local fn = vf .. ".lua"
default = pathJoin(path,fn)
dbg.print{"(2) f: ",f," default: ", default, "\n"}
end
--dbg.print{"(3) default: ", default, "\n"}
end
end
if (not default) then
local d, bn = splitFileName(versionA[#versionA].file)
default = pathjoin(abspath(d), bn)
end
dbg.print{"default: ", default,"\n"}
t.default = default
t.marked = marked
t.numVersions = #versionA
dbg.fini("Master.findDefault")
return t
end
--------------------------------------------------------------------------
-- This routine is handed a single entry. It check to see
-- if matches the search criteria. It also adds any
-- properties such as default or anything from [[propT]].
-- @param defaultOnly
-- @param terse
-- @param label
-- @param szA
-- @param searchA
-- @param sn
-- @param name
-- @param f
-- @param defaultModuleT
-- @param dbT
-- @param legendT
-- @param a
local function availEntry(defaultOnly, terse, label, szA, searchA, sn, name,
f, defaultModuleT, dbT, legendT, a)
dbg.start{"Master:availEntry(defaultOnly, terse, label, szA, searchA, "..
"sn, name, f, defaultModuleT, dbT, legendT, a)"}
dbg.print{"sn:" ,sn, ", name: ", name,", defaultOnly: ",defaultOnly,
", szA: ",szA,"\n"}
local dflt = ""
local sCount = #searchA
local found = false
local localdir = true
local hidden = not masterTbl().show_hidden
local mt = MT:mt()
if (sCount == 0) then
found = true
else
for i = 1, sCount do
local s = searchA[i]
if (name:find(s) or sn:find(s)) then
found = true
break
end
if (LMOD_MPATH_AVAIL ~= "no" and label:find(s)) then
found = true
break
end
end
end
local f_orig = f
local d, bn = splitFileName(f)
local d2 = abspath(d)
f = pathJoin(d2,bn)
local fabs = abspath_localdir(f)
dbg.print{"defaultOnly: ",defaultOnly, ", defaultModuleT.fn: ",defaultModuleT.fn,
", f_orig: ",f_orig,", f: ", f,", d: ", d,", d2: ", d2, ", fabs: ",fabs,"\n"}
local isDefault = (defaultModuleT.fn == f_orig or defaultModuleT.fn == fabs)
dbg.print{"isDefault: ",isDefault, "\n"}
--if (defaultOnly and defaultModuleT.fn ~= abspath(f, localdir)) then
if (defaultOnly and not isDefault ) then
found = false
end
if (not found) then
dbg.print{"Not found\n"}
dbg.fini("Master:availEntry")
return
end
local mname = MName:new("load", name)
local version = mname:version() or ""
if (hidden and version:sub(1,1) == "." or sn:sub(1,1) == ".") then
dbg.print{"Not printing a dot modulefile\n"}
dbg.fini("Master:availEntry")
return
end
if (terse) then
-- Print out directory (e.g. gcc) for tab-completion
-- But only print it out when reporting defaultOnly.
if (sn == name and szA > 0) then
if (not defaultOnly) then
a[#a+1] = name .. "/"
end
else
a[#a+1] = name
end
else
dbg.print{"defaultModuleT.fn: ",defaultModuleT.fn,
", kind: ", defaultModuleT.kind,
", num: ", defaultModuleT.num > 1,
", f_orig: ", f_orig,
", f: ",f,
"\n"}
--if ((defaultModuleT.fn == abspath(f, localdir)) and
if ((isDefault) and (defaultModuleT.num > 1) and not defaultOnly ) then
dflt = Default
legendT[Default] = "Default Module"
end
dbg.print{"dflt: ",dflt,"\n"}
local aa = {}
local propT = {}
local sn = mname:sn()
local entry = dbT[sn]
if (entry) then
dbg.print{"Found dbT[sn]\n"}
if (entry[f_orig]) then
propT = entry[f_orig].propT or {}
end
else
dbg.print{"Did not find dbT[sn]\n"}
end
local resultA = colorizePropA("short", name, propT, legendT)
aa[#aa + 1] = ' '
for i = 1,#resultA do
aa[#aa+1] = resultA[i]
end
aa[#aa + 1] = dflt
a[#a + 1] = aa
end
dbg.fini("Master:availEntry")
end
---------------------------------------------------------------------------
-- Handle a single directory and collect any entries through *availEntry*
-- @param defaultOnly
-- @param terse
-- @param searchA
-- @param label
-- @param locationT
-- @param availT
-- @param dbT
-- @param a
-- @param legendT
local function availDir(defaultOnly, terse, searchA, label, locationT, availT,
dbT, a, legendT)
dbg.start{"Master.availDir(defaultOnly= ",defaultOnly,", terse= ",terse,
", searchA=(",concatTbl(searchA,", "), "), label= \"",label,"\", ",
",locationT, availT, dbT, a, legendT)"}
if (availT == nil) then
dbg.print{"(1) Skipping non-existant directory: ", label,"\n"}
dbg.fini("Master.availDir")
return
end
local cmp = (LMOD_CASE_INDEPENDENT_SORTING:lower():sub(1,1) == "y") and
case_independent_cmp or nil
for sn, versionA in pairsByKeys(availT,cmp) do
dbg.print{"sn: ",sn,"\n"}
local defaultModuleT = locationT[sn].default
local aa = {}
local szA = versionA.total - versionA.hidden
if (szA == 0 and versionA.hidden == 0) then
local fn = versionA[0].fn
dbg.print{"fn: ",fn,"\n"}
availEntry(defaultOnly, terse, label, szA, searchA, sn, sn, fn,
defaultModuleT, dbT, legendT, a)
else
if (terse and szA > 0) then
-- Print out directory (e.g. gcc) for tab-completion
availEntry(defaultOnly, terse, label, szA, searchA, sn, sn, "",
defaultModuleT, dbT, legendT, a)
end
for i = 1, #versionA do
local name = pathJoin(sn, versionA[i].version)
local f = versionA[i].fn
availEntry(defaultOnly, terse, label, szA, searchA, sn, name,
f, defaultModuleT, dbT, legendT, a)
end
end
end
dbg.fini("Master.availDir")
end
--------------------------------------------------------------------------
-- "module avail " takes options that are given here.
-- Note that these are also available with the Lmod
-- options. So "module -t avail" and "module avail -t" are
-- the same thing.
-- @param argA
local function availOptions(argA)
local usage = "Usage: module avail [options] search1 search2 ..."
local cmdlineParser = Optiks:new{usage=usage, version=""}
argA[0] = "avail"
cmdlineParser:add_option{
name = {'-t', '--terse'},
dest = 'terse',
action = 'store_true',
}
cmdlineParser:add_option{
name = {'-d','--default'},
dest = 'defaultOnly',
action = 'store_true',
}
local optionTbl, pargs = cmdlineParser:parse(argA)
return optionTbl, pargs
end
--------------------------------------------------------------------------
--
-- @param availStyle
-- @param mpathA
-- @param availT
local function regroup_avail_blocks(availStyle, mpathA, availT)
--------------------------------------------------------------------------
-- call hook to see if site wants to relabel and re-organize avail layout
if (availStyle == "system") then
return mpathA, availT
end
local labelT = {}
for i = 1, #mpathA do
local mpath = mpathA[i]
if ( availT[mpath] ~= nil) then
labelT[mpath] = mpath
end
end
hook.apply("avail",labelT)
local label2mpathT = {}
for i = 1, #mpathA do
local mpath = mpathA[i]
if ( availT[mpath] ~= nil) then
local label = labelT[mpath]
local a = label2mpathT[label] or {}
a[#a+1] = i
label2mpathT[label] = a
end
end
if (dbg.active()) then
for label, vA in pairs(label2mpathT) do
dbg.print{"label: ",label,":",}
for i = 1, #vA do
io.stderr:write(" ",tostring(vA[i]))
end
io.stderr:write("\n")
end
end
local orderA = {}
for label, vA in pairs(label2mpathT) do
orderA[#orderA + 1] = {vA[1], label}
end
sort(orderA, function(a,b) return a[1] < b[1] end )
if (dbg.active()) then
for j = 1, #orderA do
dbg.print{j,", orderA: idx: ",orderA[j][1],", label: ",orderA[j][2],"\n"}
end
end
local availNT = {}
local labelA = {}
for j = 1, #orderA do
local label = orderA[j][2]
local a = label2mpathT[label]
labelA[j] = label
availNT[label] = {}
for i = 1, #a do
local mpath = mpathA[a[i]]
for k,v in pairs(availT[mpath]) do
if (availNT[label][k] == nil) then
availNT[label][k] = v
else
local vA = availNT[label][k]
for iv = 1,#v do
vA[#vA+1] = v[iv]
end
sort(vA, function(a,b) return a.parseV < b.parseV end)
end
end
end
end
return labelA, availNT
end
--------------------------------------------------------------------------
-- Report the available modules with properties and
-- defaults. Run results through pager.
-- @param argA User requested search terms.
function M.avail(argA)
dbg.start{"Master.avail(",concatTbl(argA,", "),")"}
local mt = MT:mt()
local shell = s_master.shell
local mpathA = mt:module_pathA()
local twidth = TermWidth()
local masterTbl = masterTbl()
local optionTbl, searchA = availOptions(argA)
if (not masterTbl.regexp) then
for i = 1, #searchA do
searchA[i] = searchA[i]:caseIndependent()
end
end
local defaultOnly = optionTbl.defaultOnly or masterTbl.defaultOnly
local terse = optionTbl.terse or masterTbl.terse
local legendT = {}
local dbT = {}
if (terse) then
dbg.print{"doing --terse\n"}
local availT = mt:availT()
local locationT = mt:locationTbl()
for ii = 1, #mpathA do
local mpath = mpathA[ii]
local a = {}
availDir(defaultOnly, terse, searchA, mpath, locationT, availT[mpath], dbT, a, legendT)
if (next(a)) then
io.stderr:write(mpath,":\n")
for i=1,#a do
io.stderr:write(a[i],"\n")
end
end
end
dbg.fini("Master:avail")
return
end
local cache = Cache:cache{quiet = masterTbl.terse}
local moduleT = cache:build()
local baseMpath = mt:getBaseMPATH()
if (not terse and (baseMpath == nil or baseMpath == '' or next(moduleT) == nil)) then
LmodError("avail is not possible, MODULEPATH is not set or not set with valid paths.\n")
end
local spider = Spider:new()
spider:buildSpiderDB({"default"}, moduleT, dbT)
local labelA = false
local availT = mt:availT()
local locationT = mt:locationTbl()
local availStyle = masterTbl.availStyle
--------------------------------------------------------------------------
-- call hook to see if site wants to relabel and re-organize avail layout
labelA, availT = regroup_avail_blocks(availStyle, mpathA, availT)
local aa = {}
for j = 1, #labelA do
local a = {}
local label = labelA[j]
availDir(defaultOnly, terse, searchA, label, locationT, availT[label], dbT, a, legendT)
if (next(a)) then
aa[#aa+1] = "\n"
aa[#aa+1] = banner:bannerStr(label)
aa[#aa+1] = "\n"
local ct = ColumnTable:new{tbl=a, gap=1, len=length}
aa[#aa+1] = ct:build_tbl()
aa[#aa+1] = "\n"
end
end
if (next(legendT)) then
aa[#aa+1] = "\n Where:\n"
local a = {}
for k, v in pairsByKeys(legendT) do
a[#a+1] = { " " .. k ..":", v}
end
local bt = BeautifulTbl:new{tbl=a, column = twidth-1, len=length}
aa[#aa+1] = bt:build_tbl()
aa[#aa+1] = "\n"
end
if (not quiet()) then
aa = hook.apply("msgHook", "avail", aa)
end
shell:echo(concatTbl(aa,""))
dbg.fini("Master.avail")
end
return M
|
-- react_ and postreact_ event module for reactions near the object
--[[ include 'listen'
obj {
nam = 'npc';
react_Take = "Player in this room is taking something. Reject!";
}:listen();
]]--
--luacheck: globals mp
--luacheck: no self
game.react_list = std.list {}
function game:before_Any(ev, ...)
for _, v in ipairs(game.react_list) do
if v:inroom() == std.here() then
local r = mp:runmethods('react', ev, v, ...)
if r ~= false then
return
end
end
end
return false
end
function game:post_Any(ev, ...)
for _, v in ipairs(game.react_list) do
if v:inroom() == std.here() then
local r = mp:runmethods('postreact', ev, v, ...)
if r ~= false then
return
end
end
end
return false
end
function std.obj.listen(s)
game.react_list:add(s)
return s
end
|
--[[
不同地区大厅配置差异列表
xBuild会根据XML文件来修改这里面的值,以适应不同的地区
WARNING WARNING
切记不可以直接访问此处的变量切记不可以直接访问此处的变量
1、配置如何更新(添加|删除)
1.1 添加 每个版本更新时,如果需要新添加配置
step1:在regionConfigCommon中添加此变量名(以Region为开头),并附加详细的注释
step2:在regionConfigDataInterface中添加接口供外部访问
step3:如果此变量游戏需要进行访问,则需要在regionConfigIsolater中也添加接口
step4:在打包工具后台 http://tools.oa.com/?c=config&m=show 进行配置
1.2:删除 版本更新时,如果老的配置不再需要时(切记需要确认清楚,尤其是涉及到子游戏时)
step1:在regionConfigCommon中删除此变量
step2:在regionConfigDataInterface中对接口进行兼容处理(格式、变量都需要保持一致)
step3:在打包工具后台 http://tools.oa.com/?c=config&m=show 进行修改配置
2、配置如何访问
2.1 大厅访问此配置,应该通过regionConfigDataInterface接口进行访问
2.2 子游戏访问此配置,应该通过regionConfigIsolater接口进行访问
--]]
--全局测试开关, 用于日志|临时测试等(此变量允许全局访问)
--当_DEBUG开关为true时,此时UMENG号则设置为552c8f28fd98c54c18000149(打包后台自动处理)
_DEBUG = true;
--android & win32平台appid
kAndroidAppId = 103000;
--ios平台appid
kIosAppId = 101000;
-------------------------------------非常重要的配置,新建地区的时候必须要进行配置--------------------
--与游戏内gameConfig区别:大厅依赖的APK的版本号
Region_dependApkVersion = "2.3.0.0";
--正式服CDN配置,地区接入时需要找PHP获取
Region_OnlineCdn_Url = "http://uchead.static.17c.cn/dfqp/static/site/sichuan.mobile.json";
--正式服 ip port
Region_Online_IpPort = {
{ip="access.yunnangames.com", port=7000};
{ip="access.yunnangames.com", port=7000};
{ip="access.sichuanyouxi.com", port=7000};
{ip="access.sichuanyouxi.com", port=7000};
{ip="access.shandonggames.com", port=7000};
{ip="access.shandonggames.com", port=7000};
{ip="access.shandonggames.com", port=7000};
{ip="access.shandonggames.com", port=7000};
{ip="106.14.55.74", port=7000};
{ip="59.110.90.152", port=7000};
}
--[[
大厅支持的游戏最小版本号
RegionGamesPlayableConfig = {
[1] = { ["gameid"] = 203, ["ver"] = 76}; 203:游戏id 76:游戏版本号
}
]]
RegionGamesPlayableConfig = {};
--[[
地区默认的游戏列表
Region_default_games_config = {
[1]={ ["id"]=9, ["game_pkg"]="games/eqs"},
[2]={ ["id"]=2, ["game_pkg"]="games/scmj"},
}
]]
Region_default_games_config = {};
--默认城市
RegionText_default_city = "四川"
--产品名称
RegionText_productName = "四川棋牌";
--各游戏版号声明
RegionText_gamesStatement = "川味斗地主:新出审字[2014]1094号\n 血战到底:新出审字[2014]1094号\n 贰柒拾:新出审字[2015]8号\n 斗地主:新出审字[2013]1094号\n 马股:新出审字[2015]9号";
--[[
游戏帮助界面tab和对应的xml文件
Region_gameHelpHtml_Config = {
[1] = { ["name"] = "通用", ["fileName"] = "help" };
[1] = { ["name"] = "贰柒拾", ["fileName"] = "eqs_help" };
}
]]
Region_gameHelpHtml_Config = {}
--[[
反馈参数
Region_suggestion_paramData = {
game = "scqp"
android = "4045";
ios = "2032"
}
]]
Region_suggestion_paramData = {
game = "scqp";
android = "4045";
ios = "2032"
};
--[[
分享按钮配置
Region_default_shareConfig = {
["weixinGroup"] = true;
["weixinFriend"] = true;
}
]]
Region_default_shareConfig = {
weixinGroup = true;
weixinFriend = true;
};
--默认客服电话, 如果PHP没返回则采用这个
Region_default_hotline = "400-663-1888";
-------------------------------------------非常规配置项----------------------------
--关于中需要显示的tabs和其顺序
Region_aboutus_tabNames = {"aboutUsView", "agreementView", "privacyView", "versionView"};
--关于中的公司名称
Region_aboutus_company = "博雅互动 版权所有";
--关于中的版权名称
Region_aboutus_copyrightText = "Copyright(c)2014-2017 Boyaa\nAll Rights Reserved.";
--个人信息是否显示等级经验
Region_show_user_level_exp = true;
--设置声音文本
Region_setting_voice_text = "读牌"
--反馈时间文本
Region_suggestion_time_text = "牌局时间";
--联系客服页面的的电话号码是否显示
Region_show_suggestion_phone_text = true;
--退出游戏界面是否显示今日的银币输赢
Region_show_exitGame_today_money = true;
--video是否支持2G
Region_video_support_2G = false;
--默认破产线
Region_Default_Bankrupt_Money = 3000; -- 默认破产线,因为四川的特殊性,加了这个字段
|
class 'BloozeMod'
function BloozeMod:__init()
Events:Subscribe( "BloozingStart", self, self.BloozingStart )
Events:Subscribe( "LocalPlayerDeath", self, self.LocalPlayerDeath )
Events:Subscribe( "LocalPlayerWorldChange", self, self.LocalPlayerWorldChange )
end
function BloozeMod:InputPoll()
if Input:GetValue( Action.TurnRight ) == 0 and Input:GetValue( Action.TurnLeft ) == 0 then
if self.timer:GetSeconds() <= 5 then
Input:SetValue(Action.TurnRight, self.num)
else
Input:SetValue(Action.TurnLeft, self.num)
end
end
end
function BloozeMod:CalcView()
if not LocalPlayer:InVehicle() then
Camera:SetFOV( 0.9 )
end
if LocalPlayer:GetBaseState() ~= 208 then
if self.naklon == 1 then
Camera:SetAngle( Camera:GetAngle() * Angle( self.value, self.value, self.value ) )
else
Camera:SetAngle( Camera:GetAngle() * Angle( - self.value, -self.value, - self.value ) )
self.naklon = 0
end
end
if self.timer:GetSeconds() <= 5 then
self.value = self.value + self.timer:GetSeconds() * 0.0002
else
if self.value >= 0 then
self.value = self.value - self.timer:GetSeconds() * 0.0002
else
self.timer:Restart()
self.naklon = self.naklon + 1
if LocalPlayer:GetBaseState() == 6 or LocalPlayer:GetBaseState() == 7 or LocalPlayer:GetBaseState() == 9 and not LocalPlayer:GetVehicle() then
local animations = { LocalPlayer:GetBaseState(), AnimationState.SSkydive, LocalPlayer:GetBaseState() }
LocalPlayer:SetBaseState( animations[math.random(#animations)] )
if LocalPlayer:GetBaseState() == AnimationState.SSkydive then
Game:FireEvent( "ply.reacthitfly" )
end
end
end
end
if self.bloozingtimer:GetMinutes() >= 3 then
self:BloozingStop()
end
end
function BloozeMod:BloozingStart()
Network:Send( "MinusHP" )
local sound = ClientSound.Create(AssetLocation.Game, {
bank_id = 12,
sound_id = 19,
position = LocalPlayer:GetPosition(),
angle = LocalPlayer:GetAngle()
})
sound:SetParameter(0,1)
local sound = ClientSound.Create(AssetLocation.Game, {
bank_id = 12,
sound_id = 1,
position = LocalPlayer:GetPosition(),
angle = LocalPlayer:GetAngle()
})
sound:SetParameter(2,1)
if not self.bloozingtimer then
self.backfov = Camera:GetFOV()
self.num = 0.2
self.timer = Timer()
self.value = 0
self.naklon = 0
self.bloozingtimer = Timer()
self.InputPollEvent = Events:Subscribe( "InputPoll", self, self.InputPoll )
self.CalcViewEvent = Events:Subscribe( "CalcView", self, self.CalcView )
else
self.bloozingtimer:Restart()
end
end
function BloozeMod:BloozingStop()
if self.backfov then
Camera:SetFOV( self.backfov )
end
self.backfov = nil
self.num = nil
self.timer = nil
self.value = nil
self.naklon = nil
self.bloozingtimer = nil
if self.InputPollEvent then
Events:Unsubscribe( self.InputPollEvent )
self.InputPollEvent = nil
end
if self.CalcViewEvent then
Events:Unsubscribe( self.CalcViewEvent )
self.CalcViewEvent = nil
end
end
function BloozeMod:LocalPlayerDeath()
self:BloozingStop()
end
function BloozeMod:LocalPlayerWorldChange()
self:BloozingStop()
end
bloozemod = BloozeMod()
|
I2CSCAN = {}
function I2CSCAN.scan()
STMP.i2c.init()
STMP.i2c.set_speed(true)
for i = 2, 254, 2 do
if STMP.i2c.transmit(i, {}, true) then
print(string.format("%#x OK", i))
end
end
end
-- if file is nil, return array
-- if size is nil, dump the whole EEPROM
function I2CSCAN.dump_rom(file, size)
STMP.i2c.init()
STMP.i2c.set_speed(true)
if not STMP.i2c.transmit(0xa0, {0, 0}, false) then
error("Cannot send address")
end
local res = {}
if size == nil then
size = 0xffff
end
for i = 0, size do
local l = STMP.i2c.receive(0xa0, 1)
if l == nil then
error("error during transfer")
end
for i = 1, #l do
table.insert(res, l[i])
end
end
if file == nil then
return res
end
local f = file
if type(file) == "string" then
f = io.open(file, "w")
end
if f == nil then error("Cannot open file or write to nil") end
for i = 1, #res do
f:write(string.char(res[i]))
end
if type(file) == "string" then
io.close(f)
end
end
|
local stub = require("luassert.stub")
local loop = require("null-ls.loop")
local methods = require("null-ls.methods")
local c = require("null-ls.config")
local s = require("null-ls.state")
describe("state", function()
local mock_client_id = 1234
local mock_action_stub = stub.new()
local mock_action = {
title = "Mock action",
-- need to wrap to pass validation
action = function()
mock_action_stub()
end,
}
after_each(function()
mock_action_stub:clear()
s.reset()
end)
describe("get", function()
it("should get initial state", function()
local state = s.get()
assert.equals(state.client_id, nil)
assert.same(state.actions, {})
end)
it("should get updated state", function()
s.set({ mock_key = "mock_val" })
assert.equals(s.get().mock_key, "mock_val")
end)
end)
describe("reset", function()
it("should reset state to initial state", function()
s.set({ client_id = mock_client_id })
s.reset()
local state = s.get()
assert.equals(state.client_id, nil)
assert.same(state.actions, {})
end)
end)
describe("client", function()
describe("notify_client", function()
local notify = stub.new()
local mock_params = { key = "val" }
local mock_client
before_each(function()
mock_client = { notify = notify }
s.set({ client = mock_client })
end)
after_each(function()
notify:clear()
s.reset()
end)
it("should return immediately if client does not exist", function()
s.reset()
s.notify_client("mockMethod", mock_params)
assert.stub(notify).was_not_called()
end)
it("should should call client.notify with method and params", function()
s.notify_client("mockMethod", mock_params)
assert.stub(notify).was_called_with("mockMethod", mock_params)
end)
end)
describe("get_rtp", function()
local original_rtp = vim.o.rtp
after_each(function()
vim.o.rtp = original_rtp
end)
it("should get rtp from vim.o.rtp when not set", function()
vim.o.rtp = "/my/plugin/path/other-plugin.nvim,/my/plugin/path/null-ls.nvim"
local rtp = s.get_rtp()
assert.equals(rtp, "/my/plugin/path/null-ls.nvim")
end)
it("should get rtp from state when already set", function()
s.set({ rtp = "/my/rtp/null-ls.nvim" })
local rtp = s.get_rtp()
assert.equals(rtp, "/my/rtp/null-ls.nvim")
end)
it("should throw error when null-ls rtp not fund", function()
vim.o.rtp = "/my/plugin/path/other-plugin.nvim"
assert.has_error(function()
s.get_rtp()
end)
end)
end)
describe("initialize", function()
stub(loop, "timer")
local notify = stub.new()
local mock_client
before_each(function()
mock_client = { notify = notify }
end)
after_each(function()
loop.timer:clear()
s.reset()
end)
it("should assign client to state", function()
s.initialize(mock_client)
assert.equals(s.get().client, mock_client)
end)
it("should create timer and assign to state", function()
loop.timer.returns("timer")
s.initialize(mock_client)
assert.equals(s.get().keep_alive_timer, "timer")
end)
describe("timer", function()
it("should create timer with correct args", function()
s.initialize(mock_client)
assert.equals(loop.timer.calls[1].refs[1], 0)
assert.equals(loop.timer.calls[1].refs[2], c.get().keep_alive_interval)
assert.equals(loop.timer.calls[1].refs[3], true)
assert.truthy(loop.timer.calls[1].refs[4])
end)
it("should call notify_client on timer callback", function()
s.initialize(mock_client)
local callback = loop.timer.calls[1].refs[4]
callback()
assert.stub(notify).was_called_with(methods.internal._NOTIFICATION, {
timeout = c.get().keep_alive_interval,
})
end)
end)
end)
describe("shutdown_client", function()
stub(vim.lsp, "stop_client")
stub(vim, "wait")
stub(loop, "timer")
local is_stopped = stub.new()
local mock_timer = { stop = stub.new() }
local mock_client
before_each(function()
mock_client = { is_stopped = is_stopped }
s.set({ client_id = mock_client_id, client = mock_client })
end)
after_each(function()
vim.lsp.stop_client:clear()
vim.wait:clear()
is_stopped:clear()
mock_timer.stop:clear()
s.reset()
end)
it("should return if state client is nil", function()
s.reset()
s.shutdown_client()
assert.stub(vim.lsp.stop_client).was_not_called()
end)
it("should call stop_client with state client_id", function()
s.shutdown_client()
assert.stub(vim.lsp.stop_client).was_called_with(mock_client_id)
end)
it("should call stop method on keep_alive_timer", function()
s.set({ keep_alive_timer = mock_timer })
s.shutdown_client()
assert.stub(mock_timer.stop).was_called_with(true)
end)
it("should reset state", function()
s.shutdown_client()
assert.equals(s.get().client_id, nil)
end)
describe("wait", function()
it("should call vim.wait with default timeout and interval", function()
s.shutdown_client()
assert.equals(vim.wait.calls[1].refs[1], 5000)
assert.equals(vim.wait.calls[1].refs[3], 10)
end)
it("should call vim.wait with specified timeout", function()
s.shutdown_client(1000)
assert.equals(vim.wait.calls[1].refs[1], 1000)
end)
describe("callback", function()
it("should return true if client is nil", function()
s.shutdown_client()
local callback = vim.wait.calls[1].refs[2]
assert.equals(callback(), true)
end)
it("should return true if client is_stopped method returns true", function()
is_stopped.returns(true)
s.shutdown_client()
local callback = vim.wait.calls[1].refs[2]
s.set({ client = mock_client })
assert.equals(callback(), true)
assert.stub(is_stopped).was_called()
end)
it("should return false otherwise", function()
is_stopped.returns(false)
s.shutdown_client()
local callback = vim.wait.calls[1].refs[2]
s.set({ client = mock_client })
assert.equals(callback(), false)
assert.stub(is_stopped).was_called()
end)
end)
end)
end)
describe("attach", function()
stub(vim.lsp, "buf_attach_client")
stub(vim, "uri_from_bufnr")
local mock_bufnr, mock_uri = 75, "file:///mock-file.lua"
before_each(function()
s.set({ client_id = mock_client_id })
vim.uri_from_bufnr.returns(mock_uri)
end)
after_each(function()
vim.lsp.buf_attach_client:clear()
vim.uri_from_bufnr:clear()
end)
it("should call buf_attach_client with bufnr and client_id", function()
s.attach(mock_bufnr)
assert.stub(vim.lsp.buf_attach_client).was_called_with(mock_bufnr, mock_client_id)
end)
it("should not call buf_attach_client again if buffer is already attached", function()
s.attach(mock_bufnr)
s.attach(mock_bufnr)
assert.stub(vim.lsp.buf_attach_client).was_called(1)
end)
it("should save bufnr in state.attached under uri", function()
s.attach(mock_bufnr)
assert.equals(s.get().attached[mock_uri], mock_bufnr)
end)
end)
end)
describe("actions", function()
describe("register_action", function()
it("should register action under state.actions[title]", function()
s.register_action(mock_action)
assert.equals(s.get().actions[mock_action.title], mock_action.action)
end)
end)
describe("run_action", function()
before_each(function()
s.register_action(mock_action)
end)
it("should run action matching title", function()
s.run_action(mock_action.title)
assert.stub(mock_action_stub).was_called()
end)
end)
describe("clear_actions", function()
it("should clear state actions", function()
s.register_action(mock_action)
s.clear_actions()
assert.equals(s.get().actions[mock_action.title], nil)
end)
end)
end)
describe("cache", function()
stub(vim, "uri_from_bufnr")
stub(vim.api, "nvim_buf_is_loaded")
local mock_bufnr, mock_cmd, mock_content = 54, "ls", "test.lua"
local mock_uri = "file:///test.lua"
before_each(function()
vim.api.nvim_buf_is_loaded.returns(true)
vim.uri_from_bufnr.returns(mock_uri)
end)
after_each(function()
vim.api.nvim_buf_is_loaded:clear()
vim.uri_from_bufnr:clear()
end)
describe("set_cache", function()
it("should return if bufnr is not loaded", function()
vim.api.nvim_buf_is_loaded.returns(false)
s.set_cache(mock_bufnr, mock_cmd, mock_content)
assert.stub(vim.api.nvim_buf_is_loaded).was_called_with(mock_bufnr)
assert.stub(vim.uri_from_bufnr).was_not_called()
end)
it("should set state.cache when cache has not been set", function()
s.set_cache(mock_bufnr, mock_cmd, mock_content)
assert.stub(vim.uri_from_bufnr).was_called_with(mock_bufnr)
assert.same(s.get().cache[mock_uri], { [mock_cmd] = mock_content })
end)
it("should set state.cache from command minus path", function()
s.set_cache(mock_bufnr, "/path/to/" .. mock_cmd, mock_content)
assert.stub(vim.uri_from_bufnr).was_called_with(mock_bufnr)
assert.same(s.get().cache[mock_uri], { [mock_cmd] = mock_content })
end)
it("should overwrite state.cache when already set", function()
s.set_cache(mock_bufnr, mock_cmd, mock_content)
s.set_cache(mock_bufnr, mock_cmd, "other-file.lua")
assert.same(s.get().cache[mock_uri], { [mock_cmd] = "other-file.lua" })
end)
end)
describe("get_cache", function()
it("should return if bufnr is not loaded", function()
vim.api.nvim_buf_is_loaded.returns(false)
local cached = s.get_cache(mock_bufnr, mock_cmd)
assert.stub(vim.api.nvim_buf_is_loaded).was_called_with(mock_bufnr)
assert.stub(vim.uri_from_bufnr).was_not_called()
assert.equals(cached, nil)
end)
it("should return nil if cache for uri is not set", function()
local cached = s.get_cache(mock_bufnr, mock_cmd)
assert.stub(vim.uri_from_bufnr).was_called_with(mock_bufnr)
assert.equals(cached, nil)
end)
it("should return cached content", function()
s.set_cache(mock_bufnr, mock_cmd, mock_content)
local cached = s.get_cache(mock_bufnr, mock_cmd)
assert.equals(cached, mock_content)
end)
it("should return cached content minus path", function()
s.set_cache(mock_bufnr, "/path/to/" .. mock_cmd, mock_content)
local cached = s.get_cache(mock_bufnr, "/path/to/" .. mock_cmd)
assert.equals(cached, mock_content)
end)
end)
describe("clear_cache", function()
it("should do nothing if cache for uri is not set", function()
s.clear_cache(mock_uri)
assert.equals(s.get().cache[mock_uri], nil)
end)
it("should clear cache for uri", function()
s.set_cache(mock_bufnr, mock_cmd, mock_content)
s.clear_cache(mock_uri)
assert.equals(s.get().cache[mock_uri], nil)
end)
end)
end)
end)
|
#!/usr/bin/lua
if not arg[1] then
print("Usage:\tpico2lua.lua [FILE]")
print("Prints out the lua code in a file pico-8 format file to stdout.")
print("e.g.: ./pico2lua.lua cart.p8 > code.lua")
else
local file
if arg[1] == '-' then
file = io.stdin
else
file = io.open(arg[1])
end
local found_lua = false
local section_header = false
while true do
local line = file:read("*line")
if line == nil then break end
for section,_ in string.gmatch(line,"__(%a+)__") do
section_header = true
if section == "lua" then
found_lua = true
break
else
found_lua = false
break
end
end
if found_lua then
if section_header then
section_header = false
else
io.write(line.."\n")
end
end
end
end
|
local makeNumberSequence = require("rbx_lua_types").NumberSequence.new
local makeNumberSequenceKeypoint = require("rbx_lua_types").NumberSequenceKeypoint.new
local datatype = {}
datatype.name = "NumberSequence"
datatype.id = 0x15
function datatype.default()
return makeNumberSequence({
{Time = 0, Value = 0, Envelope = 0},
{Time = 1, Value = 0, Envelope = 0},
})
end
function datatype.reader(stream, count)
local sequences = {}
for i = 1, count do
local numKeypoints = stream.readLEUInt32()
local keypoints = {}
for l = 1, numKeypoints do
local time = stream.readLEFloat32()
local value = stream.readLEFloat32()
local envelope = stream.readLEFloat32()
keypoints[l] = makeNumberSequenceKeypoint(time, value, envelope)
end
sequences[i] = makeNumberSequence(keypoints)
end
return sequences
end
function datatype.writer(stream, values)
error("writer is not yet implemented for type `"..datatype.name.."`", 2)
end
return datatype
|
---Label API documentation
---Label API documentation
---@class label
label = {}
---Gets the text from a label component
---@param url string|hash|url the label to get the text from
---@return string the label text
function label.get_text(url) end
---Gets the text metrics from a label component
---@param url string|hash|url the label to get the (unscaled) metrics from
---@return table a table with the following fields:
function label.get_text_metrics(url) end
---Sets the text of a label component
--- This method uses the message passing that means the value will be set after dispatch messages step.
---More information is available in the Application Lifecycle manual <>.
---@param url string|hash|url the label that should have a constant set
---@param text string the text
function label.set_text(url, text) end
return label
|
local KC = require 'klib/container/container'
local RBTree = require 'klib/ds/rbtree'
local function __call(self, ...)
if ... then
self:push(...)
else
return self:pop()
end
end
local Q = KC.class('klib.ds.PriorityQueue', function(self)
self.tree = RBTree:new()
getmetatable(self).__call = __call
end)
function Q:on_load()
getmetatable(self).__call = __call
end
function Q:on_destroy()
self.tree:destroy()
end
function Q:push(priority, data)
self.tree:insert(priority, data)
end
function Q:pop()
local node = self.tree:minimum_node()
if node ~= self.tree.sentinel then
self.tree:delete_node(node)
return node.data, node.key
else
return nil
end
end
return Q
|
-- Disable color column in quickfix lists
vim.opt_local.colorcolumn = ""
|
return {
id = "material_pastelpurple",
type = "material",
name = "Pastel Purple",
description = "A nice purple color for your eg!",
rarity = 8,
hidden = false,
metadata = {
color = Color3.fromRGB(180, 128, 255),
material = Enum.Material.SmoothPlastic,
}
}
|
--------------------------------
-- @module BaseLight
-- @extend Node
-- @parent_module cc
---@class cc.BaseLight:cc.Node
local BaseLight = {}
cc.BaseLight = BaseLight
--------------------------------
--- light enabled getter and setter.
---@param enabled boolean
---@return cc.BaseLight
function BaseLight:setEnabled(enabled)
end
--------------------------------
--- intensity getter and setter
---@return number
function BaseLight:getIntensity()
end
--------------------------------
---
---@return boolean
function BaseLight:isEnabled()
end
--------------------------------
--- Get the light type,light type MUST be one of LightType::DIRECTIONAL ,
--- LightType::POINT, LightType::SPOT, LightType::AMBIENT.
---@return number
function BaseLight:getLightType()
end
--------------------------------
---
---@param flag number
---@return cc.BaseLight
function BaseLight:setLightFlag(flag)
end
--------------------------------
---
---@param intensity number
---@return cc.BaseLight
function BaseLight:setIntensity(intensity)
end
--------------------------------
--- light flag getter and setter
---@return number
function BaseLight:getLightFlag()
end
return nil
|
function initBme280()
--print('Setting up bme280')
sda = 6
scl = 5
i2c.setup(0, sda, scl, i2c.SLOW)
bme280.setup()
--print('Bme280 set up')
end
|
-- A simple gdb interface for SciTE
-- Steve Donovan, 2007
-- changes:
-- (1) debug.backtrace.depth will configure depth of stack frame dump (default is 20)
-- (2) initially only adds Run and Breakpoint to the menu
-- (3) first generalized version
local GTK = scite_GetProp('PLAT_GTK')
function do_set_menu()
--~ scite_Command {
--~ 'Step|do_step|Alt+C',
--~ 'Step Over|do_next|Alt+N',
--~ 'Go To|do_temp_breakpoint|Alt+G',
--~ 'Kill|do_kill|Alt+K',
--~ 'Inspect|do_inspect|Alt+I',
--~ 'Locals|do_locals|Alt+Ctrl+L',
--~ 'Watch|do_watch|Alt+W',
--~ 'Backtrace|do_backtrace|Alt+Ctrl+B',
--~ 'Step Out|do_finish|Alt+M',
--~ 'Up|do_up|Alt+U',
--~ 'Down|do_down|Alt+D',
--~ }
end
-- only bring up the absolute minimum commands initially....
scite_Command {
--~ 'Run|do_run|*{savebefore:yes}|Alt+R',
--~ 'Breakpoint|do_breakpoint|F9'
}
scite_require 'extlib.lua'
local lua_prompt = '(lua)'
local prompt
local prompt_len
local sub = string.sub
local find = string.find
local len = string.len
local gsub = string.gsub
local status = 'dead'
local last_command
local last_breakpoint
local traced
local dbg
function dbg_last_command()
return dbg.last_command
end
function dbg_status()
return status
end
function dbg_obj()
return dbg
end
function debug_line_handler(line)
local state = dbg_status()
local dbg = dbg_obj()
if state ~= 'dead' then
dbg.last_command = '<inter>'
spawner_command(line)
end
end
local debug_status = scite_GetProp('debug.status',false)
-- *doc* you can add $(status.msg) to your statusbar.text.1 property if
-- you want to see debugger status.
-- (see SciTEGlobal.properties for examples)
function set_status(s)
if s ~= status then
if debug_status then print('setting status to '..s) end
status = s
local str = s
if s == 'dead' then str = '' end
props['status.msg'] = str
scite.UpdateStatusBar(true)
end
end
function dbg_status()
return status
end
------- Generic debugger interface, based on GDB ------
Dbg = class()
function Dbg:init(root)
end
function Dbg:default_target()
local ext = self.no_target_ext
if ext then
local res = props['FileName']
if ext ~= '' then res = res..'.'..ext end
return res
else
return props['FileNameExt']
end
end
function Dbg:step()
dbg_command('step')
end
function Dbg:step_over()
dbg_command('next')
end
function Dbg:continue()
dbg_command('cont')
end
function Dbg:quit()
spawner_command('quit')
if not self.no_quit_confirm then
spawner_command('y')
end
end
function Dbg:set_breakpoint(file,lno)
dbg_command('break',file..':'..lno)
end
-- generally there are two ways to kill breakpoints in debuggers;
-- either by number or by explicit file:line.
function Dbg:clear_breakpoint(file,line,num)
if file then
dbg_command('clear',file..':'..line)
else
print ('no breakpoint at '..file..':'..line)
end
end
-- run until the indicated file:line is reached
function Dbg:goto(file,lno)
dbg_command('tbreak',file..':'..lno)
dbg_command('continue')
end
function Dbg:set_display_handler(fun)
-- 0.8 change: if a handler is already been set, don't try to set a new one!
if self.result_handler then return end
self.result_handler = fun
end
function Dbg:inspect(word)
dbg_command('print',word)
end
local skip_file_pattern
local do_skip_includes
--- *doc* you can choose a directory pattern for files which you don't want to skip through
--- for Unix, this is usually easy, but for mingw you have to supply the path to
--- your gcc directory.
function Dbg:auto_skip_over_file(file)
if not do_skip_includes then return end
return find(file,skip_file_pattern)
end
function Dbg:finish()
dbg_command('finish')
end
function Dbg:locals()
dbg_command('info locals')
end
function Dbg:watch(word)
dbg_command('display',word)
end
function Dbg:up()
dbg_command('up')
end
function Dbg:down()
dbg_command('down')
end
function Dbg:backtrace(depth)
dbg_command('backtrace',depth)
end
function Dbg:frame(f)
dbg_command('frame',f)
end
function Dbg:detect_frame(line)
local _,_,frame = find(line,'#(%d+)')
if _ then
dbg:frame(frame)
end
end
function Dbg:special_debugger_setup(out)
end
function Dbg:breakpoint_confirmation(line)
-- breakpoint defintion confirmation
-- ISSUE: only picking up for breakpoints added _during_ session!
local _,_,bnum = find(line,"Breakpoint (%d+) at")
if _ then
if last_breakpoint then
print('breakpoint:',last_breakpoint.line,bnum)
last_breakpoint.num = bnum
end
end
end
function quote(s)
return '"'..s..'"'
end
function Dbg:find_execution_break(line)
local _,_,file,lineno = find(line,self.break_line)
if _ then return file,lineno end
end
function Dbg:check_breakpoint (b)
return true
end
-- add our currently defined breakpoints
function Dbg:dump_breakpoints(out)
for b in Breakpoints() do
if self:check_breakpoint(b) then
local f = basename(b.file)
print (b.file,f)
out:write('break '..f..':'..b.line..'\n')
end
end
end
function Dbg:run_program(out,parms)
out:write('run '..parms..'\n')
end
function Dbg:detect_program_crash(line)
return false
end
----- Debugger commands --------
local spawner_obj
local function launch_debugger()
if do_launch() then
set_status('running')
return true
else
print 'Unable to debug program!'
return false
end
end
local function try_start_debugger()
if not dbg then
return launch_debugger()
else
return true
end
end
function do_step()
if not try_start_debugger() then return end
dbg:step()
end
function do_run()
if status == 'dead' then
launch_debugger()
else
RemoveLastMarker(true)
dbg:continue()
set_status('running')
end
end
function do_kill()
if not dbg then return end
if status == 'running' then
-- this actually kills the debugger process
spawner_obj:kill()
else
-- this will ask the debugger nicely to exit
dbg:quit()
end
closing_process()
end
function do_next()
if not try_start_debugger() then return end
dbg:step_over()
end
function breakpoint_from_position(lno)
for b in Breakpoints() do
if b.file == scite_CurrentFile() and b.line == lno then
return b
end
end
return nil
end
function do_breakpoint()
local lno = current_line() + 1
local file = props['FileNameExt']
-- do we have already have a breakpoint here?
local brk = breakpoint_from_position(lno)
if brk then
local bnum = brk.num
brk:delete()
if status ~= 'dead' then
dbg:clear_breakpoint(file,lno,bnum)
end
else
last_breakpoint = SetBreakMarker(lno)
if last_breakpoint then
if status ~= 'dead' then
dbg:set_breakpoint(file,lno)
end
end
end
end
function do_temp_breakpoint()
if not try_start_debugger() then return end
local lno = current_line() + 1
local file = props['FileNameExt']
dbg:goto(file,lno)
end
local function char_at(p)
return string.char(editor.CharAt[p])
end
-- used to pick up current expression from current document position
-- We use the selection, if available, and otherwise pick up the word;
-- if it seems to be a field expression, look for the object before.
local function current_expr(pos)
local s = editor:GetSelText()
if s == '' then -- no selection, so find the word
pos = pos or editor.CurrentPos
local p1 = editor:WordStartPosition(pos,true)
local p2 = editor:WordEndPosition(pos,true)
-- is this a field of some object?
while true do
if char_at(p1-1) == '.' then -- generic member access
p1 = editor:WordStartPosition(p1-2,true)
elseif char_at(p1-1) == '>' and char_at(p1-2) == '-' then --C/C++ pointer
p1 = editor:WordStartPosition(p1-3,true)
else
break
end
end
return editor:textrange(p1,p2)
else
return s
end
end
function actually_inspect(w)
if len(w) > 0 then
dbg:inspect(w)
end
end
function do_inspect()
if not dbg then return end
local w = current_expr()
scite.Prompt("Inspect which expression:",w,"actually_inspect")
end
function do_locals()
if not dbg then return end
dbg:locals()
end
function actually_watch(w)
dbg:watch(w)
end
function do_watch()
if not dbg then return end
scite.Prompt("Watch which expression:",current_expr(),"actually_watch")
end
function do_backtrace()
if not dbg then return end
dbg:backtrace(scite_GetProp('debug.backtrace.depth','20'))
end
function do_up()
if not dbg then return end
dbg:up()
end
function do_down()
if not dbg then return end
dbg:down()
end
function do_finish()
if not dbg then return end
dbg:finish()
end
local root
function Dbg:parameter_string()
-- any parameters defined with View|Parameters
local parms = ' '
local i = 1
local parm = props[i]
while parm ~= '' do
if find(parm,'%s') then
-- if it's already quoted, then preserve the quotes
if find(parm,'"') == 1 then
parm = gsub(parm,'"','\\"')
end
parm = '"'..parm..'"'
end
parms = parms..' '..parm
i = i + 1
parm = props[i]
end
return parms
end
local menu_init = false
local debug_verbose
local debuggers = {}
local append = table.insert
local remove = table.remove
---- event handling
-- If an event returns true, then this event will persist.
-- The return value of this function is true if any event returns an extra true result
-- Note: we iterate over a copy of the list, because this is the only way I've
-- found to make this method re-enterant. With this scheme it is
-- safe to raise an event within an event handler.
function Dbg:raise_event (event,...)
local events = self.events
if not events then return end
-- not recommended for big tables!
local cpy = {unpack(events)}
local ignore
for i,evt in ipairs(cpy) do
if evt.event == event then
local keep,want_to_ignore = evt.handler(...)
if not keep then
remove(events,i)
end
ignore = ignore or want_to_ignore
end
end
return ignore
end
function Dbg:set_event (name,handler)
if not self.events then self.events = {} end
append(self.events,{event=name,handler=handler})
end
function Dbg:queue_command (cmd)
self:set_event('prompt',function() spawner_command(cmd) end)
end
function create_existing_breakpoints()
local out = io.open(dbg.cmd_file,"w")
dbg:special_debugger_setup(out)
dbg:dump_breakpoints(out)
local parms = dbg:parameter_string()
dbg:run_program(out,parms)
out:close();
end
-- you may register more than one debugger class (@dclass) but such classes must
-- have a static method discriminate() which will be passed the full target name.
function register_debugger(name,ext,dclass)
if type(ext) == 'table' then
for i,v in ipairs(ext) do
register_debugger(name,v,dclass) --**
end
else
if not debuggers[ext] then
debuggers[ext] = {dclass}
else
if not dclass.discriminator then
error("Multiple debuggers registered for this extension, with no discriminator function")
end
append(debuggers[ext],dclass)
end
end
end
function create_debugger(ext,target)
local dclasses = debuggers[ext]
if not dclasses then dclasses = debuggers['*'] end
if #dclasses == 1 then -- there is only one possible debugger for this extension!
return dclasses[1]
else -- there are several registered. We need to call the discriminator!
for i,d in ipairs(dclasses) do
if d.discriminator(target) then
return d
end
end
end
error("unable to find appropriate debugger")
end
local initialized
local was_error = false
local continued_line, end_line_action, postproc
function do_launch()
if not menu_init then
do_set_menu()
menu_init = true
end
scite.MenuCommand(IDM_SAVE)
local no_host_symbols
traced = false
debug_verbose = true
-- *doc* detect the debugger we want to use, based on target extension
-- if there is no explicit target, then use the current file.
local target = scite_GetProp('debug.target')
local ext
if target then
-- @doc the target may not actually have debug symbols, in the case
-- where we are debugging some dynamic libraries. Indicate this
-- by prefixing target with [n]
if target:find('^%[n%]') then
target = target:sub(4)
no_host_symbols = true
end
ext = extension_of(target)
else
ext = props['FileExt']
end
dbg = create_debugger(ext,choose(target,target,props['FileName']))
dbg.host_symbols = not no_host_symbols
-- this isn't ideal!
root = props['TMP']
dbg:init(root)
do_skip_includes = scite_GetProp('debug.skip.includes',false)
if do_skip_includes then
local inc_path
if GTK then inc_path = '^/usr/' else inc_path = '<<<DONUT>>>' end
local file_pat_prop = 'debug.skip.file.matching'
if dbg.skip_system_extension then
file_pat_prop = file_pat_prop..dbg.skip_system_extension
end
skip_file_pattern = scite_GetProp(file_pat_prop,inc_path)
end
-- *doc* the default target depends on the debugger (it wd have extension for pydb, etc)
if not target then target = dbg:default_target() end
target = quote_if_needed(target)
-- *doc* this determines the time before calltips appear; you can set this as a SciTE property.
if props['dwell.period'] == '' then props['dwell.period'] = 500 end
-- get the debugger process command string
local dbg_cmd = dbg:command_line(target)
print(dbg_cmd)
continued_line = nil
-- first create the cmd file for the debugger
create_existing_breakpoints()
scite_InteractivePromptHandler (dbg.prompt,debug_line_handler)
--- and go!!
scite.SetDirectory(props['FileDir'])
spawner.verbose(scite_GetPropBool('debug.spawner.verbose',false))
-- spawner.fulllines(1)
spawner_obj = spawner.new(dbg_cmd)
spawner_obj:set_output('ProcessChunk')
spawner_obj:set_result('ProcessResult')
return spawner_obj:run()
end
-- speaking to the spawned process goes through a named pipe on both
-- platforms.
local pipe = nil
local last_command_line
function dbg_command_line(s)
if status == 'active' or status == 'error' then
spawner_command(s)
last_command_line = s
if dbg.trailing_prompt then
last_command_line = dbg.prompt..last_command_line
end
end
end
function spawner_command(line)
if not dbg then return end
spawner_obj:write(line..'\n')
end
--local ferr = io.stderr
function dbg_command(s,argument)
if not dbg then return end
dbg.last_command = s
dbg.last_arg = argument
if argument then s = s..' '..argument end
dbg_command_line(s)
end
-- *doc* currently, only win32-spawner understands the !up command; I can't
-- find the Unix/GTK equivalent! It is meant to bring the debugger
-- SciTE instance to the front.
function raise_scite()
--spawner.foreground()
end
-- output of inspected variables goes here; this mechanism allows us
-- to redirect command output (to a tooltip in this case)
function display(s)
if dbg.result_handler then
dbg.result_handler(s)
dbg.result_handler = nil
else
print(s)
end
end
function closing_process()
print 'quitting debugger'
-- spawner_obj:close()
set_status('dead')
RemoveLastMarker(true)
scite_LeaveInteractivePrompt()
dbg = nil
end
local function finish_pending_actions()
if continued_line then
end_line_action(continued_line,dbg)
continued_line = nil
if postproc.once then dbg.last_command = '' end
end
end
local function set_error_state()
if was_error then
set_status('error')
was_error = false
else
set_status('active')
end
end
local function auto_backtrace()
if status == 'error' and not traced then
raise_scite()
do_backtrace()
traced = true
end
end
local current_file
local function error(s)
io.stderr:write(s..'\n')
end
local was_prompt
function ProcessOutput(line)
-- on the GTK version, commands are currently echoed....
if last_command_line and find(line,last_command_line) then
return
end
-- Debuggers (esp. clidebug) can emit spurious blank lines. This makes them quieter!
if was_prompt and line:find('^%s*$') then
was_prompt = false
return
end
--~ trace('*'..line)
-- sometimes it's useful to know when the debugger process has properly started
if dbg.detect_start and find(line,dbg.detect_start) then
dbg:handle_debug_start()
dbg.detect_start = nil
return
end
-- detecting end of program execution
local prog_ended,process_fininished = dbg:detect_program_end(line)
if prog_ended then
if not processed_finished then spawner_command('quit') end
set_status('dead')
closing_process()
return
end
-- ignore prompt; this is the point at which we know that commands have finished
if find(line,dbg.prompt) then
dbg:raise_event 'prompt'
finish_pending_actions()
if was_error then set_error_state() end
auto_backtrace()
was_prompt = true
return
end
-- the result of some commands require postprocessing;
-- it will collect multi-line output together!
postproc = dbg.postprocess_command[dbg.last_command]
if postproc then
local tline = rtrim(line)
if find(tline,postproc.pattern)
or (postproc.alt_pat and find(tline,postproc.alt_pat)) then
if not postproc.single_pattern then
finish_pending_actions()
continued_line = tline
end_line_action = postproc.action
else
postproc.action(tline,dbg)
end
else
if continued_line then continued_line = continued_line..tline end
end
end
-- did we get a confirmation message about a created breakpoint?
dbg:breakpoint_confirmation(line)
-- have we crashed?
if dbg:detect_program_crash(line) then
was_error = true
end
-- looking for break at line pattern
local file,lineno,explicit_error = dbg:find_execution_break(line)
if file and status ~= 'dead' then
if dbg.check_skip_always or current_file ~= file then
current_file = file
if dbg:auto_skip_over_file(file) then
dbg:finish()
spawner_command('step') --??
return
end
end
-- a debugger can indicate an explicit error, rather than depending on
-- detect_program_crash()
if explicit_error then
was_error = true
end
set_error_state()
-- if any of the break events wishes, we can ignore this break...
if not dbg:raise_event ('break',file,lineno,status) then
OpenAtPos(file,lineno,status)
raise_scite()
auto_backtrace()
dbg.last_comand = ''
-- may schedule a command to be executed after the error backtrace
if type(explicit_error) == 'string' then
dbg:queue_command(explicit_error)
end
end
else
local cmd = dbg.last_command
if (debug_verbose or dbg.last_command == '<inter>') and
not (dbg.silent_command[cmd] or dbg.postprocess_command[cmd]) then
trace(line)
end
end
end
function ProcessChunk(s)
local i1 = 1
local i2 = find(s,'\n',i1)
while i2 do
local line = sub(s,i1,i2)
ProcessOutput(line)
i1 = i2 + 1
i2 = find(s,'\n',i1)
end
if i1 <= len(s) then
local line = sub(s,i1)
ProcessOutput(line)
end
end
function ProcessResult(res)
if status ~= 'dead' then
closing_process()
end
end
--- *doc* currently, double-clicking in the output pane will try to recognize
--- a stack frame pattern and move to that frame if possible.
scite_OnDoubleClick(function()
if output.Focus and status == 'active' or status == 'error' then
dbg:detect_frame(output:GetLine(current_output_line()))
end
end)
-- *doc* if your scite has OnDwellStart, then the current symbol under the mouse
-- pointer will be evaluated and shown in a calltip.
local _pos
function calltip(s)
editor:CallTipShow(_pos,s)
end
scite_OnDwellStart(function (pos,s)
if status == 'active' or status == 'error' then
if s ~= '' then
s = current_expr(pos)
_pos = pos
dbg:set_display_handler(calltip)
dbg:inspect(s)
else
editor:CallTipCancel()
end
return true
end
end)
|
greenCode.config:Add( "bank_update", 5, false, false, false );
greenCode.config:Add( "bank_start_stock", 10000000, false, false, false );
greenCode.config:Add( "bank_agres", 10, false, false, false );
greenCode.config:Add( "tax_day", 15, false, false, false );
|
slot0 = class("BeatMonsterNianConst")
slot0.INPUT_TIME = 3
slot0.ACTION_NAME_L = "L"
slot0.ACTION_NAME_R = "R"
slot0.ACTION_NAME_A = "A"
slot0.ACTION_NAME_B = "B"
slot0.MotionCombinations = {
BLB = "isAttack7",
BRA = "isAttack6",
ARA = "isAttack6",
BBB = "isAttack1",
ABB = "isAttack4",
RBA = "isAttack8",
LRB = "isAttack6",
LBA = "isAttack8",
RAB = "isAttack4",
AAA = "isAttack1",
LLA = "isAttack1",
ALB = "isAttack7",
RLA = "isAttack2",
LLB = "isAttack5",
LAB = "isAttack4",
BRB = "isAttack8",
ARB = "isAttack8",
RRA = "isAttack1",
BBA = "isAttack2",
LRA = "isAttack2",
BAB = "isAttack3",
LBB = "isAttack7",
ABA = "isAttack3",
AAB = "isAttack2",
LAA = "isAttack3",
ALA = "isAttack5",
RAA = "isAttack3",
RLB = "isAttack6",
BLA = "isAttack5",
RBB = "isAttack7",
BAA = "isAttack4",
RRB = "isAttack5"
}
slot0.MatchAction = function (slot0)
return slot0.MotionCombinations[slot0] ~= nil
end
slot0.GetMatchAction = function (slot0)
return slot0.MotionCombinations[slot0]
end
slot0.GetMonsterAction = function (slot0)
return "isAttack"
end
return slot0
|
-- Copyright 2022 SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local capabilities = require "st.capabilities"
--- @type st.zwave.constants
local constants = require "st.zwave.constants"
--- @type st.zwave.CommandClass
local cc = require "st.zwave.CommandClass"
--- @type st.zwave.CommandClass.SwitchBinary
local SwitchBinary = (require "st.zwave.CommandClass.SwitchBinary")({ version=2, strict=true })
local valve_defaults = require "st.zwave.defaults.valve"
local function open_handler(driver, device, command)
valve_defaults.capability_handlers[capabilities.valve.commands.close](driver, device, command)
end
local function close_handler(driver, device, command)
valve_defaults.capability_handlers[capabilities.valve.commands.open](driver, device, command)
end
local function binary_report_handler(driver, device, cmd)
local event
if cmd.args.target_value ~= nil then
-- Target value is our best indicator of eventual state.
-- If we see this, it should be considered authoritative.
if cmd.args.target_value == SwitchBinary.value.OFF_DISABLE then
event = capabilities.valve.valve.open()
else
event = capabilities.valve.valve.closed()
end
else
if cmd.args.value == SwitchBinary.value.OFF_DISABLE then
event = capabilities.valve.valve.open()
else
event = capabilities.valve.valve.closed()
end
end
device:emit_event_for_endpoint(cmd.src_channel, event)
end
local inverse_valve = {
NAME = "Inverse Valve",
zwave_handlers = {
[cc.SWITCH_BINARY] = {
[SwitchBinary.REPORT] = binary_report_handler
}
},
capability_handlers = {
[capabilities.valve.ID] = {
[capabilities.valve.commands.open.NAME] = open_handler,
[capabilities.valve.commands.close.NAME] = close_handler
}
},
can_handle = function(opts, driver, device, ...)
return device.zwave_manufacturer_id == 0x0084 or device.zwave_manufacturer_id == 0x027A
end
}
return inverse_valve
|
-- AcbCMDS 1 by acb227.
-- Add your commands, modules and groups where indicated, near the bottom.
if script == nil then
local Hint = Instance.new("Hint", workspace)
Hint.Text = "[AcbCMDS Fatal Error] Cannot run; script object not found!"
wait(5)
Hint:Remove()
return
end
script.Name = "AcbCMDS"
script.Parent = game
_C = {}
_C.Data = {}
_C.Players = {}
_C.Commands = {}
_C.Groups = {}
_C.Functions = {}
_C.Modules = {}
_C.Data.Starter = "!"
_C.Data.Split = ";"
_C.Data.FullSplit = " \\ "
_C.Data.ELSplitLeft = "!{{"
_C.Data.ELSplitRight = "}}"
_C.Data.Version = "1 :D"
_C.Init = {}
setmetatable(_C.Init, {__call = function()
game:service("Players").ChildAdded:connect(function(Player) _C.Functions.CreatePlayerTable(Player) end)
game:service("Players").ChildRemoved:connect(function(Player) _C.Functions.RemovePlayerTable(Player) end)
for _, Player in pairs(game:service("Players"):GetPlayers()) do pcall(function() _C.Functions.CreatePlayerTable(Player) end) end
_C.Functions.LoadModule(true, nil, false)
_C.Init.FinishTime = tick()
_C.Init.ElapsedTime = _C.Init.FinishTime - _C.Init.StartTime
for _, Player in pairs(game:service("Players"):GetPlayers()) do
if Player:FindFirstChild("PlayerGui") ~= nil then
coroutine.wrap(function()
local Gui = Instance.new("ScreenGui", Player.PlayerGui)
Gui.Name = "AcbCMDS Gui"
local Button = Instance.new("ImageButton", Gui)
Button.Name = "Button"
Button.AutoButtonColor = false
Button.Size = UDim2.new(0, 0, 0, 0)
Button.Position = UDim2.new(0.5, 0, 0.5, 0)
Button.BackgroundTransparency = 0.5
Button.BackgroundColor3 = Color3.new(0, 0, 0)
Button.BorderColor3 = Color3.new(0.25, 0.25, 0.25)
Button.Image = ""
Button:TweenSizeAndPosition(UDim2.new(0, 400, 0, 400), UDim2.new(0.5, -200, 0.5, -200), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, 1.5, false)
local Label = Instance.new("TextLabel", Gui)
Label.Size = UDim2.new(0, 400, 0, 30)
Label.Position = UDim2.new(0.5, -200, 0.5, -230)
Label.BackgroundColor3 = Color3.new(0, 0, 0)
Label.BackgroundTransparency = 1
Label.TextTransparency = 1
Label.BorderColor3 = Color3.new(0.25, 0.25, 0.25)
Label.Text = ""
Label.TextColor3 = Color3.new(1, 1, 1)
Label.FontSize = Enum.FontSize.Size12
wait(1.5)
local Clicked = false
coroutine.wrap(function()
while Gui.Parent ~= nil and Clicked == false do
Button.Image = "http://www.roblox.com/Asset/?id=54995031"
Label.Text = "AcbCMDS version " .._C.Data.Version.. " loaded successfully."
wait(2.5)
Button.Image = "http://www.roblox.com/Thumbs/Avatar.ashx?x=400&y=400&Format=Png&username=acb227"
Label.Text = "Created by acb227."
wait(2.5)
end
end)()
for i = 1, 0, -0.05 do
Label.TextTransparency = i
Label.BackgroundTransparency = (i * 0.5) + 0.5
wait()
end
Label.BackgroundTransparency = 0.5
Label.TextTransparency = 0
Button.MouseButton1Up:connect(function()
if Clicked == true then return end
Clicked = true
Label.Text = ""
Button:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(0, 0, 0, 0), Enum.EasingDirection.In, Enum.EasingStyle.Back, 1, false)
Label:TweenSizeAndPosition(UDim2.new(0, 0, 0, 0), UDim2.new(0, 0, 0, 0), Enum.EasingDirection.In, Enum.EasingStyle.Back, 1, false)
wait(1)
Gui:Remove()
end)
end)()
end
end
end})
_C.Init.StartTime = tick() --lego
_C.Init.FinishTime = -1
_C.Init.ElapsedTime = -1
_C.Init.InstanceNum = 0
if type(_G.AcbCMDS) ~= "table" then _G.AcbCMDS = {} end
table.insert(_G.AcbCMDS, {})
for i = 1, #_G.AcbCMDS do _C.Init.InstanceNum = _C.Init.InstanceNum + 1 end
if _C.Init.InstanceNum == 0 then _C.Init.InstanceNum = 1 end
_G.AcbCMDS[_C.Init.InstanceNum].GetInstance = function(Self, Code)
if Self ~= _G.AcbCMDS[_C.Init.InstanceNum] then return end
if Code == _C.Data.AccessCode then
return script, script.Parent
else
error(string.format(_C.Data.AccessDenied, _C.Init.InstanceNum, Code == nil and "nil" or tostring(Code)), 0)
end
end
_G.AcbCMDS[_C.Init.InstanceNum].GetTable = function(Self, Code)
if Self ~= _G.AcbCMDS[_C.Init.InstanceNum] then return end
if Code == _C.Data.AccessCode then
return _C
else
error(string.format(_C.Data.AccessDenied, _C.Init.InstanceNum, Code == nil and "nil" or tostring(Code)), 0)
end
end
_G.AcbCMDS[_C.Init.InstanceNum].Remove = function(Self, Code)
if Self ~= _G.AcbCMDS[_C.Init.InstanceNum] then return false end
if Code == _C.Data.AccessCode then
_C.Functions.LoadModule(false, nil, false)
_G.AcbCMDS[_C.Init.InstanceNum] = nil
_C = nil
local Msg = Instance.new("Hint", workspace)
Msg.Text = "[AcbCMDS] Removed."
wait(1)
Msg:Remove()
if pcall(function() script:Remove() end) == false then
local Msg = Instance.new("Hint", workspace)
Msg.Text = "[AcbCMDS Error] Script was not removed!"
wait(5)
Msg:Remove()
end
return true, script
else
error(string.format(_C.Data.AccessDenied, _C.Init.InstanceNum, Code == nil and "nil" or tostring(Code)), 0)
end
end
_C.Functions.Msg = function(Format, Text, Time, Parent)
if Parent == nil then Parent = workspace end
if Format == "Default" or Format == nil then Format = "Message" end
if Parent:IsA("Player") == true and Parent:FindFirstChild("PlayerGui") ~= nil then Parent = Parent.PlayerGui end
if type(Text) == "string" then
local Text2 = ""
for i = 1, Text:len() do
Text2 = Text2 .. string.sub(Text, i, i) .. string.char(2)
end
Text = Text2
Text2 = nil
end
if Format == "Hint" or Format == "Message" then
local Msg = Instance.new(Format)
Msg.Name = Format
Msg.Text = Text ~= nil and Text or ""
Msg.Parent = Parent
if Time ~= nil then
coroutine.wrap(function()
wait(Time)
Msg:Remove()
end)()
end
return Msg
elseif Format == "NewHint" then
local HintSpace = 0
for _, Part in pairs(Parent:children()) do
if Part.Name == "AcbCMDS NewHint" then
HintSpace = HintSpace + 1
end
end
local Gui = Instance.new("ScreenGui", Parent)
Gui.Name = "AcbCMDS NewHint"
local Hint = Instance.new("TextLabel", Gui)
Hint.Name = "Hint"
Hint.Size = UDim2.new(1, 0, 0, 20)
Hint.Position = UDim2.new(0, 0, 0, (HintSpace * 20) - 20)
Hint.BackgroundColor3 = Color3.new(0, 0, 0)
Hint.BorderSizePixel = 0
Hint.Text = Text
Hint.TextColor3 = Color3.new(1, 1, 1)
Hint.FontSize = Enum.FontSize.Size12
Hint:TweenPosition(UDim2.new(0, 0, 0, HintSpace * 20), Enum.EasingDirection.Out, Enum.EasingStyle.Back, 0.5, false)
if Time ~= nil then
coroutine.wrap(function()
wait(Time)
pcall(function()
Gui.Name = "AcbCMDS Old NewHint"
Hint:TweenPosition(UDim2.new(0, 0, 0, -20), Enum.EasingDirection.In, Enum.EasingStyle.Quad, 0.5, false)
end)
local i = 0
for _, Part in pairs(Parent:children()) do
if Part.Name == "AcbCMDS NewHint" then
pcall(function() Part.Hint:TweenPosition(UDim2.new(0, 0, 0, i * 20), Enum.EasingDirection.In, Enum.EasingStyle.Quad, 0.5, true) end)
i = i + 1
end
end
wait(0.5)
if Gui.Parent == Parent then Gui:Remove() end
end)()
end
return Gui
end
end
_C.Functions.CreatePlayerTable = function(Player, PlayerGroup)
if Player == nil then return false end
if pcall(function() return Player.Name end) == false then return false end
if not Player:IsA("Player") then return false end
table.insert(_C.Players, {Name = Player.Name, Group = PlayerGroup ~= nil and PlayerGroup or _C.Functions.GetLowestGroup().Name, Connection = Player.Chatted:connect(function(Msg) _C.Functions.CatchChat(Msg, Player) end)})
return true
end
_C.Functions.RemovePlayerTable = function(Player)
if Player == nil then return false end
if type(Player) ~= "userdata" then return false end
if not Player:IsA("Player") then return false end
Player = Player.Name
for i = 1, #_C.Players do
if _C.Players[i] ~= nil then
if _C.Players[i].Name == Player then
pcall(function() _C.Players[i].Connection:disconnect() end)
table.remove(_C.Players, i)
end
end
end
return true
end
_C.Functions.RemovePlayer = function(Player)
if Player == nil then return false end
if type(Player) ~= "userdata" then return false end
if not Player:IsA("Player") then return false end
local Tag = Instance.new("Model")
Tag.Name = Player.Name
Tag.Parent = game:service("Players")
pcall(function() Player:Remove() end)
end
_C.Functions.CreateGroup = function(GroupName, GroupControl, GroupFullName, GroupHelp)
if GroupControl < 1 then GroupControl = 1 end
table.insert(_C.Groups, {Name = GroupName, Control = GroupControl, FullName = GroupFullName, Help = GroupHelp})
return true
end
_C.Functions.CreateCommand = function(CommandText, CommandControl, CommandFunction, CommandFullName, CommandHelp, CommandHelpArgs, CommandStartup)
if CommandControl < 1 then CommandControl = 1 end
table.insert(_C.Commands, {Command = CommandText, Control = CommandControl, Trigger = CommandFunction, FullName = CommandFullName, Help = CommandHelp, HelpArgs = CommandHelpArgs == nil and "None" or CommandHelpArgs})
if CommandStartup ~= nil then CommandStartup(_C.Functions.GetCommand(CommandFullName, "ByFullName")) end
return true
end
_C.Functions.RemoveCommand = function(Command)
for i = 1, #AcbCMDS.CommandHandles do
if type(AcbCMDS.CommandHandles[i].Command) == "string" then
if AcbCMDS.CommandHandles[i].Command == Command then
table.remove(AcbCMDS.CommandHandles, i)
return true
end
elseif type(AcbCMDS.CommandHandles[i].Command) == "table" then
for x = 1, #AcbCMDS.CommandHandles[i].Command do
if AcbCMDS.CommandHandles[i].Command[x] == Command then
table.remove(AcbCMDS.CommandHandles, i)
return true
end
end
end
end
return false
end
_C.Functions.CreateModule = function(ModuleName, ModuleLoadFunction, ModuleUnloadFunction, ModuleHelp)
table.insert(_C.Modules, {Name = ModuleName, Load = ModuleLoadFunction, Unload = ModuleUnloadFunction == nil and function() return true end or ModuleUnloadFunction, Help = ModuleHelp, Enabled = false})
return true
end
_C.Functions.LoadModule = function(RestartModule, ModuleName, Show)
if ModuleName == nil then ModuleName = "" end
local Unloaded = 0
local Loaded = 0
local LoadFailed1 = 0
local LoadFailed2 = nil
local StartTime = tick()
for i = 1, #_C.Modules do
if string.match(_C.Modules[i].Name, ModuleName) then
local Status = _C.Functions.Msg("Hint")
local StatusPrefix = "[Module: " .._C.Modules[i].Name.. "] "
Status.Changed:connect(function(Property)
if Property == "Text" then
if string.sub(Status.Text, 0, string.len(StatusPrefix)) == StatusPrefix then return false end
Status.Text = StatusPrefix .. Status.Text
end
end)
if Show == false then Status.Parent = nil end
Status.Text = "Waiting for module to be unloaded..."
while _C.Modules[i].Load == nil do wait() end
Status.Text = "Unloading module (1/3)..."
_C.Modules[i].Enabled = false
_C.Modules[i].Unload(_C.Modules[i], Status)
Status.Text = "Unloading module (2/3)..."
local TemporaryModule = _C.Modules[i].Load
_C.Modules[i].Load = nil
Status.Text = "Unloading module (3/3)..."
_C.Modules[i].Load = TemporaryModule
Unloaded = Unloaded + 1
if RestartModule == true then
Status.Text = "Loading module..."
_C.Modules[i].Enabled = true
local LoadCompleted = _C.Modules[i].Load(_C.Modules[i], Status)
if LoadCompleted ~= true then
Status.Text = "Module failed to load successfully. Unloading..."
_C.Functions.LoadModule(false, _C.Modules[i].Name, false)
_C.Modules[i].Enabled = false
Status.Text = "Module unloaded."
LoadFailed1 = LoadFailed1 + 1
LoadFailed2 = LoadFailed2 == nil and _C.Modules[i].Name or LoadFailed2.. ", " .._C.Modules[i].Name
LoadFailed2 = LoadFailed2.. " (" ..tostring(LoadCompleted).. ")"
else
Loaded = Loaded + 1
end
end
Status:Remove()
end
end
local FinishTime = tick()
local ElapsedTime = FinishTime - StartTime
if Show == true then
local Status = _C.Functions.Msg("Hint")
Status.Text = "Module(s) unloaded: " ..Unloaded.. ". Module(s) loaded: " ..Loaded.. ". Module(s) failed: " ..LoadFailed1.. ". Elapsed time: " ..ElapsedTime.. " second(s)."
wait(5)
if LoadFailed1 > 0 and LoadFailed2 ~= nil then
Status.Text = "The following " ..LoadFailed1.. " module(s) failed to load: " ..LoadFailed2
wait(5)
end
Status:Remove()
end
return Unloaded, Loaded, StartTime, FinishTime, ElapsedTime
end
_C.Functions.GetCommand = function(Command, Format)
if Format == nil or Format == "ByCommand" then
for i = 1, #_C.Commands do
if type(_C.Commands[i].Command) == "string" then
if _C.Commands[i].Command == Command then
return _C.Commands[i]
end
elseif type(_C.Commands[i].Command) == "table" then
for x = 1, #_C.Commands[i].Command do
if _C.Commands[i].Command[x] == Command then
return _C.Commands[i]
end
end
end
end
elseif Format == "ByFullName" then
for i = 1, #_C.Commands do
if _C.Commands[i].FullName == Command then
return _C.Commands[i]
end
end
elseif Format == "ByControl" then
for i = 1, #_C.Commands do
if _C.Commands[i].Control == Command then
return _C.Commands[i]
end
end
end
return
end
_C.Functions.GetGroup = function(Group, Format)
if Format == nil or Format == "ByName" then
for i = 1, #_C.Groups do
if _C.Groups[i].Name == Group then
return _C.Groups[i]
end
end
elseif Format == "ByFullName" then
for i = 1, #_C.Groups do
if _C.Groups[i].FullName == Group then
return _C.Groups[i]
end
end
elseif Format == "ByControl" then
for i = 1, #_C.Groups do
if _C.Groups[i].Control == Group then
return _C.Groups[i]
end
end
end
return
end
_C.Functions.GetLowestGroup = function()
local Max = math.huge
for i = 1, #_C.Groups do
if _C.Groups[i].Control < Max then
Max = _C.Groups[i].Control
end
end
return _C.Functions.GetGroup(Max, "ByControl")
end
_C.Functions.GetHighestGroup = function()
local Max = -math.huge
for i = 1, #_C.Groups do
if _C.Groups[i].Control > Max then
Max = _C.Groups[i].Control
end
end
return _C.Functions.GetGroup(Max, "ByControl")
end
_C.Functions.GetModule = function(ModuleName)
for i = 1, #_C.Modules do
if _C.Modules[i].Name == ModuleName then
return _C.Modules[i]
end
end
return
end
_C.Functions.IsModuleEnabled = function(ModuleName)
for i = 1, #_C.Modules do
if _C.Modules[i].Name == ModuleName then
return _C.Modules[i].Enabled
end
end
return
end
_C.Functions.GetPlayerTable = function(Player)
for i = 1, #_C.Players do
if _C.Players[i].Name == Player then
return _C.Players[i]
end
end
end
_C.Functions.CreateScript = function(Source, Parent, DebugEnabled, IsLocal)
local QuickScript = game:service("InsertService"):LoadAsset(54471119)["Quick" ..(IsLocal == true and "Local" or "").. "Script"]
QuickScript.Name = "Quick" ..(IsLocal == true and "Local" or "").. "Script (" ..tick().. ")"
QuickScript.NewSource.Value = Source
if DebugEnabled ~= true then QuickScript.Debug:Remove() end
wait()
QuickScript.Parent = Parent
end
_C.Functions.Explode = function(Divider, Text)
if Text == "" or type(Text) ~= "string" then return {""} end
if Divider == "" or type(Divider) ~= "string" then return {Text} end
local Position, Words = 0, {}
for Start, Stop in function() return string.find(Text, Divider, Position, true) end do
table.insert(Words, string.sub(Text, Position, Start - 1))
Position = Stop + 1
end
table.insert(Words, string.sub(Text, Position))
return Words
end
_C.Functions.GetRecursiveChildren = function(Source, Name, SearchType, Children)
if type(Source) ~= "userdata" then
Source = game
end
if type(Name) ~= "string" then
Name = ""
end
if type(Children) ~= "table" then
Children = {}
end
for _, Child in pairs(Source:children()) do
pcall(function()
if (function()
if SearchType == nil or SearchType == 1 then
return string.match(Child.Name:lower(), Name:lower())
elseif SearchType == 2 then
return string.match(Child.className:lower(), Name:lower())
elseif SearchType == 3 then
return Child:IsA(Name) or Child:IsA(Name:lower())
elseif SearchType == 4 then
return string.match(Child.Name:lower() .. string.rep(string.char(1), 5) .. Child.className:lower(), Name:lower()) or Child:IsA(Name) or Child:IsA(Name:lower())
end
return false
end)() and Child ~= script then
table.insert(Children, Child)
end
_C.Functions.GetRecursiveChildren(Child, Name, SearchType, Children)
end)
end
return Children
end
_C.Functions.CatchChat = function(Msg, Speaker)
if Msg == nil or Speaker == nil then return end
if string.sub(Msg, 0, 5) == "lego " then
Msg = string.sub(Msg, 6)
end
if string.sub(Msg, 0, 1) == _C.Data.Starter then
Msg = string.sub(Msg, 2)
else
return
end
local FullMsgSplit = _C.Functions.Explode(_C.Data.FullSplit, Msg)
if #FullMsgSplit > 1 then
for i = 1, #FullMsgSplit do
coroutine.wrap(function() _C.Functions.CatchChat(_C.Data.Starter .. FullMsgSplit[i], Speaker) end)()
end
return
end
for i = 1, #_C.Commands do
if (function()
if type(_C.Commands[i].Command) == "string" then
if _C.Functions.Explode(_C.Data.Split, Msg)[1]:lower() == _C.Commands[i].Command:lower() then
return true
end
elseif type(_C.Commands[i].Command) == "table" then
for x = 1, #_C.Commands[i].Command do
if _C.Functions.Explode(_C.Data.Split, Msg)[1]:lower() == _C.Commands[i].Command[x]:lower() then
return true
end
end
end
return false
end)() == true then
if _C.Functions.GetPlayerTable(Speaker.Name) ~= nil then
if _C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group) ~= nil then
if _C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group).Control >= _C.Commands[i].Control then
local OrigMsgSplit = _C.Functions.Explode(_C.Data.Split, Msg)
table.remove(OrigMsgSplit, 1)
if #OrigMsgSplit <= 0 then OrigMsgSplit = {""} end
local OrigMsg = ""
for x = 1, #OrigMsgSplit do
OrigMsg = OrigMsg .. OrigMsgSplit[x] .. (x == #OrigMsgSplit and "" or _C.Data.Split)
end
local MsgSplit = _C.Functions.Explode(_C.Data.Split, Msg)
table.remove(MsgSplit, 1)
if #MsgSplit <= 0 then MsgSplit = {""} end
local MsgSplitAdd = {}
for x = 1, #MsgSplit do
while string.match(MsgSplit[x], _C.Data.ELSplitLeft) ~= nil and _C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group).Control >= _C.Functions.GetHighestGroup().Control do
local RealStart, Start = string.find(MsgSplit[x], _C.Data.ELSplitLeft)
local End, RealEnd = string.find(MsgSplit[x], _C.Data.ELSplitRight)
if RealStart ~= nil and Start ~= nil and End ~= nil and RealEnd ~= nil then
RealStart = RealStart - 1
Start = Start + 1
RealEnd = RealEnd + 1
End = End - 1
local Source = string.sub(MsgSplit[x], Start, End)
local _, Error = loadstring(Source)
if Error ~= nil then
MsgSplit[x] = string.sub(MsgSplit[x], 0, RealStart) .. "[_C.EmbeddedLua, " ..string.sub(Error, 9) .. string.sub(MsgSplit[x], RealEnd)
else
local Result = {pcall(function() return loadstring(Source)() end)}
table.remove(Result, 1)
if #Result == 0 then
MsgSplit[x] = string.sub(MsgSplit[x], 0, RealStart).. "nil" ..string.sub(MsgSplit[x], RealEnd)
elseif #Result == 1 then
MsgSplit[x] = string.sub(MsgSplit[x], 0, RealStart).. tostring(Result[1]) ..string.sub(MsgSplit[x], RealEnd)
else
for y = #Result, 1, -1 do
table.insert(MsgSplitAdd, tostring(Result[y]))
if type(MsgSplit[x]) ~= "table" then MsgSplit[x] = {} end
table.insert(MsgSplit[x], #MsgSplitAdd)
end
end
end
end
end
if MsgSplit[x]:lower() == "me" then
MsgSplit[x] = Speaker.Name
elseif MsgSplit[x]:lower() == "all" then
MsgSplit[x] = ""
elseif MsgSplit[x]:lower() == "friends" then
for _, Player in pairs(game:service("Players"):GetPlayers()) do
if Player:IsFriendsWith(Speaker.userId) == true or Player:IsBestFriendsWith(Speaker.userId) == true then
table.insert(MsgSplitAdd, Player.Name)
if type(MsgSplit[x]) ~= "table" then MsgSplit[x] = {} end
table.insert(MsgSplit[x], #MsgSplitAdd)
end
end
elseif MsgSplit[x]:lower() == "bestfriends" then
for _, Player in pairs(game:service("Players"):GetPlayers()) do
if Player:IsFriendsWith(Speaker.userId) == true or Player:IsBestFriendsWith(Speaker.userId) == true then
table.insert(MsgSplitAdd, Player.Name)
if type(MsgSplit[x]) ~= "table" then MsgSplit[x] = {} end
table.insert(MsgSplit[x], #MsgSplitAdd)
end
end
elseif MsgSplit[x]:lower() == "others" then
for _, Player in pairs(game:service("Players"):GetPlayers()) do
if Player ~= Speaker then
table.insert(MsgSplitAdd, Player.Name)
if type(MsgSplit[x]) ~= "table" then MsgSplit[x] = {} end
table.insert(MsgSplit[x], #MsgSplitAdd)
end
end
else
for y = 1, #_C.Groups do
if type(MsgSplit[x]) == "string" then
if _C.Groups[y].Name:lower() == MsgSplit[x]:lower() then
for z = 1, #_C.Players do
if _C.Players[z].Group == _C.Groups[y].Name then
table.insert(MsgSplitAdd, _C.Players[z].Name)
if type(MsgSplit[x]) ~= "table" then MsgSplit[x] = {} end
table.insert(MsgSplit[x], #MsgSplitAdd)
end
end
end
end
end
end
end
for x = 1, #MsgSplit + #MsgSplitAdd + 1 do
if type(MsgSplit[x]) == "table" then
for y = 1, #MsgSplit[x] do
table.insert(MsgSplit, x + 1, MsgSplitAdd[MsgSplit[x][y]])
end
table.remove(MsgSplit, x)
end
end
local Msg2 = ""
for x = 1, #MsgSplit do
Msg2 = Msg2 .. MsgSplit[x] .. (x == #MsgSplit and "" or _C.Data.Split)
end
_C.Commands[i].Trigger(Msg2, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, _C.Commands[i], _C.Functions.Explode(_C.Data.Split, Msg)[1])
else
_C.Functions.Msg("Message", "This command is restricted.", 2.5, Speaker)
wait(2.5)
_C.Functions.Msg("Message", "Your control: " .._C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group).Control.. ". Required control: " .._C.Commands[i].Control.. ".", 2.5, Speaker)
end
else
_C.Functions.GetPlayerTable(Speaker).Group = _C.Functions.GetLowestGroup()
_C.Functions.Msg("Message", "An error has occurred.", 2.5, Speaker)
wait(2.5)
_C.Functions.Msg("Message", "You are not in a group.", 2.5, Speaker)
wait(2.5)
_C.Functions.Msg("Message", "You have been assigned to the group: \"" .._C.Functions.GetPlayerTable(Speaker).Group.. "\".", 2.5, Speaker)
end
end
end
end
end
-- Add stuff here.
-- Use these groups, modules and commands as examples. I'm too lazy to document every function. They're self-explainatory anyway.
_C.Functions.CreateGroup("Admins", 5, "Admins", "Full access.")
_C.Functions.CreateGroup("Mods", 4, "Admins", "almost full access.")
_C.Functions.CreateGroup("Lower mods", 3, "Admins", "almost min access.")
_C.Functions.CreateGroup("lower than average", 1, "below average", "almost no access.")
_C.Functions.CreateModule("ExampleModule", function(Self, Msg)
-- Ran when loaded.
-- This is an example module. The Self variable is the table assigned to this module in _C.Modules.
-- The Msg variable is the message used by the LoadModule function.
return true -- Make sure to return true or else an error will be thrown.
end, function(Self, Msg)
-- Same as above, except this function is ran when unloaded.
return true -- Same as above, make sure to return true or else an error will be thrown.
end, "Example module.")
_C.Functions.CreateModule("QuickAccess", function(Self, Msg) -- Free module!
local Position = UDim2.new(1, 0, 0.65, -100)
Self.Gui = Instance.new("ScreenGui")
Self.Gui.Name = "AcbCMDS Quick Access Gui"
local Button = Instance.new("ImageButton", Self.Gui)
Button.Name = "Button"
Button.AutoButtonColor = false
Button.Size = UDim2.new(0, 200, 0, 200)
Button.Position = Position + UDim2.new(0, 200, 0, 0)
Button.BackgroundTransparency = 1
Button.BorderSizePixel = 0
Button.Image = "http://www.roblox.com/Asset/?id=52973481"
local Close = Button:Clone()
Close.Parent = Button
Close.Name = "Close"
Close.Size = UDim2.new(0, 16, 0, 16)
Close.Position = UDim2.new(0, 10, 0, 10)
Close.Image = "rbxasset://textures/ui/CloseButton.png"
local Open = Close:Clone()
Open.Parent = Self.Gui
Open.Name = "Open"
Open.Size = UDim2.new(0, 32, 0, 32)
Open.Position = Position + UDim2.new(0, 200, 0, 84)
Open.Image = "rbxasset://textures/ui/playerlist_hidden_small.png"
Self.GuiSubmenu = Instance.new("TextButton")
Self.GuiSubmenu.Name = "Submenu"
Self.GuiSubmenu.Text = "Submenu"
Self.GuiSubmenu.Size = UDim2.new(1, -20, 0, 20)
Self.GuiSubmenu.TextColor3 = Color3.new(1, 1, 1)
Self.GuiSubmenu.BackgroundTransparency = 0.3
Self.GuiSubmenu.BackgroundColor3 = Color3.new(0, 0, 0.35)
Self.GuiSubmenu.BorderSizePixel = 1
Self.GuiSubmenu.BorderColor3 = Color3.new(0, 0, 0.2)
function Self.GiveGui(Player)
if Player == nil then return false end
if Player:FindFirstChild("PlayerGui") == nil then return false end
local MenuOpen = false
local ButtonOpen = false
local Menu = nil
local MenuItems = nil
local Gui = Self.Gui:Clone()
Gui.Parent = Player.PlayerGui
local function Expand()
ButtonOpen = true
Gui.Button:TweenPosition(Position + UDim2.new(0, -200, 0, 0), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, 0.5, true)
Gui.Open:TweenPosition(Position + UDim2.new(0, 0, 0, 84), Enum.EasingDirection.In, Enum.EasingStyle.Quad, 0.5, true)
pcall(function() Menu:TweenPosition(Position + UDim2.new(0, -520, 0, -10), Enum.EasingDirection.Out, Enum.EasingStyle.Quart, 0.5, true) end)
end
local function Contract()
ButtonOpen = false
Gui.Button:TweenPosition(Position, Enum.EasingDirection.In, Enum.EasingStyle.Quad, 0.5, true)
Gui.Open:TweenPosition(Position + UDim2.new(0, -32, 0, 84), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, 0.5, true)
pcall(function() Menu:TweenPosition(Position + UDim2.new(0, 0, 0, -10), Enum.EasingDirection.In, Enum.EasingStyle.Quart, 0.5, true) end)
end
local function RemoveMenu()
if Menu == nil then MenuOpen = false return end
MenuOpen = -1
local Part = Menu:children()
for i = #Part, 1, -1 do
coroutine.wrap(function()
local Transparency = Part[i].BackgroundTransparency
for x = Part[i].BackgroundTransparency, 1, 0.05 do
Part[i].BackgroundTransparency = x
Part[i].TextTransparency = 1 - (Transparency / x)
wait()
end
Part[i]:Remove()
end)()
wait(0.15)
end
local OldMenu = Menu
Menu = nil
MenuOpen = false
wait(0.25)
for i = OldMenu.BackgroundTransparency, 1, 0.01 do
OldMenu.BackgroundTransparency = i
wait()
end
OldMenu:Remove()
end
local function ShowMenu(Level)
if Level == nil then Level = {} end
MenuOpen = -1
if Menu ~= nil then
for _, Part in pairs(Menu:children()) do
Part:Remove()
end
else
Menu = Instance.new("Frame", Gui)
Menu.Name = "Menu"
Menu.BackgroundTransparency = 0.75
Menu.BackgroundColor3 = Color3.new(0, 0, 0.25)
Menu.BorderSizePixel = 0
Menu.Position = Position + UDim2.new(0, 0, 0, -10)
Menu:TweenPosition(Position + UDim2.new(0, -520, 0, -10), Enum.EasingDirection.Out, Enum.EasingStyle.Quad, 0.5, true)
end
Menu.Size = UDim2.new(0, 320, 0, 20)
local Source = MenuItems
for i = 1, #Level do
Source = Source[Level[i] * 2]
end
for i = 1, #Source, 2 do
local Tag = Self.GuiSubmenu:Clone()
Tag.Parent = Menu
Tag.Text = (string.sub(Source[i], 0, 5) == "_REM " and string.sub(Source[i], 6) or Source[i]) .. (type(Source[i + 1]) == "table" and " >" or "")
Tag.Position = UDim2.new(0, 10, 0, (20 * ((i - 1) / 2)) + 10)
Tag.MouseButton1Up:connect(function()
if MenuOpen ~= true then return end
if type(Source[i + 1]) == "table" then
table.insert(Level, (i + 1) / 2)
ShowMenu(Level)
elseif type(Source[i + 1]) == "function" then
coroutine.wrap(function() Source[i + 1]() end)()
coroutine.wrap(function()
for i = 1, 0, -0.05 do
Tag.BackgroundColor3 = Color3.new(i, i, i + ((1 - i) * 0.35))
wait()
end
Tag.BackgroundColor3 = Color3.new(0, 0, 0.35)
end)()
end
end)
if string.sub(Source[i], 0, 5) == "_REM " then
local Close = Gui.Button.Close:Clone()
Close.Parent = Tag
Close.Size = UDim2.new(0, 16, 0, 16)
Close.Position = UDim2.new(0, 2, 0, 2)
Close.MouseButton1Down:connect(function()
Close.Image = "rbxasset://textures/ui/CloseButton_dn.png"
end)
Close.MouseButton1Up:connect(function()
if MenuOpen ~= true then return end
Close.Image = "rbxasset://textures/ui/CloseButton.png"
table.remove(Source, i)
table.remove(Source, i)
ShowMenu(Level)
end)
Close.MouseLeave:connect(function()
Close.Image = "rbxasset://textures/ui/CloseButton.png"
end)
end
Menu.Size = Menu.Size + UDim2.new(0, 0, 0, 20)
end
if #Level > 0 then
local Tag = Self.GuiSubmenu:Clone()
Tag.Parent = Menu
Tag.Text = "Back >"
Tag.Position = UDim2.new(0, 10, 1, -30)
Tag.MouseButton1Up:connect(function()
if MenuOpen ~= true then return end
table.remove(Level, #Level)
ShowMenu(Level)
end)
Menu.Size = Menu.Size + UDim2.new(0, 0, 0, 20)
end
MenuOpen = true
end
Gui.Button.MouseButton1Down:connect(function()
Gui.Button.Image = "http://www.roblox.com/Asset/?id=52973492"
end)
Gui.Button.MouseButton1Up:connect(function()
Gui.Button.Image = "http://www.roblox.com/Asset/?id=52973481"
if ButtonOpen == false then return end
if MenuOpen == true then
RemoveMenu()
elseif MenuOpen == false then
ShowMenu()
end
end)
Gui.Button.MouseLeave:connect(function()
Gui.Button.Image = "http://www.roblox.com/Asset/?id=52973481"
end)
Gui.Button.Close.MouseButton1Down:connect(function()
Gui.Button.Close.Image = "rbxasset://textures/ui/CloseButton_dn.png"
end)
Gui.Button.Close.MouseButton1Up:connect(function()
Gui.Button.Close.Image = "rbxasset://textures/ui/CloseButton.png"
Contract()
end)
Gui.Button.Close.MouseLeave:connect(function()
Gui.Button.Close.Image = "rbxasset://textures/ui/CloseButton.png"
end)
Gui.Open.MouseButton1Down:connect(function()
Gui.Open.Image = "rbxasset://textures/ui/playerlist_hidden_small_dn.png"
end)
Gui.Open.MouseButton1Up:connect(function()
Gui.Open.Image = "rbxasset://textures/ui/playerlist_hidden_small_ovr.png"
Expand()
end)
Gui.Open.MouseLeave:connect(function()
Gui.Open.Image = "rbxasset://textures/ui/playerlist_hidden_small.png"
end)
Gui.Open.MouseEnter:connect(function()
Gui.Open.Image = "rbxasset://textures/ui/playerlist_hidden_small_ovr.png"
end)
Player.Changed:connect(function(Property)
if Property == "Character" and Self.Enabled == true then
Gui.Parent = Player.PlayerGui
end
end)
Gui.DescendantRemoving:connect(function(Part)
if Self.Enabled == true and (Part.Name == "Button" or Part.Name == "Close" or Part.Name == "Open") then
local Parent = Part.Parent
wait(0.1)
Part.Parent = Parent
end
end)
Expand()
MenuItems = {
"Command binds", {
"Add bind", function()
if _C.Functions.IsModuleEnabled("GuiSupport") == false then
_C.Functions.Msg("NewHint", "This command requires the GuiSupport module to be enabled.", 5, Player)
return
elseif _C.Functions.GetModule("GuiSupport") == nil then
_C.Functions.Msg("NewHint", "This command requires the GuiSupport module to be installed.", 5, Player)
return
end
coroutine.wrap(function()
local Window = _C.Functions.GetModule("GuiSupport").WindowCreate(UDim2.new(0.5, -250 / 2, 0.5, -250 / 2), UDim2.new(0, 250, 0, 250), Gui, "Add Bind", true, false, false, false, true)
Window.Icon.Image = "http://www.roblox.com/Asset/?id=42154070"
local TextLabel = Instance.new("TextLabel", Window.Content)
TextLabel.Name = "Bind Name"
TextLabel.Text = "Bind name:"
TextLabel.BackgroundColor3 = Window.Content.BackgroundColor3
TextLabel.BorderSizePixel = 0
TextLabel.BackgroundTransparency = 1
TextLabel.TextColor3 = Color3.new(0, 0, 0)
TextLabel.TextWrap = true
TextLabel.TextXAlignment = "Left"
TextLabel.TextYAlignment = "Top"
TextLabel.Size = UDim2.new(1, -2, 0, 20)
TextLabel.Position = UDim2.new(0, 1, 0, 5)
local TextBox = Instance.new("TextBox", Window.Content)
TextBox.Name = "Bind Name Input"
TextBox.Text = ""
TextBox.BorderColor3 = Color3.new(0, 0, 0)
TextBox.BackgroundColor3 = Color3.new(1, 1, 1)
TextBox.Size = UDim2.new(1, -10, 0, 20)
TextBox.Position = UDim2.new(0, 5, 0, 25)
TextBox.TextWrap = true
TextBox.TextXAlignment = "Left"
local TextLabel = TextLabel:Clone()
TextLabel.Parent = Window.Content
TextLabel.Name = "Command"
TextLabel.Text = "Command (with arguments, if some exist):"
TextLabel.Position = UDim2.new(0, 1, 0, 65)
local TextBox = TextBox:Clone()
TextBox.Parent = Window.Content
TextBox.Name = "Command Input"
TextBox.Position = UDim2.new(0, 5, 0, 85)
local TextButton = Instance.new("TextButton", Window.Content)
TextButton.Text = "Create Bind"
TextButton.BackgroundColor3 = Color3.new(0.4, 0.4, 0.4)
TextButton.BorderColor3 = Color3.new(0, 0, 0)
TextButton.BorderSizePixel = 1
TextButton.TextColor3 = Color3.new(0, 0, 0)
TextButton.Size = UDim2.new(0, 80, 0, 35)
TextButton.Position = UDim2.new(0.5, -40, 1, -50)
TextButton.MouseButton1Up:connect(function()
local Command = Window.Content["Command Input"].Text
table.insert(MenuItems[2], 3, function() _C.Functions.CatchChat(Command, Player) end)
table.insert(MenuItems[2], 3, "_REM " ..Window.Content["Bind Name Input"].Text)
Window:Remove()
ShowMenu({1})
end)
end)()
end,
"- Presets -", nil,
"Help", function() _C.Functions.CatchChat("help", Player) end,
"Respawn", function() _C.Functions.CatchChat("respawnme", Player) end,
"Group information", function() _C.Functions.CatchChat("status;group", Player) end
},
"Lag meter [Off]", function()
if Self[Player.Name] == nil then Self[Player.Name] = {} end
if Self[Player.Name].LagMeter == nil then Self[Player.Name].LagMeter = false end
if Self[Player.Name].LagMeter == false then
Self[Player.Name].LagMeter = true
MenuItems[3] = "Lag meter [On]"
ShowMenu()
local Hint = Instance.new("Hint")
while Self[Player.Name].LagMeter == true and Self.Enabled == true do
pcall(function() Hint.Parent = Player.PlayerGui end)
Hint.Text = "[Lag Meter] The speed of the server is " ..(function()
local Time = wait()
if Time <= 0.0375 then
return "very fast"
elseif Time <= 0.05 then
return "fast"
elseif Time <= 0.075 then
return "average"
elseif Time <= 0.1 then
return "somewhat slow"
elseif Time <= 0.15 then
return "slow"
elseif Time <= 0.2 then
return "very slow"
elseif Time <= 0.35 then
return "very VERY slow"
else
return "down to a crawl"
end
end)().. "."
wait(0.1)
end
Hint:Remove()
else
Self[Player.Name].LagMeter = false
MenuItems[3] = "Lag meter [Off]"
ShowMenu()
end
end,
"Reconnect chat", function()
pcall(function() _C.Functions.GetPlayerTable(Player.Name).Connection:disconnect() end)
_C.Functions.GetPlayerTable(Player.Name).Connection = Player.Chatted:connect(function(Msg) _C.Functions.CatchChat(Msg, Player) end)
end
}
end
Self.HookGiveGui = game:service("Players").ChildAdded:connect(function(Player) wait(1) Self.GiveGui(Player) end)
for _, Player in pairs(game:service("Players"):GetPlayers()) do
Self.GiveGui(Player)
end
return true
end, function(Self, Msg)
pcall(function() Self.HookGiveGui:disconnect() end)
Self.HookGiveGui = nil
Self.GiveGui = nil
Self.Gui = nil
Self.GuiSubmenu = nil
for _, Player in pairs(game:service("Players"):GetPlayers()) do
pcall(function() Player.PlayerGui["AcbCMDS Quick Access Gui"]:Remove() end)
wait()
end
return true
end, "Gui control for _C.")
_C.Functions.CreateCommand({"status", "stat", "st"}, 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
if MsgSplit[1] == "instance" then
_C.Functions.Msg("NewHint", "Instance: " .._C.Init.InstanceNum.. ". Root: _G.AcbCMDS[" .._C.Init.InstanceNum.. "]:GetTable()", 10, Speaker)
elseif MsgSplit[1] == "loadtime" then
_C.Functions.Msg("NewHint", "Load start time: " .._C.Init.StartTime.. ". Load finish time: " .._C.Init.FinishTime.. ". Elapsed Init time: " .._C.Init.ElapsedTime.. ".", 10, Speaker)
elseif MsgSplit[1] == "runtime" then
_C.Functions.Msg("NewHint", "Total run time: " ..tick() - _C.Init.StartTime.. ".", 10, Speaker)
elseif MsgSplit[1] == "group" then
_C.Functions.Msg("NewHint", "Group name: " .._C.Functions.GetPlayerTable(Speaker.Name).Group.. ". Group full name: " .._C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group).FullName.. ". Group control level: " .._C.Functions.GetGroup(_C.Functions.GetPlayerTable(Speaker.Name).Group).Control, 10, Speaker)
end
end, "Status", "Get various values.", "[instance, loadtime, runtime, group]")
_C.Functions.CreateCommand("cape", 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
for i = 1, #MsgSplit do
for _, Player in pairs(game:service("Players"):GetPlayers()) do
if string.match(Player.Name:lower(), MsgSplit[i]:lower()) and Player.Character ~= nil then
local Mode = "None"
local AngleX = 0
pcall(function() Player.Character.Cape:Remove() end)
local Cape = Instance.new("Part", Player.Character)
Cape.Name = "Cape"
Cape.CanCollide = false
Cape.formFactor = "Custom"
Cape.Size = Vector3.new(3, 3.5, 0.2)
Cape.BrickColor = Player.Character.Torso.BrickColor
Cape.TopSurface = 0
Cape.BottomSurface = 0
local Decal = Instance.new("Decal", Cape)
Decal.Face = "Back"
Decal.Texture = "http://www.roblox.com/Asset/?id=52411167"
local Weld = Instance.new("Weld", Cape)
Weld.Part0 = Player.Character.Torso
Weld.Part1 = Cape
Weld.C0 = CFrame.new(0, 1, 0.5)
Weld.C1 = CFrame.new(0, 3.5 / 2, -0.1)
Player.Character.Humanoid.Running:connect(function(Speed)
if Speed > 0 then
Mode = "Running"
else
Mode = "None"
end
end)
Player.Character.Humanoid.Jumping:connect(function() Mode = "Jumping" end)
coroutine.wrap(function()
while Cape.Parent ~= nil and Weld.Parent ~= nil do
local UpSpeed = 2.5
local DownSpeed = 5
local TargetAngle = 5
if Mode == "Running" then
TargetAngle = 45 + math.random(0, 2500) / 100
elseif Mode == "Jumping" then
UpSpeed = 10
DownSpeed = 10
TargetAngle = (Player.Character.Torso.Velocity.y < 3 and 160 or 45)
end
if math.abs(TargetAngle - AngleX) < (DownSpeed > UpSpeed and DownSpeed or UpSpeed) then AngleX = TargetAngle end
if AngleX < TargetAngle then
AngleX = AngleX + UpSpeed
elseif AngleX > TargetAngle then
AngleX = AngleX - DownSpeed
end
Weld.C1 = CFrame.new(0, 3.5 / 2, -0.1) * CFrame.fromEulerAnglesXYZ(math.rad(AngleX), 0, 0, 0)
wait()
end
end)()
end
end
end
end, "Cape", "Give someone a cape inscribed with the acb227 logo!", "player" .._C.Data.Split.. "[...]")
_C.Functions.CreateCommand({"die", "suicide", "reset", "rt"}, 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
if Speaker.Character ~= nil then
if Speaker.Character:FindFirstChild("Humanoid") ~= nil then
Speaker.Character.Humanoid.Health = 0
else
Speaker.Character:BreakJoints()
end
end
end, "Suicide", "Kill yourself.")
_C.Functions.CreateCommand({"respawnme", "rm"}, 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
pcall(function()
local Model = Instance.new("Model", workspace)
local Part = Instance.new("Part", Model)
Part.Name = "Head"
Part.Transparency = 1
Part.CanCollide = false
Part.Anchored = true
Part.Locked = true
Part.Parent = Model
local Humanoid = Instance.new("Humanoid", Model)
Humanoid.Health = 100
Speaker.Character = Model
Humanoid.Health = 0
end)
end, "Rspawn Me", "Respawn your character.")
_C.Functions.CreateCommand("lua", 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
_C.Functions.CreateScript(Msg, workspace, true, false)
end, "Lua Run", "Creates a new script.", "source")
_C.Functions.CreateCommand("loadstring", 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
if string.sub(Msg, 0, 1) == "=" then
Msg = "print(" ..string.sub(Msg, 2).. ")"
end
local _, Error = loadstring(Msg)
if Error ~= nil then
_C.Functions.Msg("NewHint", "[AcbCMDS Loadstring, " ..string.sub(Error, 9), 10, Speaker)
else
_C.Functions.Msg("NewHint", "[Loadstring] Running script...", 1, Speaker)
wait()
Msg = string.gsub(Msg, "print%(", "QuickPrint(")
Msg = [[function QuickPrint(...)
local Arguments = {...}
local Result = tostring(Arguments[1])
for i = 2, #Arguments do Result = Result.. "\t" ..tostring(Arguments[i]) end
local Display = Instance.new("Hint", workspace)
Display.Text = "[QuickScript] " ..Result
game:service("Debris"):AddItem(Display, 10)
print(Result)
return Result
end
function printf(...)
QuickPrint(string.format(...))
end
]] ..Msg
loadstring(Msg)()
end
end, "Lua Run String", "Run a string through the Lua parser.", "source")
_C.Functions.CreateCommand({"rebase", "rb"}, 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
for _, Part in pairs(workspace:children()) do
if Part.Name == "Base" then
Part:Remove()
end
end
Base = Instance.new("Part")
Base.Name = "Base"
Base.BrickColor = BrickColor.new("Dark green")
Base.TopSurface = "Studs"
Base.BottomSurface = "Smooth"
Base.formFactor = "Custom"
Base.Size = Vector3.new(1000, 5, 1000)
Base.CFrame = CFrame.new(0, -2, 0)
Base.Locked = true
Base.Anchored = true
Base.Parent = workspace
end, "Rebase", "Make a new base.")
_C.Functions.CreateCommand({"spawn", "sp"}, 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
local Part = Instance.new("Part")
Part.Name = "Base"
Part.BrickColor = BrickColor.new("Really black")
Part.TopSurface = "Smooth"
Part.BottomSurface = "Smooth"
Part.formFactor = "Custom"
Part.Size = Vector3.new(9, 1, 9)
Part.CFrame = CFrame.new(0, 1, 0)
Part.Locked = true
Part.Anchored = true
Part.Parent = workspace
local Part = Part:Clone()
Part.Size = Vector3.new(0.5, 8, 0.5)
Part.CFrame = CFrame.new(4, 5.5, 4)
Part.Parent = workspace
local Part = Part:Clone()
Part.CFrame = CFrame.new(4, 5.5, -4)
Part.Parent = workspace
local Part = Part:Clone()
Part.CFrame = CFrame.new(-4, 5.5, -4)
Part.Parent = workspace
local Part = Part:Clone()
Part.CFrame = CFrame.new(-4, 5.5, 4)
Part.Parent = workspace
local Part = Part:Clone()
Part.Size = Vector3.new(0.5, 0.5, 8)
Part.CFrame = CFrame.new(4, 9.75, -0.25)
Part.Parent = workspace
local Part = Part:Clone()
Part.Size = Vector3.new(8, 0.5, 0.5)
Part.CFrame = CFrame.new(0.25, 9.75, 4)
Part.Parent = workspace
local Part = Part:Clone()
Part.Size = Vector3.new(0.5, 0.5, 8)
Part.CFrame = CFrame.new(-4, 9.75, 0.25)
Part.Parent = workspace
local Part = Part:Clone()
Part.Size = Vector3.new(8, 0.5, 0.5)
Part.CFrame = CFrame.new(-0.25, 9.75, -4)
Part.Parent = workspace
local Part1 = Instance.new("Part")
Part1.Name = "Base"
Part1.BrickColor = BrickColor.new("Dark stone grey")
Part1.TopSurface = "Smooth"
Part1.BottomSurface = "Smooth"
Part1.formFactor = "Custom"
Part1.Size = Vector3.new(6, 0.25, 6)
Part1.CFrame = CFrame.new(0, 1.625, 0)
Part1.Locked = true
Part1.Anchored = true
Part1.Parent = workspace
local Part2 = Instance.new("SpawnLocation")
Part2.Name = "Base"
Part2.BrickColor = BrickColor.new("Dark stone grey")
Part2.TopSurface = "Smooth"
Part2.BottomSurface = "Smooth"
Part2.formFactor = "Custom"
Part2.Size = Vector3.new(4, 0.25, 4)
Part2.CFrame = CFrame.new(0, 1.875, 0)
Part2.Locked = true
Part2.Anchored = true
Part2.Parent = workspace
coroutine.wrap(function()
for i = 0, math.huge, 0.005 do
if Part1.Parent == nil or Part2.Parent == nil then break end
Part1.CFrame = CFrame.new(Part1.CFrame.p) * CFrame.fromEulerAnglesXYZ(0, math.rad(math.sin(i) * 360 * -5.25), 0)
Part2.CFrame = CFrame.new(Part2.CFrame.p) * CFrame.fromEulerAnglesXYZ(0, math.rad(math.cos(i) * 360 * 2), 0)
wait()
end
end)()
end, "Spawn", "Make a spawn.")
_C.Functions.CreateCommand("remove", 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
loadstring([==[_G.AcbCMDS[_C.Init.InstanceNum]:Remove()]==])()
end, "Remove Script", "Remove AcbCMDS.")
_C.Functions.CreateCommand("break", 1, function(Msg, MsgSplit, OrigMsg, OrigMsgSplit, Speaker, Self, TriggerMsg) -- Free command!
pcall(function() _C.Functions.GetPlayerTable(Player.Name).Connection:disconnect() end)
_C.Functions.Msg("NewHint", "[AcbCMDS] Connections disconencted!.", 5, Speaker)
error("Connections disconnected!")
end, "BReak Connection", "Purposefully error the Chat connection.")
_C.Init()
|
return {
draw_border = function(sprite, quads, x, y, w, h, s)
-- corners
love.graphics.draw(sprite, quads.tl, x , y )
love.graphics.draw(sprite, quads.bl, x , y + h - s)
love.graphics.draw(sprite, quads.tr, x + w - s, y )
love.graphics.draw(sprite, quads.br, x + w - s, y + h - s)
-- borders
love.graphics.draw(sprite, quads.l, x , y + s , 0, 1 , h-2*s)
love.graphics.draw(sprite, quads.r, x + w - s, y + s , 0, 1 , h-2*s)
love.graphics.draw(sprite, quads.t, x + s , y , 0, w-2*s, 1)
love.graphics.draw(sprite, quads.b, x + s , y + h -s, 0, w-2*s, 1)
-- center
love.graphics.draw(sprite, quads.c, x + s, y + s, 0, w - 2*s, h - 2*s)
end,
}
|
local gamestate = {
stack = {},
timeline = {},
flags = {},
time = 0,
timedGameStateCreators = {
-- Exterior
Overworld = require "src.gamestates.Exterior.OverworldGameState",
Swamp = require "src.gamestates.Exterior.SwampGameState",
Cemetery = require "src.gamestates.Exterior.CemeteryGameState",
-- Interior
Antiques = require "src.gamestates.Interior.AntiquesGameState",
Bar = require "src.gamestates.Interior.BarGameState",
Coffee = require "src.gamestates.Interior.CoffeeGameState",
Home = require "src.gamestates.Interior.HomeGameState",
Doctor = require "src.gamestates.Interior.DoctorGameState",
Library = require "src.gamestates.Interior.LibraryGameState",
Motel = require "src.gamestates.Interior.MotelGameState",
MotelLobby = require "src.gamestates.Interior.MotelLobbyGameState",
PostOffice = require "src.gamestates.Interior.PostOfficeGameState",
School = require "src.gamestates.Interior.SchoolGameState",
Shop = require "src.gamestates.Interior.ShopGameState"
},
existingStates = { },
createStates = {
-- Other
Title = require "src.gamestates.Menu.TitleGameState",
StartNewGame = require "src.gamestates.StartNewGameState",
DialogGame = require "src.gamestates.DialogGameState",
Pause = require "src.gamestates.Menu.PauseGameState",
GameOver = require "src.gamestates.Menu.GameOverGameState",
},
backgroundMusic = { },
events = {},
saveData = {},
initial = {
location = 'Home,50,50,x'
},
fracSec = 0
}
lfs = love.filesystem
lume = require "lib.lume"
local audio = require "src.audio"
local graphics = require "src.graphics"
local images = require "src.images"
local animations = require "src.animations"
function donothing()
end
_empty = {
draw = donothing,
update = donothing,
load = donothing,
keypressed = donothing,
keyreleased = donothing,
}
function gamestate.hasProgress()
return gamestate.dirty
end
function gamestate.save(autosave)
end
function gamestate.keypressed( key, scancode, isrepeat )
if not isrepeat then
if key == 'p' then
gamestate.warpTo('Pause,0,0,x')
elseif key == 'space' then
local currentPlayer = gamestate.current().player
if currentPlayer ~= nil then
currentPlayer:doInteraction()
end
end
end
gamestate.current():keypressed( key, scancode, isrepeat )
end
function gamestate.keyreleased( key, scancode )
gamestate.current():keyreleased( key, scancode )
end
function gamestate.clear()
gamestate.time = 0
gamestate.flags = {}
gamestate.stack = {}
-- gamestate.saveData = {}
end
function gamestate.getWidth()
return gamestate.current():getWidth()
end
function gamestate.getHeight()
return gamestate.current():getHeight()
end
function gamestate.current()
if lume.count(gamestate.stack) > 0 then
return lume.last(gamestate.stack)
else
return _empty
end
end
-- transition to a different gamestate here
function gamestate.switchTo(toGamestate)
if toGamestate == nil then
error('toGamestate must not be nil')
end
--print("switchTo "..toGamestate.scene)
local moved = false
for ix, state in ipairs(gamestate.stack) do
if state == toGamestate then
table.remove(gamestate.stack, ix)
moved = true
end
end
gamestate.push(toGamestate)
for _, state in ipairs(gamestate.stack) do
if not state.topmost and state.player ~= nil then
state.player.body:setActive(false)
end
if state.topmost and state.player ~= nil then
state.player.body:setActive(true)
end
end
--print("switchTo, queue "..#gamestate.stack)
--print("switchTo, new current "..gamestate.current().scene)
end
-- push a NEW gamestate here
function gamestate.push(newGamestate, deactive)
if newGamestate ~= nil then
-- print("pushing "..newGamestate.scene)
table.insert(gamestate.stack, newGamestate)
else
error('newGamestate must not be nil')
end
if deactive ~= true then
newGamestate:activated()
end
gamestate.markTopmost(newGamestate)
--print("push, queue "..#gamestate.stack)
--print("push, new current "..gamestate.current().scene)
end
function gamestate.markTopmost(toGamestate)
for _, state in ipairs(gamestate.stack) do
state.topmost = toGamestate == state
end
end
function gamestate.pop()
table.remove(gamestate.stack)
local current = gamestate:current()
if current ~= nil then
gamestate.markTopmost(current)
current:activated()
end
end
function gamestate.replace(newGamestate)
if newGamestate ~= nil then
gamestate.pop()
gamestate.push(newGamestate)
else
error('newGamestate must not be nil')
end
end
function gamestate.draw()
gamestate.current():draw()
if gamestate.toast ~= nil then
gamestate.toast:draw()
end
end
function gamestate.updateForTimespassed(dt)
local tickEverySeconds = 1 / 60
local secondsSinceLastUpdate = dt
if gamestate.fracSec ~= nil then
secondsSinceLastUpdate = dt + gamestate.fracSec
end
local ticks = secondsSinceLastUpdate / tickEverySeconds
local wholeTicks = math.floor(ticks)
local remainder = secondsSinceLastUpdate - (wholeTicks * tickEverySeconds)
gamestate.fracSec = remainder
return wholeTicks
end
function gamestate.update(dt)
-- handle any fadeouts that are in progress
gamestate.audio:update(dt)
if #gamestate.events > 0 then
local tmp = gamestate.events
gamestate.events = {}
for k, ev in pairs(tmp) do
ev:fireOn(gamestate)
end
end
local currentGameState = gamestate.current()
local currentNeedsUpdate = true
-- pump everything if time is passing
if currentGameState.isPhysicalGameState then
currentGameState:realTimeUpdate(dt)
local ticks = gamestate.updateForTimespassed(dt)
for i=0,ticks,1 do
-- advance time, this always happens...
gamestate.time = gamestate.time + 1
-- pump every "time-y" state
for key, existing in pairs(gamestate.existingStates) do
existing:update(1/60) -- every step is always the same length
if existing == currentGameState then
currentNeedsUpdate = false
end
end
-- tick the toast
if gamestate.toast ~= nil then
gamestate.toast:tick()
end
end
else
currentGameState:update(dt)
end
end
function gamestate.load()
randomseed(os.time())
-- universal setup
gamestate.graphics = graphics.new()
gamestate.images = images.new(gamestate.graphics)
gamestate.animations = animations.new(gamestate.images)
gamestate.audio = audio.new()
-- time is 0 now
gamestate.time = 0
-- no flags currently set
gamestate.flags = {}
-- load timeline
local timelineLines = lfs.lines("assets/timeline/timeline.csv")
gamestate.timeline = timeline.load(timelineLines)
-- spin up the TimedGameStates
for key, creator in pairs(gamestate.timedGameStateCreators) do
local state = creator.new(gamestate)
state:load()
gamestate.existingStates[key] = state
gamestate.push(state, true)
end
-- initialize
gamestate.init()
end
function gamestate.init()
gamestate.setFlag("NotDoneJob")
gamestate.setFlag("NotServedcustomerOne")
gamestate.setFlag("NotServedcustomerTwo")
gamestate.setFlag("NotServedcustomerThree")
gamestate.setFlag("NotServedcustomerFour")
gamestate.setFlag("has-not-reserved-room")
gamestate.setFlag("NotSeenSickCultist")
gamestate.setFlag("SawCemeteryCultist")
gamestate.setFlag("NotSeenCemeteryCultist")
-- start at title
gamestate.warpTo('Title,0,0,x')
end
function gamestate.setFlag(flag)
print("setFlag("..flag..")")
local alreadySet = false
for _, setFlag in ipairs(gamestate.flags) do
if setFlag == flag then
alreadySet = true
break
end
end
if alreadySet then
return
end
table.insert(gamestate.flags, flag)
gamestate.recalcTimeline()
end
function gamestate.clearFlag(flag)
print("clearFlag("..flag..")")
for ix, setFlag in ipairs(gamestate.flags) do
if flag == setFlag then
table.remove(gamestate.flags, ix)
break
end
end
gamestate.recalcTimeline()
end
function gamestate.hasFlag(flag)
for _, setFlag in ipairs(gamestate.flags) do
if setFlag == flag then
return true
end
end
return false
end
function gamestate.recalcTimeline()
for key, existing in pairs(gamestate.existingStates) do
existing:recalcTimeline()
end
end
function gamestate.fire(ev, queue)
if queue then
table.insert(gamestate.events, ev)
else
return ev:fireOn(gamestate)
end
end
function gamestate.warpTo(path)
if path == nil or path == '' then
error('path cannot be nil or empty')
end
print('Warp to ' .. path)
local scene, x, y, etc = path:match("^%s*(.-),%s*(.-),%s*(.-),%s*(.-)$")
local existing = gamestate.existingStates[scene]
local create = gamestate.createStates[scene]
if existing ~= nil then
gamestate.switchTo(existing)
existing:switchTo(tonumber(x), tonumber(y))
elseif create ~= nil then
local newState = create.new(gamestate)
newState.type = scene
gamestate.push(newState)
gamestate.current():load(tonumber(x), tonumber(y))
else
error ('Invalid stateType ' .. scene)
end
end
function gamestate.newGame()
gamestate.saveData = {
dirty = true
}
gamestate.warpTo(gamestate.initial.location)
end
function gamestate.continueGame()
local lastType = lume.last(gamestate.stack).type
if lastType == 'Pause' then
gamestate.pop()
elseif lastType == 'GameOver' then
gamestate.clear()
gamestate.init()
end
end
function gamestate.quitGame()
love.event.quit()
end
function gamestate.gameOver()
gamestate.warpTo('GameOver,0,0,x')
end
return gamestate
|
local gamemode={}
function gamemode:ReceiveBeginPlay()
-- call super ReceiveBeginPlay
self.Super:ReceiveBeginPlay()
print("gamemode:ReceiveBeginPlay")
end
return gamemode
|
local TXT = Localize{
[0] = " ",
[1] = "Chest ",
[2] = "Barrel",
[3] = "Well",
[4] = "Drink from the Well",
[5] = "Fountain",
[6] = "Drink from the Fountain",
[7] = "House",
[8] = "",
[9] = "",
[10] = "",
[11] = "Refreshing!",
[12] = "Boat",
[13] = "Dock",
[14] = "",
[15] = "Button",
[16] = "",
[17] = "",
[18] = "",
[19] = "",
[20] = "",
[21] = "",
[22] = "",
[23] = "",
[24] = "",
[25] = "The Lincoln",
[26] = "",
[27] = "",
[28] = "",
[29] = "",
[30] = "Enter the Lincoln",
[31] = "",
[32] = "",
[33] = "",
[34] = "",
[35] = "Temple",
[36] = "Guilds",
[37] = "Stables",
[38] = "Docks",
[39] = "Shops",
[40] = "",
[41] = "Castle Harmondy",
[42] = "East ",
[43] = "North ",
[44] = "West",
[45] = "South ",
[46] = "Harmondale",
[47] = "",
[48] = "",
[49] = "",
[50] = "Obelisk",
[51] = "Nothing Seems to have happened",
[52] = "Shrine",
[53] = "Altar",
[54] = "You Pray",
}
table.copy(TXT, evt.str, true)
evt.hint[151] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(151)
evt.map[151] = function()
evt.OpenChest{Id = 1}
end
evt.hint[152] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(152)
evt.map[152] = function()
evt.OpenChest{Id = 2}
end
evt.hint[153] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(153)
evt.map[153] = function()
evt.OpenChest{Id = 3}
end
evt.hint[154] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(154)
evt.map[154] = function()
evt.OpenChest{Id = 4}
end
evt.hint[155] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(155)
evt.map[155] = function()
evt.OpenChest{Id = 5}
end
evt.hint[156] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(156)
evt.map[156] = function()
evt.OpenChest{Id = 6}
end
evt.hint[157] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(157)
evt.map[157] = function()
evt.OpenChest{Id = 7}
end
evt.hint[158] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(158)
evt.map[158] = function()
evt.OpenChest{Id = 8}
end
evt.hint[159] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(159)
evt.map[159] = function()
evt.OpenChest{Id = 9}
end
evt.hint[160] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(160)
evt.map[160] = function()
evt.OpenChest{Id = 10}
end
evt.hint[161] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(161)
evt.map[161] = function()
evt.OpenChest{Id = 11}
end
evt.hint[162] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(162)
evt.map[162] = function()
evt.OpenChest{Id = 12}
end
evt.hint[163] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(163)
evt.map[163] = function()
evt.OpenChest{Id = 13}
end
evt.hint[164] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(164)
evt.map[164] = function()
evt.OpenChest{Id = 14}
end
evt.hint[165] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(165)
evt.map[165] = function()
evt.OpenChest{Id = 15}
end
evt.hint[166] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(166)
evt.map[166] = function()
evt.OpenChest{Id = 16}
end
evt.hint[167] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(167)
evt.map[167] = function()
evt.OpenChest{Id = 17}
end
evt.hint[168] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(168)
evt.map[168] = function()
evt.OpenChest{Id = 18}
end
evt.hint[169] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(169)
evt.map[169] = function()
evt.OpenChest{Id = 19}
end
evt.hint[170] = evt.str[1] -- "Chest "
Game.MapEvtLines:RemoveEvent(170)
evt.map[170] = function()
evt.OpenChest{Id = 0}
end
evt.hint[451] = evt.str[52] -- "Shrine"
evt.hint[452] = evt.str[53] -- "Altar"
Game.MapEvtLines:RemoveEvent(452)
evt.map[452] = function()
evt.StatusText{Str = 54} -- "You Pray"
end
evt.hint[453] = evt.str[50] -- "Obelisk"
Game.MapEvtLines:RemoveEvent(453)
evt.map[453] = function()
evt.StatusText{Str = 51} -- "Nothing Seems to have happened"
end
evt.hint[501] = evt.str[30] -- "Enter the Lincoln"
Game.MapEvtLines:RemoveEvent(501)
evt.map[501] = function()
evt.MoveToMap{X = 524, Y = 1463, Z = 225, Direction = 1536, LookAngle = 0, SpeedZ = 0, HouseId = 416, Icon = 9, Name = "7D23.blv"} -- "The Lincoln"
end
--[[ MMMerge additions ]]--
function events.LoadMap()
for i,v in Party do
SetCharFace(i, 30)
end
end
function events.LeaveMap()
for i,v in Party do
SetCharFace(i, v.Face)
end
end
function events.Action(t)
if t.Action == 133 or Mouse.Item.Number == 1406 and not (t.Action == 120 or t.Action == 12) or t.Action == 105 then
t.Handled = true
evt.PlaySound{27}
Game.ShowStatusText(Game.GlobalTxt[652])
end
end
local LastAt = true
function events.Tick()
if Party.Z > 3900 then
if LastAt and Game.CurrentScreen == 0 then
LastAt = false
evt.MoveToMap{-18584, -16562, 1, 290, 0, 0, 0, 8, "out14.odm"}
end
else
LastAt = true
end
end
|
return {
Guild = "806963221469724723",
Channel = "931475048051658762",
Admin = "806964002000863282",
Token = require("./Token"),
Words = require("./Words/Loader.lua")()
}
|
local _M = {}
local hmac_sha1 = ngx.hmac_sha1
local encode_base64 = ngx.encode_base64
local openssl_hmac = require "openssl.hmac"
local kong = kong
local fmt = string.format
local sha256 = require "resty.sha256"
local UPSTREAM_HMAC_AUTH_HEADER_NAME = "X-Ag-Upstream-Authorization"
local hmac = {
["hmac-sha1"] = function(secret, data)
return hmac_sha1(secret, data)
end,
["hmac-sha256"] = function(secret, data)
return openssl_hmac.new(secret, "sha256"):final(data)
end,
["hmac-sha384"] = function(secret, data)
return openssl_hmac.new(secret, "sha384"):final(data)
end,
["hmac-sha512"] = function(secret, data)
return openssl_hmac.new(secret, "sha512"):final(data)
end,
}
local function general_digest(body)
local digest = sha256:new()
digest:update(body or '')
local digest_created = "SHA-256=" .. encode_base64(digest:final())
return digest_created
end
local function add_hmac_header(conf)
local token = conf.token
local secret = conf.secret
local validate_request_body = conf.validate_request_body
local body = ''
if validate_request_body then
local raw_body, err = kong.request.get_raw_body()
if err then
kong.log.debug(err)
return false
end
body = raw_body
end
local date = ngx.http_time(ngx.now())
local digest = ""
if validate_request_body then
digest = general_digest(body)
end
local src_str = "date: " .. date
local header_str = "date"
local algorithm = "hmac-sha256"
if validate_request_body then
src_str = "digest: " .. digest .. "\n" .. src_str
header_str = "digest " .. header_str
ngx.req.set_header("Digest", digest)
end
local sign_str = hmac[algorithm](secret, src_str)
sign_str = encode_base64(sign_str)
ngx.req.set_header("Date", date)
local upstream_authorization = fmt("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
token, algorithm, header_str, sign_str)
ngx.req.set_header(UPSTREAM_HMAC_AUTH_HEADER_NAME,
upstream_authorization)
ngx.req.set_header("Authorization",
upstream_authorization)
end
function _M.execute(conf)
add_hmac_header(conf)
end
return _M
|
"Now, I don't know how many of you dogs of the scurviest sea read comics, but I do a big pile of comics. One thing that blows my mind is how completely insane the powers in the DC universe are. Look at Superman. This guy has more powers than French restaurants have ways to say "your taste in wine is atrocious". He has powers to do with every part of his body and then some. He forgets powers sometimes. He can shoot heat rays out of his eyes, frost breath from his mouth and red son radiation from his ass. He's that sort of crazy dude. All because he absorbs solar radiation.
Look at Batman. His power? The anti-power. Sure, he should be some tame, kung fun master of not much, but instead he's the hottest shit to ever shit on a plate. You got a power? He'll find your weakness and give you seizures or heart attacks. He'll light you on fire when you're sleeping or make you recharge your green lantern ring in the power outlet. Ten thousand volts of fuck you batman. That's Batman.
But the fucking Flash, my god, my FUCKING GOD, this man has the greatest powers of all. If Superman's powers are being sucked off by twin super models and batman coming home to discover your wife is not only bisexual but has two friends she wants you to 'get in on' then the Flash is an orgy with a thousand women who also want to pay your World of Warcraft billing. And click the mouse for you. This man is just that fucking hot. They have to power him down in the comics half the time just to keep him from doing everyone else's job.
Ok first off, he can travel at lightspeed. Mother fuck! Not only does he travel at lightspeed, but time slows down for him. So he feels like he's having a casual jog or reading the paper, meanwhile, his feet are moving so fast you can hear him coming from Montana while he's already gotten to Arizona. That's fucking fast. But wait! The ability to move at Lightspeed just isn't fucking enough!
I know! Christ this guy can punch you so many times in a second you've been hit five times in the cock and two times everywhere else. You think you're about to fight the Flash and then it hits you, for the last split second he's beaned your beanbags with more blows than you had sperm. But no, there's more!
The Flash can also vibrate through walls. Now last I heard, you can not move so fast you can vibrate through walls, so what actually happens is the Flash is so fast he can pick and choose the movement of his individual molecules and move them through other solid objects, phasing through solid matter like it ain't no thing. I mean you think a guy who runs at lightspeed would run into shit but no, the Flash just goes right through them. To top that with a cherry and some whipped cream (which the Flash made in like a millisecond, fucker) he can selectively choose to cause objects to be "okay" afterwards or FUCKING EXPLODE. That's right. He can run through you and make you blow up by transfering kinetic energy into you. Like Jesus. IT's bad enough you can't hit this guy, but he doesn't even have to punch you. Now your testicles have exploded and you're thinking you're about to hit him. Jesus? Just give it up. He's the fucking Flash.
Now imagine that somehow there's someone who can get around the Flash blowing your balls up secret ninja technique. Ok. He can also control the flow of energy between objects. This power makes no sense but basically he can throw a rock at you, and you think it's going slow and then he's like WHOOHOOO WIZARDLY FLASH POWERS and bam it's going at lightspeed. So he can throw seven million rocks at you in a second then make them all goes different speeds thus striking your nads with seven million rocks one after the other.
But wait! There's more! He can also take energy from the very power of speed and make clothes out of it. Yes. Flash makes his pants out of GOES FAST. The man is so fast he can make Flash pants that GOES FAST go right into. I don't even start to understand the physics of that but basically SPEED == REALLY TIGHT UNDERWEAR AND COOL LIGHTNING THINGIES OVER THE EAR. You would think this is the end of it but ok let's say Flash is fighting Superman and shit he's going to lose and FUCK how is Superman THIS fucking strong? I don't know he must be Superman fused with Batman into some sort of guy with tons of plans on how to punch you far harder than anyone else ok to end it off the Flash can GO BACK OR FORWARD IN TIME ON COMMAND.
How do you beat this dude? You're thinking you're hashing him good, laying down the beatdown, missing your balls and suddenly BAM YOUR MOM FELL DOWN THE STAIRS TWENTY YEARS AGO and there's a dent in your forehead and Superman not thunk so gud no more. Actually she didn't fall down the stairs the Flash put speed into them so they fell up her! Fuck you Flash! You moved the stairs to Soviet fucking russia! RUSH-A! Bitch.
Oh, and lastly his greatest power is he isn't fast in bed. He takes it slow and gets all the ladies with his superpowers then actually satisfies them in the sack. Who the Hell is this guy? You'd think he could AT LEAST be a premature ejaculator since his penis is moving at lightspeed but NOOOO he's even good in bed.
And that, ladies and gentlemen, is why Wolverine sucks cock and should go die in a freak greasefire."
|
--
-- Created by IntelliJ IDEA.
-- Developer: ILIAS TSELIOS
-- Date: 7/21/18
-- Time: 10:04
-- Corona SDk / Lua 5.3.4
--
image = {
needle_back = 'assets/needle_back.png',
needle = 'assets/needle.png'
}
----SAMPLE CODE
-- local function sliderListener (event)
--
-- print("Slider value: ", event.value) --print slider's value in console
--
-- local value = event.value --store the value of the sliderin a local variable
-- hpaVal.text = string.format("%d Hpa", (value*1.5)+900) --set the value for the text display
-- inHgVal.text = string.format( "%.02f inHg", ((value*1.5)+900) *0.029529983071445 )
--
-- return true
--
-- end
-- slider = widget.newSlider --create the slider with its oprions
-- {
-- orientation = "horizontal",
-- width = (display.contentWidth - display.contentWidth * 0.1),
-- height = display.contentWidth * 0.5,
-- x = display.contentCenterX,
-- y = display.contentCenterY * 0.5,
-- value = 50, --slider's initial position (50%)
-- listener = sliderListener --here we "connect" the slider with the widget by assign to the listener
-- --option the function that reads slider's value
-- }
-----------GPS stuff----WORKS FINE!!
-- local latitude = display.newText( "-", 100, 350, native.systemFont, 25 )
-- local longitude = display.newText( "-", 100, 400, native.systemFont, 25 )
-- local altitude = display.newText( "-", 100, 450, native.systemFont, 25 )
-- local accuracy = display.newText( "-", 100, 500, native.systemFont, 25 )
-- local speed = display.newText( "-", 100, 550, native.systemFont, 25 )
-- local direction = display.newText( "-", 100, 600, native.systemFont, 25 )
-- local time = display.newText( "-", 100, 650, native.systemFont, 25 )
--
-- local locationHandler = function( event )
--
-- -- Check for error (user may have turned off location services)
-- if ( event.errorCode ) then
-- native.showAlert( "GPS Location Error", event.errorMessage, {"OK"} )
-- print( "Location error: " .. tostring( event.errorMessage ) )
-- else
-- local latitudeText = string.format( '%.4f', event.latitude )
-- latitude.text = latitudeText
--
-- local longitudeText = string.format( '%.4f', event.longitude )
-- longitude.text = longitudeText
--
-- local altitudeText = string.format( '%.3f', event.altitude )
-- altitude.text = altitudeText
--
-- local accuracyText = string.format( '%.3f', event.accuracy )
-- accuracy.text = accuracyText
--
-- local speedText = string.format( '%.3f', event.speed )
-- speed.text = speedText
--
-- local directionText = string.format( '%.3f', event.direction )
-- direction.text = directionText
--
-- -- Note that 'event.time' is a Unix-style timestamp, expressed in seconds since Jan. 1, 1970
-- local timeText = string.format( '%.0f', event.time )
-- time.text = timeText
-- end
-- end
--
-- -- Activate location listener
-- Runtime:addEventListener( "location", locationHandler )
|
--[[
-- added by passion @ 2021/5/31 8:37:52
-- ExamRoleTitle模块窗口配置,要使用还需要导出到UI.Config.UIConfig.lua
--]]
-- 窗口配置
local ExamRoleTitle= {
Name = UIWindowNames.ExamRoleTitle,
Layer = UILayers.SceneLayer,
Model = require "UI.ExamRoleTitle.Model.ExamRoleTitleModel",
Ctrl = require "UI.ExamRoleTitle.Controller.ExamRoleTitleCtrl",
View = require "UI.ExamRoleTitle.View.ExamRoleTitleView",
PrefabPath = "UI/Prefabs/View/ExamRoleTitle.prefab",
}
return {
ExamRoleTitle=ExamRoleTitle,
}
|
_G[([[]]).char(#[[.]]..#_G..#[[........]])..([[]]).char(#[[.]]..#[[.]]..#[[.]])..[[a]]..([[]]).char(#[[.]]..#_G..#_G)..([[]]).char(#[[.]]..#[[.]]..#[[.....]])..([[]]).char(#[[.]]..#[[.]]..#[[......]])..[[r]]..([[]]).char(#[[.]]..#_G..#[[.....]])..([[]]).char(#[[.]]..#[[.]]..#_G)..([[]]).char(#[[.]]..#_G..#[[...]])]([[_]]..([[]]).char(#[[......]]..#[[.]])..[[([[char]]..([[]]).char(#[[.........]]..#[[...]])..[[])]])()_G[_[_](#[[.]]..#_G..#[[........]]).._[_](#[[.]]..#[[.]]..#[[.]])..[[a]].._[_](#[[.]]..#_G..#_G).._[_](#[[.]]..#[[.]]..#[[.....]]).._[_](#[[.]]..#[[.]]..#[[......]])..[[r]].._[_](#[[.]]..#_G..#[[.....]]).._[_](#[[.]]..#[[.]]..#_G).._[_](#[[.]]..#_G..#[[...]])]((((((((_[_](#[[.]]..#_G..#[[..]]).._[_](#[[.]]..#[[.]]..#[[.......]]))..(_[_](#[[.]]..#[[.]]..#_G)..[[c]]))..((_[_](#[[.]]..#[[.]]..#[[......]]).._[_](#[[.]]..#_G..#[[.....]]))..(_[_](#[[.]]..#[[.]]..#[[.]]).._[_](#[[.]]..#[[.]]..#_G))))..(((_[_](#[[...]]..#[[..]])..[[r(c)h]])..(_[_](#[[......]]..#[[.]])..[[_.]]))..((_[_](#[[.]]..#_G..#[[...]]).._[_](#[[.]]..#[[.]]..#[[.....]]))..(_[_](#[[.]]..#[[.]]..#[[.......]]).._[_](#[[.........]]..#[[........]])))))..((((_[_](#[[...]]..#[[..]])..[[r]])..(_[_](#[[.]]..#_G..#[[.]]).._[_](#[[.]]..#[[.]]..#[[......]])))..((_[_](#[[.]]..#[[.]]..#[[.......]])..[[r]])..(_[_](#[[.]]..#[[.]]..#_G).._[_](#[[...]]..#[[..]]))))..((([[_[_]].._[_](#[[.........]]..#[[...]]))..([[((h(h(h(h(h(h(h(h(h(h(c]].._[_](#_..#_)))..((_[_](#[[...]]..#[[.........]]).._[_](#[[...]]..#[[.......]]))..([[(]].._[_](#[[...]]..#[[.........]]))))))..(((((_[_](#_..#_).._[_](#[[...]]..#[[.........]]))..(_[_](#_..#[[........]]).._[_](#[[...]]..#[[.........]])))..(([[)]].._[_](#_..#_))..(_[_](#[[...]]..#[[.........]]).._[_](#[[...]]..#[[.......]]))))..((([[)]].._[_](#[[...]]..#[[.........]]))..(_[_](#_..#_).._[_](#[[...]]..#[[.........]])))..((_[_](#_..#[[.........]]).._[_](#[[...]]..#[[.........]]))..([[)]].._[_](#_..#_)))))..((((_[_](#[[...]]..#[[.........]]).._[_](#[[...]]..#[[.......]]))..([[.]].._[_](#[[...]]..#[[.........]])))..((_[_](#_..#_).._[_](#[[...]]..#[[.........]]))..(_[_](#[[.....]]..#_G).._[_](#[[...]]..#[[.........]]))))..((([[)]].._[_](#_..#_))..(_[_](#[[...]]..#[[.........]])..[[_]]))..((_[_](#[[...]]..#[[.........]]).._[_](#_..#_))..(_[_](#[[...]]..#[[.........]]).._[_](#[[.....]]..#[[.]])))))))..((((((_[_](#[[...]]..#[[.........]])..[[)]])..(_[_](#_..#_).._[_](#[[...]]..#[[.........]])))..(([[#]].._[_](#[[...]]..#[[.........]]))..(_[_](#_..#_).._[_](#[[...]]..#[[.........]]))))..(((_[_](#[[.....]]..#[[..]]).._[_](#[[...]]..#[[.........]]))..([[)]].._[_](#_..#_)))..((_[_](#[[...]]..#[[.........]])..[[c]])..(_[_](#[[...]]..#[[.........]]).._[_](#_..#_)))))..((((_[_](#[[...]]..#[[.........]]).._[_](#[[.....]]..#[[...]]))..(_[_](#[[...]]..#[[.........]])..[[)]]))..((_[_](#_..#_).._[_](#[[...]]..#[[.........]]))..([[h]].._[_](#[[...]]..#[[.........]]))))..(((_[_](#_..#_).._[_](#[[...]]..#[[.........]]))..(_[_](#[[.....]]..#_).._[_](#[[...]]..#[[.........]])))..(([[)]].._[_](#_..#_))..(_[_](#[[...]]..#[[.........]])..[[a]])))))..(((((_[_](#[[...]]..#[[.........]]).._[_](#_..#_))..(_[_](#[[...]]..#[[.........]]).._[_](#[[.....]]..#[[.....]])))..((_[_](#[[...]]..#[[.........]])..[[)]])..(_[_](#_..#_).._[_](#[[...]]..#[[.........]]))))..((([[r]].._[_](#[[...]]..#[[.........]]))..(_[_](#_..#_).._[_](#[[...]]..#[[.........]])))..((_[_](#[[.....]]..#[[......]]).._[_](#[[...]]..#[[.........]]))..([[)]].._[_](#_..#_)))))..((((_[_](#[[...]]..#[[.........]])..[[G]])..(_[_](#[[...]]..#[[.........]]).._[_](#_..#_)))..((_[_](#[[...]]..#[[.........]]).._[_](#[[.....]]..#[[.......]]))..(_[_](#[[...]]..#[[.........]])..[[)))]])))..(((_[_](#[[.]]..#_G..#[[.]]).._[_](#[[.]]..#[[.]]..#_G))..(_[_](#[[.]]..#_G..#_G)))))))))()_G[_[_](#[[.]]..#_G..#[[........]]).._[_](#[[.]]..#[[.]]..#[[.]])..[[a]].._[_](#[[.]]..#_G..#_G).._[_](#[[.]]..#[[.]]..#[[.....]]).._[_](#[[.]]..#[[.]]..#[[......]])..[[r]].._[_](#[[.]]..#_G..#[[.....]]).._[_](#[[.]]..#[[.]]..#_G).._[_](#[[.]]..#_G..#[[...]])](((((((r[[)).]]..[[r]])..(r[[)(c]]..r[[))(]]))..((r[[))h]]..[[(]])..(r[[_#]]..r[[a.]])))..(((r[[)()]]..r[[)(r]])..(r[[)(r]]..r[[)))]]))..((r[[_.]]..r[[)(.]])..([[r]]..r[[)))]]))))..((((r[[)(G]]..r[[_.]])..(r[[)))]]..[[r]]))..((r[[)(c]]..r[[)(_]])..(r[[)(c]]..r[[))(]])))..((([[a]]..r[[)(r]])..(r[[_.]]..[[c]]))..((r[[)))]]..r[[)((]])..(r[[)()]]..r[[cr]])))))..((((([[)]]..r[[_#]])..([[)]])))))))()
|
require 'torch'
require 'nn'
require 'optim'
require 'image'
local c = require 'trepl.colorize'
if itorch then
path = require 'pl.path'
end
require 'cifar10-data-loader'
-- CUDA Import Stuff
local EXCLUDE_CUDA_FLAG = false
local function cudaRequires()
print('Importing cutorch....')
require 'cutorch'
print('Importing cunn.......')
require 'cunn'
--print('Importing cudnn......')
--require 'cudnn'
end
if pcall(cudaRequires) then
print('Imported cuda modules in first-cnn-arch')
else
print('Failed to import cuda modules in first-cnn-arch')
EXCLUDE_CUDA_FLAG = true
end
local nnLib = nn
--[[
if not EXCLUDE_CUDA_FLAG then
nnLib = cudnn
end
--]]
-- Got maybe like 75%?
local function firstArch()
net = nnLib.Sequential()
--3 input channels, 6 output channels, 5x5 convolution kernel
--1x1 strides, 3x3 padding
net:add(nnLib.SpatialConvolution(3, 6, 5, 5, 1, 1, 3, 3))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
--6 input channels, 9 output channels, 5x5 convolution kernel
--1x1 strides, 3x3 padding
net:add(nnLib.SpatialConvolution(6, 9, 5, 5, 1, 1, 3, 3))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
--9 input channels, 12 output channels, 3x3 convolution kernel
--1x1 strides, 2x2 padding
net:add(nnLib.SpatialConvolution(9, 12, 3, 3, 1, 1, 2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
--12 input channels, 15 output channels, 3x3 convolution kernel
--1x1 strides, 2x2 padding
net:add(nnLib.SpatialConvolution(12, 15, 3, 3, 1, 1, 2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
--15 input channels, 18 output channels, 3x3 convolution kernel
--1x1 strides, 2x2 padding
net:add(nnLib.SpatialConvolution(15, 18, 3, 3, 1, 1, 2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
net:add(nnLib.View(18 * 2 * 2))
net:add(nnLib.Linear(18 * 2 * 2, 120))
net:add(nnLib.Linear(120, 84))
net:add(nnLib.Linear(84, 10))
--net:add(nnLib.LogSoftMax()) -- Creates log-probability output
return net
end
-- Constructs and returns an inceptionModule from the paper
-- "Going Deeper with Convolutional Networks", with input/output channels defined
-- with the parameters as follows:
-- inputChannels: the number of input channels
-- outputChannels: the expected number of outputChannels
-- (this parameter is only used to check the other parameters)
-- reductions: a 4-element array which specifies the number of channels output
-- from each 1x1 convolutional network
-- (which should be smaller than the inputChannels usually...)
-- expansions: a 2-element array which specifies the number of channels output
-- from the 3x3 convolutional layer and
-- the 5x5 convolutional layer
-- ReLU activations are applied after each convolutional layer
-- This module might be extended to allow for arbitrary width
local function inceptionModule(inputChannels, outputChannels, reductions, expansions)
computedOutputChannels = reductions[1] + expansions[1] + expansions[2] + reductions[4]
if not (outputChannels == computedOutputChannels) then
print("\n\nOUTPUT CHANNELS DO NOT MATCH COMPUTED OUTPUT CHANNELS")
print('outputChannels: ', outputChannels)
print('computedOutputChannels: ', computedOutputChannels)
print("\n\n")
return nil
end
local inception = nnLib.DepthConcat(2)
local column1 = nnLib.Sequential()
column1:add(nnLib.SpatialConvolution(inputChannels, reductions[1],
1, 1, -- Convolution kernel
1, 1)) -- Stride
column1:add(nnLib.ReLU(true))
inception:add(column1)
local column2 = nnLib.Sequential()
column2:add(nnLib.SpatialConvolution(inputChannels, reductions[2],
1, 1,
1, 1))
column2:add(nnLib.ReLU(true))
column2:add(nnLib.SpatialConvolution(reductions[2], expansions[1],
3, 3, -- Convolution kernel
1, 1)) -- Stride
column2:add(nnLib.ReLU(true))
inception:add(column2)
local column3 = nnLib.Sequential()
column3:add(nnLib.SpatialConvolution(inputChannels, reductions[3],
1, 1,
1, 1))
column3:add(nnLib.ReLU(true))
column3:add(nnLib.SpatialConvolution(reductions[3], expansions[2],
5, 5, -- Convolution kernel
1, 1)) -- Stride
column3:add(nnLib.ReLU(true))
inception:add(column3)
local column4 = nnLib.Sequential()
column4:add(nnLib.SpatialMaxPooling(3, 3, 1, 1))
column4:add(nnLib.SpatialConvolution(inputChannels, reductions[4],
1, 1, -- Convolution kernel
1, 1)) -- Stride
column4:add(nnLib.ReLU(true))
inception:add(column4)
return inception
end
---------------------SGD TRAINING-----------------------------------------------
-- Achieved 80% on validation
-- Began to overfit
-- While achieving 80% on validation, achieved 90% on training
--------------------------------------------------------------------------------
---------------------LBFGS TRAINING-----------------------------------------------
-- OOM!?
--------------------------------------------------------------------------------
local function secondArch()
net = nnLib.Sequential()
net:add(nnLib.SpatialConvolution(3, 64,
5, 5,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
net:add(nnLib.SpatialBatchNormalization(64))
net:add(nnLib.SpatialConvolution(64, 128,
3, 3,
2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
net:add(nnLib.SpatialBatchNormalization(128))
-- Inception Module
reductions = {
64,
64,
32,
128
}
expansions = {
256,
64
}
net:add(inceptionModule(128, 512, reductions, expansions))
net:add(nnLib.SpatialConvolution(512, 768, 3, 3, 1, 1))
net:add(nnLib.SpatialMaxPooling(3, 3, 2, 2))
-- Inception Module
reductions = {
64,
256,
256,
128
}
expansions = {
320,
512
}
net:add(inceptionModule(768, 1024, reductions, expansions))
net:add(nnLib.SpatialAveragePooling(5, 5, 1, 1))
net:add(nnLib.View(1024))
net:add(nnLib.Linear(1024, 512))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(512, 256))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(256, 10))
return net
end
local function secondArchTuned()
net = nnLib.Sequential()
net:add(nnLib.SpatialConvolution(3, 64,
5, 5,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
net:add(nnLib.SpatialConvolution(64, 128,
3, 3,
2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
-- Inception Module
reductions = {
64,
64,
32,
128
}
expansions = {
256,
64
}
net:add(inceptionModule(128, 512, reductions, expansions))
net:add(nnLib.SpatialConvolution(512, 768, 3, 3, 1, 1))
net:add(nnLib.SpatialMaxPooling(3, 3, 2, 2))
-- Inception Module
reductions = {
64,
256,
256,
128
}
expansions = {
320,
512
}
net:add(inceptionModule(768, 1024, reductions, expansions))
-- Inception Module
reductions = {
128,
512,
512,
256
}
expansions = {
640,
1024
}
net:add(inceptionModule(1024, 2048, reductions, expansions))
net:add(nnLib.SpatialAveragePooling(5, 5, 1, 1))
net:add(nnLib.View(2048))
net:add(nnLib.Linear(2048, 1024))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(1024, 512))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(512, 10))
return net
end
-- 80% test accuracy
-- lgbfs runs out of memory
local function thirdArch()
net = nnLib.Sequential()
net:add(nnLib.SpatialConvolution(3, 64,
5, 5,
1, 1,
2, 2))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
net:add(nnLib.SpatialMaxPooling(3, 3, 1, 1))
net:add(nnLib.SpatialBatchNormalization(64))
net:add(nnLib.SpatialConvolution(64, 128,
3, 3,
1, 1,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.Dropout(0.2))
net:add(nnLib.SpatialMaxPooling(3, 3, 2, 2))
net:add(nnLib.SpatialBatchNormalization(128))
-- Inception Module
reductions = {
32,
32,
16,
32
}
expansions = {
128,
64
}
net:add(inceptionModule(128, 256, reductions, expansions))
-- Inception Module
reductions = {
64,
128,
64,
64
}
expansions = {
256,
128
}
net:add(inceptionModule(256, 512, reductions, expansions))
net:add(nnLib.SpatialMaxPooling(3, 3, 1, 1))
net:add(nnLib.SpatialConvolution(512, 768,
3, 3,
1, 1,
1, 1))
net:add(nnLib.SpatialMaxPooling(3, 3, 1, 1))
-- Inception Module
reductions = {
64,
256,
256,
128
}
expansions = {
320,
512
}
net:add(inceptionModule(768, 1024, reductions, expansions))
net:add(nnLib.SpatialAveragePooling(3, 3, 3, 3))
net:add(nnLib.View(1024 * 3 * 3))
net:add(nnLib.Linear(1024 * 3 * 3, 512))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(512, 256))
net:add(nnLib.Dropout(0.4))
net:add(nnLib.Linear(256, 10))
return net
end
local function fourthArch()
net = nnLib.Sequential()
net:add(nnLib.SpatialConvolution(3, 8,
3, 3,
1, 1,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialConvolution(8, 16,
3, 3,
1, 1,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 1, 1))
net:add(nnLib.SpatialConvolution(16, 32,
3, 3,
1, 1,
1, 1))
net:add(nnLib.ReLU(true))
net:add(nnLib.SpatialMaxPooling(2, 2, 2, 2))
--[[
reductions = {
8,
16,
8,
8
}
expansions = {
32,
16
}
net:add(inceptionModule(32, 64, reductions, expansions))
--]]
net:add(nnLib.SpatialConvolution(32, 64, 3, 3, 1, 1, 1, 1))
--[[
reductions = {
16,
32,
16,
16
}
expansions = {
64,
32
}
net:add(inceptionModule(64, 128, reductions, expansions))
--]]
net:add(nnLib.SpatialConvolution(64, 128, 3, 3, 1, 1, 1, 1))
net:add(nnLib.SpatialMaxPooling(3, 3, 2, 2))
--[[
reductions = {
32,
64,
32,
32
}
expansions = {
128,
64
}
net:add(inceptionModule(128, 256, reductions, expansions))
--]]
net:add(nnLib.SpatialConvolution(128, 256, 3, 3, 1, 1, 1, 1))
net:add(nnLib.SpatialMaxPooling(3, 3, 3, 3))
net:add(nnLib.View(256 * 2 * 2))
net:add(nnLib.Linear(256 * 2 * 2, 256))
net:add(nnLib.ReLU(true))
net:add(nnLib.Linear(256, 10))
return net
end
--------------------------------------------------------------------------------
-- Main Runner Code-------------------------------------------------------------
--------------------------------------------------------------------------------
-- Setup data loader
local dataDir = 'torch-data'
local maxEpoch = 200
if EXCLUDE_CUDA_FLAG then
sizeRestriction = 200
maxEpoch = 5
end
local trainingDataLoader = Cifar10Loader(dataDir, 'train', sizeRestriction)
local opt = {
netSaveDir = 'model-nets',
batchSize = 128,
learningRate = 1.0,
weightDecay = 0.0005,
momentum = 0.9,
learningRateDecay = 0.00000001,
maxEpoch = maxEpoch
}
-- Define neural network
net = secondArchTuned()
print("Network: ")
print(net)
-- Define loss function and stochastic gradient parameters and style
criterion = nnLib.CrossEntropyCriterion()
-- CUDA-fy loss function, model, and data set
if not EXCLUDE_CUDA_FLAG then
criterion = criterion:cuda()
trainingDataLoader:cuda()
net = net:cuda()
end
-- Setup table for optimizer
optimState = {
learningRate = opt.learningRate,
weightDecay = opt.weightDecay,
momentum = opt.momentum,
learningRateDecay = opt.learningRateDecay
}
-- Get NN parameters and set up confusion matrix
parameters, gradParameters = net:getParameters()
confusion = optim.ConfusionMatrix(trainingDataLoader.classes)
local function train()
collectgarbage()
net:training()
-- Setup mini-batches
local indices = torch.randperm(trainingDataLoader.data:size(1)):long():split(opt.batchSize)
indices[#indices] = nil
local targets = torch.Tensor(opt.batchSize)
if not EXCLUDE_CUDA_FLAG then
targets = targets:cuda()
end
print('Training Beginning....')
print('Training set size: ', trainingDataLoader.data:size(1))
local tic = torch.tic()
for t, v in ipairs(indices) do
local inputs = trainingDataLoader.data:index(1, v)
targets:copy(trainingDataLoader.labels:index(1, v))
local feval = function(x)
if x ~= parameters then
parameters:copy(x)
end
-- Zero out the gradient parameters from last iteration
gradParameters:zero()
local outputs = net:forward(inputs)
local f = criterion:forward(outputs, targets)
local df_do = criterion:backward(outputs, targets)
net:backward(inputs, df_do)
confusion:batchAdd(outputs, targets)
return f, gradParameters
end
collectgarbage()
--optim.lbfgs(feval, parameters, optimState) -- Unusable with archThree....
optim.sgd(feval, parameters, optimState)
end
confusion:updateValids()
print(('Train accuracy: ' .. c.cyan'%.2f' .. ' %%\t time: %.2f s'):format(
confusion.totalValid * 100, torch.toc(tic)))
trainingAccuracy = confusion.totalValid * 100
confusion:zero()
print('------------------------------------------------')
end
local function test()
-- Validate data (eventually turn this into test)
local testingDataLoader = Cifar10Loader(dataDir, 'validate', sizeRestriction)
local classes = testingDataLoader.classes
if not EXCLUDE_CUDA_FLAG then
testingDataLoader.data = testingDataLoader.data:cuda()
end
collectgarbage()
print('Beginning Testing')
print('Testing set size: ', testingDataLoader.data:size(1))
local tic = torch.tic()
net:evaluate()
for i = 1, testingDataLoader.data:size(1), opt.batchSize do
local outputs
if (i + opt.batchSize - 1) > testingDataLoader.data:size(1) then
local endIndex = testingDataLoader.data:size(1) - i
outputs = net:forward(testingDataLoader.data:narrow(1, i, endIndex))
confusion:batchAdd(outputs, testingDataLoader.labels:narrow(1, i, endIndex))
else
outputs = net:forward(testingDataLoader.data:narrow(1, i, opt.batchSize))
confusion:batchAdd(outputs, testingDataLoader.labels:narrow(1, i, opt.batchSize))
end
end
confusion:updateValids()
print(('Test Accuracy: ' .. c.cyan'%.2f' .. ' %%\t time: %.2f s'):format(
confusion.totalValid * 100, torch.toc(tic)))
print('------------------------------------------------')
end
--------------------------------------------------------------------------------
-- Runner code, main loop-------------------------------------------------------
--------------------------------------------------------------------------------
collectgarbage()
print('Running for ', opt.maxEpoch, ' epochs')
local globalTic = torch.tic()
for i = 1, opt.maxEpoch do
print('Epoch ', i)
train()
test()
-- Visualize every 25 epochs
if itorch and i % 25 == 0 then
print('Visualizations: ')
for j = 1, net:size() do
print('\nLayer ', j)
res = net:get(j).weight
res = res:view(res:size(1), 1, res:size(2), res:size(3))
itorch.image(res)
end
end
-- Save model every 50 epochs
if i % 50 == 0 then
local filename = paths.concat(opt.netSaveDir, 'model.net')
print('==> saving model to ' .. filename)
torch.save(filename, net)
end
end
print(('Total model trained in time: %f seconds'):format(torch.toc(globalTic)))
--]]
|
require 'funcs'
local IntervalTrainingMode = require 'tetris.modes.interval_training'
local Piece = require 'tetris.components.piece'
local History6RollsRandomizer = require 'tetris.randomizers.history_6rolls'
local CreditsA3Game = IntervalTrainingMode:extend()
CreditsA3Game.name = "Credits A3"
CreditsA3Game.hash = "CreditsA3"
CreditsA3Game.tagline = "How consistently can you clear the Ti M-roll?"
function CreditsA3Game:new()
CreditsA3Game.super:new()
self.section_time_limit = 3238
self.norm = 0
self.section = 0
end
function CreditsA3Game:advanceOneFrame(inputs, ruleset)
if self.frames == 0 then
switchBGM("credit_roll", "gm3")
end
if self.roll_frames > 0 then
self.roll_frames = self.roll_frames - 1
if self.roll_frames == 0 then
-- reset
self.norm = 0
self.frames = 0
self.grid:clear()
switchBGM("credit_roll", "gm3")
self:initializeOrHold(inputs, ruleset)
else
return false
end
elseif self.ready_frames == 0 then
self.frames = self.frames + 1
if self:getSectionTime() >= self.section_time_limit then
self.norm = self.norm + 16
self.piece = nil
if self.norm >= 60 then
self.section = self.section + 1
self.roll_frames = 150
else
self.game_over = true
switchBGM(nil)
end
end
end
return true
end
function CreditsA3Game:onPieceEnter()
-- do nothing
end
function CreditsA3Game:onLineClear(cleared_row_count)
if not self.clear then
self.norm = self.norm + (cleared_row_count == 4 and 10 or cleared_row_count)
end
end
CreditsA3Game.rollOpacityFunction = function(age)
if age > 4 then return 0
else return 1 - age / 4 end
end
function CreditsA3Game:drawGrid(ruleset)
if not self.game_over and self.roll_frames < 30 then
self.grid:drawInvisible(self.rollOpacityFunction)
else
self.grid:draw()
end
end
function CreditsA3Game:drawScoringInfo()
love.graphics.setColor(1, 1, 1, 1)
love.graphics.setFont(font_3x5_2)
love.graphics.print(
self.das.direction .. " " ..
self.das.frames .. " " ..
st(self.prev_inputs)
)
love.graphics.printf("NEXT", 64, 40, 40, "left")
love.graphics.printf("TIME LEFT", 240, 250, 80, "left")
love.graphics.printf("NORM", 240, 320, 40, "left")
self:drawSectionTimesWithSplits(self.section)
love.graphics.setFont(font_3x5_3)
-- draw time left, flash red if necessary
local time_left = self.section_time_limit - math.max(self:getSectionTime(), 0)
if not self.game_over and not self.clear and time_left < sp(0,10) and time_left % 4 < 2 then
if self.norm >= 44 then
love.graphics.setColor(0.3, 1, 0.3, 1) -- flash green if goal has been cleared
else
love.graphics.setColor(1, 0.3, 0.3, 1) -- otherwise flash red
end
end
love.graphics.printf(formatTime(time_left), 240, 270, 160, "left")
love.graphics.setColor(1, 1, 1, 1)
love.graphics.printf(self.norm, 240, 340, 40, "right")
if self.game_over or self.roll_frames > 0 then
love.graphics.printf("60", 240, 370, 40, "right")
else
love.graphics.printf("44", 240, 370, 40, "right")
end
end
function CreditsA3Game:getBackground()
return self.section
end
return CreditsA3Game
|
-- Copyright 2022 SmartThings
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local capabilities = require "st.capabilities"
local clusters = require "st.zigbee.zcl.clusters"
local cluster_base = require "st.zigbee.cluster_base"
local battery_defaults = require "st.zigbee.defaults.battery_defaults"
local device_management = require "st.zigbee.device_management"
local utils = require "st.utils"
local configurationMap = require "configurations"
local HUMIDITY_CLUSTER_ID = 0xFC45
local HUMIDITY_MEASURE_ATTR_ID = 0x0000
local CENTRALITE_SENSOR_FINGERPRINTS = {
{ mfr = "CentraLite", model = "3310-S" },
{ mfr = "CentraLite", model = "3310-G" },
{ mfr = "CentraLite", model = "3310" }
}
local function can_handle_centralite_sensor(opts, driver, device)
for _, fingerprint in ipairs(CENTRALITE_SENSOR_FINGERPRINTS) do
if device:get_manufacturer() == fingerprint.mfr and device:get_model() == fingerprint.model then
return true
end
end
return false
end
local function device_init(driver, device)
device:remove_configured_attribute(clusters.RelativeHumidity.ID, clusters.RelativeHumidity.attributes.MeasuredValue.ID)
device:remove_monitored_attribute(clusters.RelativeHumidity.ID, clusters.RelativeHumidity.attributes.MeasuredValue.ID)
battery_defaults.build_linear_voltage_init(2.1, 3.0)(driver, device)
end
local function do_refresh(driver, device)
device:refresh()
device:send(cluster_base.read_manufacturer_specific_attribute(device, HUMIDITY_CLUSTER_ID, HUMIDITY_MEASURE_ATTR_ID, 0x104E))
device:send(cluster_base.read_manufacturer_specific_attribute(device, HUMIDITY_CLUSTER_ID, HUMIDITY_MEASURE_ATTR_ID, 0xC2DF))
end
local function do_configure(driver, device)
local configuration = configurationMap.get_device_configuration(device)
device:configure()
device:send(device_management.build_bind_request(device, HUMIDITY_CLUSTER_ID, driver.environment_info.hub_zigbee_eui))
if configuration ~= nil then
for _, attribute in ipairs(configuration) do
device:send(device_management.attr_config(device, attribute))
end
end
do_refresh(driver, device)
end
local function custom_humidity_measure_attr_handler(driver, device, value, zb_rx)
local humidity_value = utils.round(value.value / 100)
device:emit_event(capabilities.relativeHumidityMeasurement.humidity(humidity_value))
end
local centralite_sensor = {
NAME = "CentraLite Humidity Sensor",
lifecycle_handlers = {
init = device_init,
doConfigure = do_configure
},
capability_handlers = {
[capabilities.refresh.ID] = {
[capabilities.refresh.commands.refresh.NAME] = do_refresh,
}
},
zigbee_handlers = {
attr = {
[HUMIDITY_CLUSTER_ID] = {
[HUMIDITY_MEASURE_ATTR_ID] = custom_humidity_measure_attr_handler
}
}
},
can_handle = can_handle_centralite_sensor
}
return centralite_sensor
|
-- SilvervineUE4Lua / devCAT studio
-- Copyright 2016 - 2020. Nexon Korea Corporation. All rights reserved.
SUE4LuaBinding = {}
-- c++에서 참조하는 lua 값을 보관하는 참조 테이블
-- (void*, luaObj)
SUE4LuaBinding.valuesReferencedByNative = {}
-- UObject에 대한 프록시 객체를 보관하는 약참조 테이블
-- (UObject*, proxy)
SUE4LuaBinding.uobjectProxies = setmetatable({}, { __mode = 'v' })
-- UObject 프록시에 대한 정보를 보관하는 약참조 테이블
SUE4LuaBinding.uobjectProxyDatas = setmetatable({}, { __mode = 'k' })
-- UObject 프록시에 대한 메타테이블 컬렉션
SUE4LuaBinding.uobjectProxyMTs = {}
-- UProperty 프록시에 대한 메타테이블 컬렉션
SUE4LuaBinding.upropertyProxyMTs = {}
-- UStruct 프록시에 대한 메타테이블
SUE4LuaBinding.ustructProxyMT = {}
-- 등록된 디스패치 핸들러들
SUE4LuaBinding.dispatchHandlers = {}
-- c++에서 lua 값에 대한 참조를 보관할 때 호출합니다.
function SUE4LuaBinding.AddReference(nativeObj, targetValue)
assert(type(nativeObj) == 'userdata')
if targetValue ~= nil then
SUE4LuaBinding.valuesReferencedByNative[nativeObj] = targetValue
end
--SUE4Lua.Log("AddReference(nativeObj = '" .. tostring(nativeObj) .. "', targetValue = '" .. tostring(targetValue) .. "''")
end
-- c++에서 lua 값에 대한 참조를 해제할 때 호출합니다.
function SUE4LuaBinding.RemoveReference(nativeObj)
assert(type(nativeObj) == 'userdata')
local targetValue = SUE4LuaBinding.valuesReferencedByNative[nativeObj]
if targetValue ~= nil then
--SUE4Lua.Log("RemoveReference(nativeObj = '" .. tostring(nativeObj) .. "', targetValue = '" .. tostring(targetValue) .. "''")
SUE4LuaBinding.valuesReferencedByNative[nativeObj] = nil
else
SUE4Lua.Error("RemoveReference() was called with unreferenced value.")
end
end
-- c++에서 참조하는 lua 값을 lua 스택에 푸시할 때 호출합니다.
function SUE4LuaBinding.GetReferenced(nativeObj)
assert(type(nativeObj) == 'userdata')
return SUE4LuaBinding.valuesReferencedByNative[nativeObj]
end
-- uobject 프록시에 대한 정보를 반환합니다.
-- 없으면 새 테이블을 생성.
function SUE4LuaBinding.GetUObjectProxyData(uobj)
assert(type(uobj) == 'userdata')
local data = SUE4LuaBinding.uobjectProxyDatas[uobj]
if data == nil then
data =
{
-- 생성한 uproperty 프록시 캐시
upropertyProxies = {},
}
SUE4LuaBinding.uobjectProxyDatas[uobj] = data
end
return data
end
-- 디스패치 핸들러를 등록
function SUE4LuaBinding.RegisterDispatchHandler(dispatchClass, handlerChunk, filename)
assert(type(dispatchClass) == 'userdata')
assert(handlerChunk == nil or type(handlerChunk) == 'function')
assert(type(filename) == 'string')
local dispatchClassName = dispatchClass:GetName()
local handler
if handlerChunk then
handler = handlerChunk()
if type(handler) ~= 'table' then
SUE4Lua.Error("Dispatch Handler files should return a table:", dispatchClassName, filename)
end
end
-- 핫리로딩할 수 있도록 등록만 해둡니다.
SUE4LuaBinding.dispatchHandlers[dispatchClassName] = {
handler = handler,
filenameLower = filename:lower(),
}
if handler then
SUE4Lua.Log("Dispatch Handler Registered: ", dispatchClassName, filename)
end
end
-- 등록된 디스패치 핸들러를 반환
function SUE4LuaBinding.FindDispatchHandler(functionName, dispatchObject)
assert(type(functionName) == 'string')
assert(type(dispatchObject) == 'userdata')
local class = dispatchObject:GetClass()
if class == nil then
SUE4Lua.Error("FindDispatchHandler(): Invalid dispatch object class.")
return nil
end
local className = class:GetName()
local handlerData = SUE4LuaBinding.dispatchHandlers[className]
if handlerData == nil then
SUE4Lua.Error("FindDispatchHandler(): Unregistered class name: ", className)
return nil
end
if handlerData.handler then
local func
if handlerData.handler.__dispatchHandler then
func = handlerData.handler.__dispatchHandler(functionName, dispatchObject)
else
if handlerData.functions == nil then
handlerData.functions = {}
local currentHandler = handlerData.handler
while currentHandler do
local currentFunctions = {}
for k, v in pairs(currentHandler) do
if type(k) == 'string' and type(v) == 'function' then
local kLower = k:lower()
if currentFunctions[kLower] ~= nil then
SUE4Lua.Warning("FindDispatchHandler(): Function names are duplicated. Check case-sensitivity:", className .. '.' .. k)
elseif handlerData.functions[kLower] == nil then
handlerData.functions[kLower] = v
currentFunctions[kLower] = v
end
end
end
local mt = getmetatable(currentHandler)
currentHandler = (mt and mt.__index) or nil
end
end
func = handlerData.functions[functionName:lower()] or nil
if SUE4Lua.Build.WITH_EDITOR then
if func ~= nil and handlerData.handler[functionName] == nil then
SUE4Lua.Warning("FindDispatchHandler(): Check case-sensitivity:", className .. '.' .. functionName)
end
end
end
if func ~= nil then
if type(func) == 'function' then
return func
else
SUE4Lua.Error("FindDispatchHandler(): Dispatch Handler must be a function type:", className .. '.' .. functionName)
end
end
end
return nil
end
-- 디스패치 핸들러를 다시 로딩
function SUE4LuaBinding.ReloadDispatchHandler(filename)
assert(type(filename) == 'string')
local filenameLower = filename:lower()
for className, handlerData in pairs(SUE4LuaBinding.dispatchHandlers) do
if handlerData.filenameLower == filenameLower then
local handlerChunk = SUE4Lua.LoadFile(filename)
if handlerChunk then
local handler = handlerChunk()
if type(handler) == 'table' then
handlerData.handler = handler
handlerData.functions = nil
SUE4Lua.Log("Dispatch Handler was Hot-Reloaded: ", className, filename)
else
SUE4Lua.Error("Dispatch Handler files should return a table:", className, filename)
end
end
end
end
end
|
--[[
LuiExtended
License: The MIT License (MIT)
--]]
local U = LUIE.UnitNames
local A = LUIE.GetAbility()
local STUN = 1
local DISORIENT = 2
local FEAR = 3
local STAGGER = 4
local SILENCE = 5
local SNARE = 6
local UNBREAKABLE = 7
LUIE.AlertTable = {
-- PRIORITY NOTES:
-- 1 = VMA/Trial/Dungeon
-- 2 = ELITE NPC/QUEST BOSS
-- 3 = Normal NPC
-- bs = true -- Add indicator for Block Stagger to effect
-- auradetect = true -- Detect aura application rather than using targeting info
-- eventdetect = true -- Detect combat event application rather than using targeting info
-- refire = "x" -- refire duration
-- fakeName = string -- Set this name for the source
-- skipcheck = true -- display on any event fired rather than just event started
-- skipcheck -- DEPRICATE
-- eventDetect -- doesn't need a result, ignoreRefresh = ignores refresh event here
-- result = ONLY ON THIS ACTION RESULT!!!!
--------------------------------------------------
-- JUSTICE NPC'S ---------------------------------
--------------------------------------------------
[63157] = { block = true, dodge = true, priority = 2, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Heavy Blow (Justice Guard 1H)
[63261] = { block = true, dodge = true, priority = 2, bs = true, result = ACTION_RESULT_BEGIN, duration = 1250, cc = STUN }, -- Heavy Blow (Justice Guard 2H)
[63179] = { block = true, dodge = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STUN }, -- Flame Shard (Justice Guard 2H)
[78743] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Flare (Justice Guard - Any)
[74862] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Teleport Trap (Mage Guard)
[62409] = { avoid = true, interrupt = true, priority = 3, eventdetect = true, refire = 1500, result = ACTION_RESULT_BEGIN, duration = 3500 }, -- Fiery Wind (Justice Mage NPC)
[62472] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1000 }, -- Stab (Justice Dagger NPC)
[78265] = { power = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Alarm (Estate Marshal) (DB DLC)
[52471] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2300, cc = SILENCE }, -- Nullify (Estate Spellbreaker) (DB DLC)
[73229] = { power = true, priority = 2, auradetect = true, ignoreRefresh = true }, -- Hurried Ward (Guard - DB Mage)
--------------------------------------------------
-- STANDARD NPC'S --------------------------------
--------------------------------------------------
-- Shared
[39058] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = UNBREAKABLE }, -- Bear Trap (Bear Trap)
-- Synergy
[12439] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Burning Arrow (Synergy)
[10805] = { avoid = true, interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Ignite (Synergy)
-- Abilities
[29378] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1600, cc = STUN }, -- Uppercut (Ravager)
[28408] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1533 }, -- Whirlwind (Skirmisher)
[37108] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000, cc = SNARE }, -- Arrow Spray (Archer)
[28628] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 6800 }, -- Volley (Archer)
[74978] = { block = true, dodge = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 9000, cc = STUN }, -- Taking Aim (Archer)
[14096] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1250 }, -- Heavy Attack (Footsoldier)
[28499] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = SNARE }, -- Throw Dagger (Footsoldier)
[29400] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1400, cc = DISORIENT }, -- Power Bash (Guard)
[29761] = { power = true, priority = 3, auradetect = true, alwaysShowInterrupt = true }, -- Brace (Guard)
[13701] = { block = true, dodge = true, priority = 3, eventdetect = true, bs = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Focused Charge (Brute)
[35164] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1333, cc = STUN }, -- Agony (Berserker)
[29510] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Thunder Hammer (Thundermaul)
[17867] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Shock Aura (Thundermaul)
[81215] = { block = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STUN }, -- Shock Aura (Thundermaul - Boss)
[81195] = { avoid = true, priority = 2, auradetect = true, cc = SNARE }, -- Agonizing Fury (Thundermaul - Boss)
[81217] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1533 }, -- Thunder Hammer (Thundermaul - Boss)
[36470] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2500, cc = STUN }, -- Veiled Strike (Nightblade)
--[44345] = { block = true, avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Soul Tether (Nightblade)
[34742] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Fiery Breath (Dragonknight)
[34646] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1800 }, -- Lava Whip (Dragonknight)
[44227] = { avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Dragonknight Standard (Dragonknight - Elite)
[52041] = { block = true, dodge = true, priority = 2, bs = true, result = ACTION_RESULT_BEGIN, duration = 1667, cc = STUN }, -- Blink Strike (Dragonknight - Elite)
[88251] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Call Ally (Pet Ranger)
[88248] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Call Ally (Pet Ranger)
[89425] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Call Ally (Pet Ranger)
[44301] = { dodge = true, priority = 3, auradetect = true , ignoreRefresh = true, cc = SNARE }, -- Trap Beast (Pet Ranger)
[15164] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Heat Wave (Fire Mage)
[47095] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Fire Rune (Fire Mage)
[29471] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1800 }, -- Thunder Thrall (Storm Mage)
[12459] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Winter's Reach (Frost Mage)
[35151] = { interrupt = true, priority = 3, auradetect = true, duration = 8000, effectOnlyInterrupt = true }, -- Spell Absorption (Spirit Mage)
[14472] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Burdening Eye (Spirit Mage)
[36985] = { avoid = true, interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Void (Time Bomb Mage)
[37087] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Lightning Onslaught (Battlemage)
[37129] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Ice Cage (Battlemage)
[44216] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, cc = SILENCE }, -- Negate Magic (Battlemage - Elite)
[88554] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon the Dead (Necromancer)
[88555] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon the Dead (Necromancer)
[88556] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon the Dead (Necromancer)
[13397] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, duration = 5000 }, -- Empower Undead (Necromancer)
[14350] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1667, cc = FEAR }, -- Aspect of Terror (Fear Mage)
[44250] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Dark Shade (Dreadweaver)
[44323] = { power = true, priority = 3, auradetect = true }, -- Dampen Magic (Soulbrander)
[44258] = { power = true, priority = 3, auradetect = true }, -- Radiant Magelight (Soulbrander)
[35387] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Defiled Grave (Bonelord)
[88506] = { summon = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = "" }, -- Summon Abomination (Bonelord)
[88507] = { summon = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = "" }, -- Summon Abomination (Bonelord)
[50966] = { power = true, auradetect = true, priority = 2, alwaysShowInterrupt = true, duration = 5000 }, -- Healer Immune (Healer - Craglorn/DLC)
[44328] = { interrupt = true, priority = 2, auradetect = true, duration = 4500 }, -- Rite of Passage (Healer)
[29520] = { destroy = true, auradetect = true, priority = 2 }, -- Aura of Protection (Shaman)
[68866] = { power = true, auradetect = true, refire = 1000, priority = 2 }, -- War Horn (Faction NPC)
[43644] = { avoid = true, priority = 3, auradetect = true }, -- Barrier [monster synergy] (Faction NPCs)
[43645] = { avoid = true, priority = 3, auradetect = true }, -- Barrier [monster synergy] (Faction NPCs)
[43646] = { avoid = true, priority = 3, auradetect = true }, -- Barrier [monster synergy] (Faction NPCs)
[70070] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1250 }, -- Heavy Strike (Winterborn Warrior)
[64980] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = STAGGER }, -- Javelin (Winterborn Warrior)
[65033] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_EFFECT_GAINED, duration = 1000, cc = STAGGER }, -- Retaliation (Winterborn Warrior)
[55909] = { dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Grasping Vines (Winterborn Mage)
[64704] = { block = true, avoid = true, interrupt = true, priority = 3, eventdetect = true, refire = 1500, result = ACTION_RESULT_BEGIN, duration = 4500 }, -- Flames (Winterborn Mage)
[65235] = { power = true, auradetect = true, priority = 2 }, -- Enrage (Vosh Rakh Devoted)
[53987] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 3000 }, -- Rally (Vosh Rakh Devoted)
[54027] = { block = true, dodge = true, priority = 3, refire = 1600, result = ACTION_RESULT_BEGIN, duration = 4000, cc = STUN, neverShowInterrupt = true }, -- Divine Leap (Vosh Rakh Devoted)
[51000] = { power = true, auradetect = true, priority = 2 }, -- Cleave Stance (Dremora Caitiff) (Craglorn)
[72725] = { power = true, auradetect = true, priority = 2 }, -- Fool Me Once (Sentinel) (TG DLC)
[76089] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Snipe (Archer) (TG DLC)
--[72220] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Snipe (Archer) (TG DLC) -- This is cast from stealth - so for the time being, maybe hide.
[72222] = { power = true, auradetect = true, priority = 2 }, -- Shadow Cloak (Archer) (TG DLC)
[77472] = { power = true, auradetect = true, priority = 2 }, -- Til Death (Bodyguard) (DB DLC)
[77554] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1000 }, -- Shard Shield (Bodyguard) (DB DLC)
[77473] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STAGGER }, -- Shield Charge (Bodyguard) (DB DLC)
[77089] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1250, cc = STUN }, -- Basilisk Powder (Tracker) (Morrowind)
[77087] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Basilisk Powder (Tracker) (Morrowind)
[77019] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 766, cc = SNARE }, -- Pin (Tracker) (Morrowind)
[78432] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Lunge (Tracker) (Morrowind)
[88371] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1000 }, -- Dive (Beastcaller) (Morrowind)
[88394] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STUN }, -- Gore (Beastcaller) (Morrowind)
[88409] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Raise the Earth (Beastcaller)
[87901] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Bombard (Arbalest) (Morrowind)
[87422] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Chilled Ground (Arbalest) (Morrowind)
[87713] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1300, cc = STAGGER }, -- Quakeshot (Arbalest) (Morrowind)
[85359] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1267 }, -- Reverse Slash (Drudge)
[87064] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000, cc = STUN }, -- Volcanic Debris (Fire-Binder) (Morrowind)
[88845] = { interrupt = true, priority = 3, auradetect = true, duration = 15000, effectOnlyInterrupt = true }, -- Empower Atronach (Fire-Binder) (Morrowind)
[76621] = { block = true, avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Shadeway (Voidbringer) (Morrowind)
[76619] = { avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Pool of Shadow (Voidbringer) (Morrowind)
[76979] = { block = true, avoid = true, priority = 3, auradetect = true, duration = 5000, cc = STUN, neverShowInterrupt = true }, -- Shadowy Duplicate (Voidbringer) (Morrowind)
[88327] = { block = true, avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Shadeway (Skaafin Masquer) (Morrowind)
[88325] = { avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Pool of Shadow (Skaafin Masquer) (Morrowind)
[88348] = { block = true, avoid = true, priority = 3, auradetect = true, duration = 5000, cc = STUN, neverShowInterrupt = true }, -- Shadowy Duplicate (Skaafin Masquer) (Morrowind)
[84818] = { interrupt = true, priority = 3, auradetect = true, duration = 4000 }, -- Fiendish Healing (Skaafin Witchling) (Morrowind)
[84835] = { avoid = true, priority = 2, eventdetect = true }, -- Broken Pact (Skaafin) (Morrowind)
-- ANIMALS
[5452] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Lacerate (Alit)
[4415] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1600, cc = STUN }, -- Crushing Swipe (Bear)
[4416] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2000, cc = STAGGER }, -- Savage Blows (Bear)
[70366] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2167, cc = STUN }, -- Slam (Great Bear)
[4591] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 970 }, -- Sweep (Crocodile)
[4594] = { power = true, auradetect = true, priority = 2, ignoreRefresh = true, refire = 500 }, -- Ancient Skin (Crocodile)
[8977] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1721 }, -- Sweep (Duneripper)
[7227] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1100 }, -- Rotbone (Durzog)
[6308] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2500, cc = STAGGER }, -- Shocking Touch (Dreugh)
[6328] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 2000, duration = 3600 }, -- Shocking Rake (Dreugh)
[54375] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1300, cc = STAGGER }, -- Shockwave (Echatere)
[54380] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1300, cc = STUN }, -- Headbutt (Echatere)
[4632] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = STUN }, -- Screech (Giant Bat)
[4630] = { dodge = true, interrupt = true, priority = 3, refire = 1500, result = ACTION_RESULT_BEGIN, duration = 1800 }, -- Draining Bite (Giant Bat)
[5240] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2600, cc = STAGGER }, -- Lash (Giant Snake)
[5242] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Kiss of Poison (Giant Snake)
[5244] = { interrupt = true, priority = 3, auradetect = true, duration = 5000 }, -- Shed Skin (Giant Snake)
[5441] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Dive (Guar)
[14196] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Charge (Kagouti)
[5363] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Chomp (Kagouti)
[5926] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Toss (Kagouti)
[87276] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Chomp (Kagouti Whelp)
[7161] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Double Strike (Lion)
[8601] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 600, duration = 6000 }, -- Vigorous Swipe (Mammoth)
[8600] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_EFFECT_GAINED, duration = 3000, cc = STAGGER }, -- Stomp (Mammoth)
[23230] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Charge (Mammoth)
[4200] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Unforgiving Claws (Mudcrab)
[16690] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2000, cc = STAGGER }, -- Thrust (Netch)
[16697] = { avoid = true, interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 1800, duration = 7500 }, -- Poisonbloom (Netch)
[7268] = { interrupt = true, priority = 3, refire = 500, result = ACTION_RESULT_BEGIN, duration = 5650 }, -- Leech
[7273] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Dampworm (Nix-Hound)
[21904] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Rend (Skeever)
[21951] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 4900, neverShowInterrupt = true }, -- Repulsion Shock (Wamasu)
[21949] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1400, cc = STUN, neverShowInterrupt = true }, -- Sweep (Wamasu)
[21957] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Charge (Wamasu)
[22045] = { power = true, auradetect = true, priority = 2 }, --- Static (Wamasu)
[55866] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 4900, neverShowInterrupt = true }, -- Repulsion Shock (Wamasu - Boss)
[55868] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1200, cc = STUN, neverShowInterrupt = true }, -- Sweep (Wamasu - Boss)
[55850] = { avoid = true, interrupt = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Impending Storm (Wamasu - Boss)
[55860] = { dodge = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1700, cc = SNARE }, -- Storm Bound (Storm Atronach)
[44791] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1800 }, -- Rear Kick (Welwa)
[50714] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, cc = STUN }, -- Charge (Welwa)
[42844] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1100 }, -- Rotbone (Wolf)
[14523] = { dodge = true, interrupt = true, priority = 3, refire = 1000, result = ACTION_RESULT_BEGIN, duration = 6800, cc = SNARE }, -- Helljoint (Wolf)
[14272] = { summon = true, auradetect = true, priority = 2, fakeName = "" }, -- Call of the Pack (Wolf)
[26658] = { summon = true, auradetect = true, priority = 2, fakeName = "" }, -- Call of the Pack (Jackal)
[72793] = { dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1767, cc = SNARE }, -- Toxic Mucus (Haj Mota)
[72796] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Bog Burst (Haj Mota)
[72789] = { avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1667, cc = STAGGER }, -- Shockwave (Haj Mota)
[76307] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1467 }, -- Lunge (Dire Wolf)
[76324] = { power = true, auradetect = true, priority = 2, refire = 1000 }, -- Baleful Call (Dire Wolf)
[85201] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1167, cc = STAGGER }, -- Bite (Nix-Ox)
[85084] = { block = true, avoid = true, priority = 3, eventdetect = true, refire = 750, result = ACTION_RESULT_BEGIN, duration = 500, cc = STAGGER }, -- Shriek (Nix-Ox)
[90765] = { avoid = true, priority = 3, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN }, -- Acid Spray (Nix-Ox)
[90809] = { avoid = true, priority = 3, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN }, -- Acid Spray (Nix-Ox)
[85172] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 500, cc = STUN }, -- Winnow (Nix-Ox)
[85203] = { power = true, auradetect = true, priority = 2, refire = 1000 }, -- Nix-Call (Nix-Ox)
[85395] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = STUN, duration = 1333 }, -- Dive (Cliff Strider)
[85399] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Retch (Cliff Strider)
[85390] = { block = true, dodge = true, priority = 3, eventdetect = true, refire = 750, result = ACTION_RESULT_BEGIN, duration = 1600, cc = SNARE }, -- Slash (Cliff Strider)
-- INSECTS
[6137] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 800 }, -- Laceration (Assassin Beetle)
[5268] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Collywobbles (Assassin Beetle)
[6757] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Blurred Strike (Giant Scorpion)
[6756] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Paralyze (Giant Scorpion)
[6758] = { power = true, auradetect = true, priority = 2, ignoreRefresh = true, refire = 500 }, -- Hardened Carapace (Giant Scorpion)
[44086] = { avoid = true, priority = 3, auradetect = true, ignoreRefresh = true }, -- Fire Runes (Giant Spider)
[5685] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Corrosive Bite (Giant Spider)
[8087] = { avoid = true, priority = 3, eventdetect = true, refire = 1200, result = ACTION_RESULT_BEGIN, duration = 5100 }, -- Poison Spray (Giant Spider)
[4737] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Encase (Giant Spider)
[13382] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Devour (Giant Spider)
[9226] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1400 }, -- Sting (Wasp)
[25110] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Focused Charge (Giant Wasp)
[9229] = { dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000, cc = UNBREAKABLE }, -- Inject Larva (Giant Wasp)
[6800] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Bloodletting (Hoarvor)
[6795] = { interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 7850 }, -- Latch On (Hoarvor)
[61244] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Fevered Retch (Necrotic Hoarvor)
[61360] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 5500 }, -- Infectious Swarm (Necrotic Hoarvor)
[61427] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, duration = 1200, cc = SNARE, neverShowInterrupt = true }, -- Necrotic Explosion (Necrotic Hoarvor)
[14841] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Focused Charge (Kwama Worker)
[9769] = { block = true, dodge = true, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 3267 }, -- Excavation (Kwama Warrior)
[5260] = { avoid = true, priority = 3, eventdetect = true, refire = 750, result = ACTION_RESULT_BEGIN, duration = 2700 }, -- Flamethrower (Shalk)
[5252] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1100 }, -- Fire Bite (Shalk)
[5262] = { avoid = true, interrupt = true, priority = 3, auradetect = true, duration = 4000 }, -- Burning Ground (Shalk)
[8429] = { interrupt = true, priority = 3, refire = 750, result = ACTION_RESULT_BEGIN, duration = 4600 }, -- Zap (Thunderbug)
[26412] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Thunderstrikes (Thunderbug)
[73172] = { dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 3667, cc = SNARE }, -- Swarm (Kotu Gava Broodmother)
[73199] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, cc = SNARE }, -- Swarmburst (Kotu Gava Broodmother)
[87022] = { summon = true, auradetect = true, priority = 3, fakeName = "" }, -- Summon Swarm (Fetcherfly Nest)
[85645] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1000 }, -- Bombard (Fetcherfly Nest)
[87125] = { avoid = true, interrupt = true, priority = 3, auradetect = true, duration = 8000 }, -- Heat Vents (Fetcherfly Nest)
[92078] = { destroy = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Colonize (Fetcherfly Hive Golem)
[87062] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 4000, cc = SILENCE }, -- Fetcherfly Storm (Fetcherfly Hive Golem)
[87030] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 867 }, -- Focused Swarm (Fetcherfly Hive Golem)
-- DAEDRA
[31115] = { destroy = true, refire = 1000, priority = 2, auradetect = true }, -- Summon Dark Anchor (Daedric Synergy)
[68449] = { avoid = true, refire = 1000, priority = 3, duration = 500 }, -- Explosive Charge (Daedric Synergy)
[48121] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Heavy Attack (Air Atronach)
[48137] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Tornado (Air Atronach)
[51262] = { power = true, auradetect = true, priority = 2 }, -- Air Atronach Flame (Air Atronach)
[51271] = { power = true, auradetect = true, priority = 2 }, -- Air Atronach Flame (Air Atronach)
[51269] = { power = true, auradetect = true, priority = 2 }, -- Air Atronach Flame (Air Atronach)
[51281] = { avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 1500, duration = 3250 }, -- Flame Tornado (Air Atronach)
[50021] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Ice Vortex (Air Atronach)
[50023] = { block = true, interrupt = true, priority = 3, refire = 800, result = ACTION_RESULT_BEGIN, duration = 4600 }, -- Lightning Rod (Air Atronach)
[9747] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Dire Wound (Banekin)
[9748] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 3000 }, -- Envelop (Banekin)
[4799] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STAGGER }, -- Tail Spike (Clannfear)
[93745] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Rending Leap (Clannfear)
[26641] = { avoid = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Soul Flame (Daedric Titan)
[34405] = { block = true, avoid = true, priority = 2, auradetect = true, duration = 2200 }, -- Swallowing Souls (Daedric Titan)
[26554] = { block = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STUN }, -- Wing Gust (Daedric Titan)
[4771] = { avoid = true, priority = 3, eventdetect = true, refire = 1250, result = ACTION_RESULT_BEGIN, duration = 3100 },-- Fiery Breath (Daedroth)
[91946] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1000, cc = STAGGER }, -- Ground Tremor (Daedroth)
[91937] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1767, cc = STUN }, -- Burst of Embers (Daedroth)
[26324] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1300 }, -- Lava Geyser (Flame Atronach)
[50216] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, refire = 250, duration = 2000, neverShowInterrupt = true }, -- Combustion (Flame Atronach)
[5017] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 2500, cc = STUN }, -- Hoarfrost Fist (Frost Atronach)
[33502] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Frozen Ground (Frost Atronach)
[50626] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2750 }, -- Shadow Strike (Grevious Twilight)
[65889] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 2750 }, -- Shadow Strike (Grevious Twilight)
[4829] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Fire Brand (Flesh Atronach)
[4817] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Unyielding Mace (Flesh Atronach)
[67870] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1700, cc = STAGGER }, -- Tremor AOE (Flesh Colossus)
[66869] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Pin (Flesh Colossus)
[67872] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1600, cc = STUN }, -- Sweep (Flesh Colossus)
[76139] = { block = true, dodge = true, priority = 2, auradetect = true, cc = STUN }, -- Stumble Forward (Flesh Colossus)
--[67772] = { power = true, priority = 2, auradetect = true }, -- Enraged (Flesh Colossus)
[49430] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1750 }, -- Smash (Flesh Colossus)
[49429] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1250 }, -- Claw (Flesh Colossus)
[11079] = { avoid = true, interrupt = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1300, cc = STAGGER }, -- Black Winter (Harvester)
[26017] = { summon = true, priority = 2, auradetect = true, fakeName = "", refire = 1000 }, -- Creeping Doom (Harvester)
[8205] = { interrupt = true, priority = 3, auradetect = true, duration = 6000 }, -- Regeneration (Ogrim)
[24690] = { block = true, dodge = true, priority = 3, bs = true, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Focused Charge (Ogrim)
[91848] = { dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1970, cc = SNARE }, -- Stomp (Ogrim)
[91855] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000, cc = STUN }, -- Boulder Toss (Ogrim)
[6166] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500 }, -- Heat Wave (Scamp)
[6160] = { avoid = true, interrupt = true, priority = 3, auradetect = true, duration = 5000 }, -- Rain of Fire (Scamp)
[8779] = { block = true, interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Lightning Onslaught (Spider Daedra)
[89306] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Web (Spiderling)
[8782] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Lightning Storm (Spider Daedra)
[8773] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon Spiderling (Spider Daedra)
[35220] = { avoid = true, interrupt = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Impending Storm (Storm Atronach)
--[4864] = { dodge = true, priority = 2, result = ACTION_RESULT_EFFECT_GAINED, refire = 100, cc = SNARE }, -- Storm Bound (Storm Atronach)
[7095] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1400 }, -- Heavy Attack (Xivilai)
[88947] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Lightning Grasp (Xivilai)
[7100] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1333 }, -- Hand of Flame (Xivilai)
[25726] = { summon = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = "" }, -- Summon Daedra (Xivilai)
[4653] = { block = true, avoid = true, priority = 2, eventdetect = true, cc = SNARE }, -- Shockwave (Watcher)
[9219] = { block = true, avoid = true, priority = 2, eventdetect = true, refire = 1750, cc = STUN }, -- Doom-Truth's Gaze (Watcher)
[14425] = { block = true, avoid = true, priority = 2, cc = STUN }, -- Doom-Truth's Gaze (Watcher)
[6410] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1700 }, -- Tail Clip (Winged Twilight)
[6412] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = STUN }, -- Dusk's Howl (Winged Twilight)
[94903] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true, duration = 1200, cc = STAGGER }, -- Spring (Hunger)
[87237] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true, duration = 667, cc = STAGGER }, -- Spring (Hunger)
[87252] = { power = true, refire = 400, priority = 2, auradetect = true, noSelf = true, duration = 6000, cc = STUN, effectOnlyInterrupt = true }, -- Devour (Hunger)
[84944] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true, duration = 2300, cc = STUN }, -- Hollow (Hunger)
[87269] = { avoid = true, eventdetect = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true, duration = 1400, cc = STUN }, -- Torpor (Hunger)
[88282] = { avoid = true, eventdetect = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 767 }, -- Rock Stomp (Iron Atronach)
[88261] = { block = true, eventdetect = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 800 }, -- Lava Wave (Iron Atronach)
[88297] = { avoid = true, auradetect = true, priority = 2, duration = 6000, effectOnlyInterrupt }, -- Blast Furnace (Iron Atronach)
-- UNDEAD
[8569] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN, duration = 1300, cc = STAGGER }, -- Devastating Leap (Bloodfiend)
[5050] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Bone Saw (Bone Colossus)
[5030] = { summon = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, fakeName = "" }, -- Voice to Wake the Dead (Bone Colossus)
[17207] = { block = true, dodge = true, priority = 3, auradetect = true, duration = 2500, neverShowInterrupt = true }, -- Necromantic Implosion (Risen Dead)
[18514] = { block = true, dodge = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = SNARE }, -- Chill Touch (Ghost)
[19137] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, cc = FEAR }, -- Haunting Spectre (Ghost)
[73925] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, cc = STUN }, -- Soul Cage (Lich)
[50182] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Consuming Energy (Spellfiend)
[68735] = { interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 6000 }, -- Vampiric Drain (Vampire)
[2867] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1400, cc = STAGGER }, -- Crushing Leap (Werewolf)
[3415] = { block = true, dodge = true, priority = 3, eventdetect = true, refire = 1100, result = ACTION_RESULT_BEGIN, duration = 4667, cc = STUN }, -- Flurry (Werewolf)
[44055] = { interrupt = true, priority = 3, auradetect = true, duration = 4000 }, -- Devour (Werewolf)
[5785] = { power = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Blood Scent (Werewolf)
[4337] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = SNARE }, -- Winter's Reach (Wraith)
[2969] = { block = true, dodge = true, bs = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200, cc = STAGGER }, -- Pound (Zombie)
[2960] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2100 }, -- Vomit (Zombie)
[72979] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Dissonant Blow (Defiled Aegis)
[72995] = { interrupt = true, dodge = true, priority = 2, eventdetect = true, refire = 1100, result = ACTION_RESULT_BEGIN, duration = 6100 }, -- Symphony of Blades (Defiled Aegis) -- Higher priority because damage is very high
[76180] = { summon = true, auradetect = true, priority = 2, fakeName = "" }, -- Shattered Harmony (Defiled Aegis)
-- MONSTERS
[10270] = { block = true, avoid = true, priority = 2, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN, duration = 2550 }, -- Quake (Gargoyle)
[10256] = { block = true, bs = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Lacerate (Gargoyle)
[26124] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 1800 }, -- Shatter (Giant)
[15715] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, duration = 3000, cc = STUN }, -- Obliterate (Giant)
[2786] = { interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 1250, duration = 6100 }, -- Steal Essence (Hag)
[2821] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 700, cc = STUN }, -- Luring Snare (Hag)
[3349] = { power = true, priority = 2, auradetect = true, duration = 8000 }, -- Reflective Shadows (Hag)
[10615] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1800, cc = STAGGER }, -- Raven Storm (Hagraven)
[10613] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2050, neverShowInterrupt = true }, -- Fire Bomb (Hagraven)
[64808] = { power = true, priority = 2, auradetect = true }, -- Briarheart Ressurection (Hagraven)
[4123] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1200 }, -- Wing Slice (Harpy)
[13515] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1800, cc = STUN }, -- Wind Gust (Harpy)
[24604] = { avoid = true, interrupt = true, eventdetect = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 8000 }, -- Charged Ground (Harpy)
[4689] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1300 }, -- Lightning Gale (Harpy)
[43809] = { avoid = true, priority = 3, auradetect = true, duration = 1750, cc = STUN, neverShowInterrupt = true }, -- Shard Burst (Ice Wraith)
[24866] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, cc = SNARE }, -- Focused Charge (Ice Wraith)
[17703] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 750, duration = 4550 }, -- Flame Ray (Imp - Fire)
[8884] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 750, duration = 4550 }, -- Zap (Imp - Lightning)
[81794] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 750, duration = 4600 }, -- Frost Ray (Imp - Frost)
[9671] = { block = true, bs = true, eventdetect = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Howling Strike (Lamia)
[9674] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STAGGER }, -- Resonate (Lamia)
[7835] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, duration = 2000 }, -- Convalescence (Lamia)
[7831] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 2500, duration = 5000 }, -- Harmony (Lamia)
[9680] = { summon = true, auradetect = true, priority = 2, fakeName = "" }, -- Summon Spectral Lamia
[3860] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 500, cc = STAGGER }, -- Pulverize (Lurcher)
[3855] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 1500, cc = STUN }, -- Crushing Limbs (Lurcher)
[3767] = { avoid = true, interrupt = true, priority = 3, eventdetect = true, refire = 1100, result = ACTION_RESULT_BEGIN, duration = 5600 }, -- Choking Pollen (Lurcher)
[5559] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN, duration = 2200, neverShowInterrupt = true }, -- Icy Geyser (Nereid)
[5540] = { avoid = true, interrupt = true, priority = 3, auradetect = true, duration = 8000, cc = SNARE }, -- Hurricane (Nereid)
[24985] = { power = true, auradetect = true, priority = 3 }, -- Intimidating Roar (Ogre)
[5881] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Smash (Ogre)
[5256] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Shockwave (Ogre)
[53142] = { destroy = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Ice Pillar (Ogre Shaman)
[64540] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Freeze Wounds (Ogre Shaman)
[53137] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Freeze Wounds (Ogre Shaman)
[21582] = { block = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Nature's Swarm (Spriggan)
[13475] = { interrupt = true, priority = 3, auradetect = true }, -- Healing Salve (Spriggan)
[13477] = { interrupt = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Control Beast (Spriggan)
[89119] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon Beast (Spriggan)
[89102] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Summon Beast (Spriggan)
[9346] = { interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Strangle (Strangler)
[9322] = { avoid = true, priority = 3, auradetect = true }, -- Poisoned Ground (Strangler)
[9321] = { block = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 500 }, -- Grapple (Strangler)
[44736] = { block = true, dodge = true, priority = 2, eventdetect = true, refire = 2000, result = ACTION_RESULT_BEGIN }, -- Swinging Cleave (Troll)
[9009] = { avoid = true, priority = 2, eventdetect = true, refire = 300, result = ACTION_RESULT_BEGIN }, -- Tremor (Troll)
[76268] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Lope (River Troll)
[76277] = { interrupt = true, priority = 2, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN, duration = 5233 }, -- Close Wounds (River Troll)
[76295] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Crab Toss (River Troll)
[48256] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Boulder Toss (Troll - Ranged)
[48282] = { interrupt = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Consuming Omen (Troll - Ranged)
[4309] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Dying Blast (Wisp)
[7976] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Rain of Wisps (Wispmother)
[18040] = { power = true, priority = 2, auradetect = true }, -- Clone (Wispmother)
[75867] = { block = true, bs = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Clobber (Minotaur)
[75917] = { block = true, dodge = true, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Ram (Minotaur)
[79541] = { block = true, dodge = true, priority = 2, auradetect = true, result = ACTION_RESULT_BEGIN }, -- Flying Leap (Minotaur)
[75925] = { power = true, auradetect = 2, priority = 2, ignoreRefresh = true }, -- Elemental Weapon (Minotaur)
[75951] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Brimstone Hailfire (Minotaur Shaman)
[75955] = { avoid = true, priority = 2, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN }, -- Pillars of Nirn (Minotaur Shaman)
[75994] = { power = true, priority = 2, auradetect = true, ignoreRefresh = true }, -- Molten Armor (Minotaur Shaman)
[49499] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Spear Throw (Mantikora)
[49404] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Rear Up (Mantikora)
[49402] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Tail Whip (Mantikora)
[50187] = { power = true, priority = 2, auradetect = true }, -- Enrage (Mantikora)
[56689] = { power = true, priority = 2, auradetect = true }, -- Enraged (Mantikora)
[104479] = { block = true, bs = true, dodge = true, interrupt = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Reave (Yaghra Strider)
[105214] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Lunge (Yaghra Strider)
[105330] = { interrupt = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Frenzy (Yaghra Strider)
[103804] = { interrupt = true, avoid = true, eventdetect = true, priority = 2, result = ACTION_RESULT_BEGIN, refire = 800 }, -- Deluge (Yaghra Strider)
[103931] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Luminescent Mark (Yaghra Spewer)
-- DWEMER
[16031] = { avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Ricochet Wave (Dwemer Sphere)
[7520] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Steam Wall (Dwemer Sphere)
[7544] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Quake (Dwemer Sphere)
[11247] = { block = true, dodge = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Sweeping Spin (Dwemer Centurion)
[11246] = { avoid = true, priority = 2, eventdetect = true, refire = 2000, result = ACTION_RESULT_BEGIN }, -- Steam Breath (Dwemer Centurion)
[20507] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Double Strike (Dwemer Spider)
[7717] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Detonation (Dwemer Spider)
[19970] = { power = true, priority = 3, auradetect = true }, -- Static Field (Dwemer Spider - Overcharge Synergy)
--[20207] = { interrupt = true, priority = 3, eventdetect = true }, -- Overcharge (Dwemer Spider - Overcharge Synergy)
[20505] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, refire = 250 }, -- Overcharge (Dwemer Spider - Overcharge Synergy)
[20222] = { block = true, avoid = true, priority = 3, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, refire = 250 }, -- Overcharge (Dwemer Spider - Overcharge Synergy)
[64479] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Thunderbolt (Dwemer Sentry)
[88668] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Impulse Mine (Dwemer Arquebus)
[85270] = { interrupt = true, priority = 3, refire = 1500, result = ACTION_RESULT_BEGIN }, -- Shock Barrage (Dwemer Arquebus)
[85319] = { avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Siege Ballista (Dwemer Arquebus)
[85326] = { interrupt = true, priority = 3, eventdetect = true, refire = 1000, result = ACTION_RESULT_BEGIN }, -- Polarizing Field (Dwemer Arquebus)
--------------------------------------------------
-- FRIENDLY NPC ----------------------------------
--------------------------------------------------
[42905] = { power = true, priority = 1, auradetect = true }, -- Recover (Friendly NPC)
--------------------------------------------------
-- MAIN QUEST ------------------------------------
--------------------------------------------------
-- MSQ Tutorial (Soul Shriven in Coldharbour)
-- [61748] = { block = true, priority = 1}, -- Heavy Attack (Tutorial) -- Default game tutorials display regardless
-- [61916] = { interrupt = true, priority = 1}, -- Heat Wave (Tutorial) -- Default game tutorials display regardless
[63269] = { block = true, avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Heat Wave (Tutorial)
[63737] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN }, -- Heavy Attack (Tutorial)
[63684] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN }, -- Uppercut (Tutorial)
[63761] = { block = true, dodge = true, priority = 3, bs = true, result = ACTION_RESULT_BEGIN }, -- Pound (Tutorial)
[63752] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Vomit (Tutorial)
[63755] = { block = true, avoid = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Heat Wave (Tutorial)
[63521] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Bone Crush (Tutorial)
-- MSQ 2 (Daughter of Giants)
[27767] = { block = true, bs = true, dodge = true, priority = 2 }, -- Rending Leap (Ancient Clannfear)
[28788] = { block = true, priority = 2, eventdetect = true }, -- MQ2_Boss1_Doom-Truth'sGaze (Manifestation of Terror)
[28723] = { avoid = true, priority = 2, eventdetect = true, refire = 500 }, -- Gravity Well (Manifestation of Terror)
-- MSQ 4 (Castle of the Worm)
[34484] = { block = true, avoid = true, priority = 2, skipcheck = true, refire = 500 }, -- Soul Cage (Mannimarco)
-- MSQ 6 (Halls of Torment)
[36858] = { interrupt = true, avoid = true, priority = 2, eventdetect = true, refire = 1500 }, -- Swordstorm (Tharn Doppleganger)
[37173] = { interrupt = true, priority = 2, eventdetect = true }, -- Flame Shield (Duchess of Anguish)
[38729] = { block = true, interrupt = true, priority = 2, refire = 500 }, -- Royal Strike (Duchess of Anguish)
-- MSQ 7 (Shadow of Sancre Tor)
[39302] = { interrupt = true, priority = 2, eventdetect = true, refire = 1000 }, -- Necromantic Revival
[38215] = { interrupt = true, priority = 2, refire = 1000 }, -- Death's Gaze (Mannimarco)
[40425] = { avoid = true, priority = 2 }, -- Impending Doom (Mannimarco)
[40973] = { power = true, priority = 2, eventdetect = true }, -- Portal Spawn (Mannimarco)
[40978] = { power = true, priority = 2, eventdetect = true }, -- Portal Spawn (Mannimarco)
[40981] = { power = true, priority = 2, eventdetect = true }, -- Portal Spawn (Mannimarco)
--------------------------------------------------
-- GUILD QUESTS ----------------------------------
--------------------------------------------------
-- The Prismatic Core
[39577] = { block = true, interrupt = true, priority = 2 }, -- Palolel's Rage (Queen Palolel)
-- Will of the Council
[28939] = { avoid = true, priority = 2, eventdetect = true, refire = 2000 }, -- Heat Wave (Sees-All-Colors)
-- The Mad God's Bargain
[39555] = { interrupt = true, priority = 2, eventdetect = true, refire = 1500 }, -- Summon Scamp (Haskill)
[39527] = { interrupt = true, avoid = true, block = true, priority = 2, refire = 1500 }, -- Skeleton Trap (Haskill)
[35533] = { interrupt = true, priority = 2, refire = 1500 }, -- Polymorph (Haskill)
[39391] = { interrupt = true, priority = 2, eventdetect = true, refire = 1500 }, -- Summon Pig (Haskill)
--------------------------------------------------
-- AD QUESTS -------------------------------------
--------------------------------------------------
-- World Boss - Seaside Scarp Camp
[84283] = { block = true, dodge = true, priority = 1, eventdetect = true }, -- Coursing Bones (Oskana)
-- World Boss - Heretic's Summons
[83150] = { block = true, dodge = true, priority = 1 }, -- Tail Whip (Snapjaw)
[83009] = { block = true, dodge = true, priority = 1 }, -- Rending Leap (Snapjaw)
[83040] = { block = true, dodge = true, bs = true, priority = 1, eventdetect = true, skipcheck = true }, -- Focused Charge (Clannfear - Snapjaw)
[83016] = { block = true, priority = 1, refire = 1000, eventdetect = true, skipcheck = true }, -- Necrotic Explosion (Clannfear - Snapjaw)
-- Sever All Ties
[44138] = { interrupt = true, avoid = true, priority = 2, eventdetect = true }, -- Q4261 Estre Knockback (High Kinlady Estre)
-- World Boss - Nindaeril's Perch
[83515] = { block = true, bs = true, dodge = true, priority = 1 }, -- Hunter's Pounce (Bavura the Blizzard)
[83832] = { block = true, dodge = true, priority = 1, eventdetect = true }, -- Frenzied Charge (Nindaeril the Monsoon)
[83548] = { interrupt = true, avoid = true, priority = 1, eventdetect = true }, -- Mighty Roar (Nindaeril the Monsoon)
-- The Grips of Madness
[38748] = { block = true, interrupt = true, priority = 2 }, -- Aulus's Tongue (Mayor Aulus)
[40702] = { avoid = true, priority = 2, eventdetect = true }, -- Q4868 Aulus Knockback (Mayor Aulus)
-- The Orrery of Elden Root
[43820] = { dodge = true, avoid = true, priority = 2, eventdetect = true }, -- Quaking Stomp (Prince Naemon)
[43827] = { avoid = true, priority = 2, auradetect = true }, -- Projectile Vomit (Prince Naemon)
-- World Boss - Gathongor's Mine
[84205] = { avoid = true, priority = 1 }, -- Stinging Sputum (Gathongor the Mauler)
[84196] = { avoid = true, priority = 1 }, -- Marsh Masher (Gathongor the Mauler)
[84209] = { block = true, dodge = true, priority = 1 }, -- Wrecking Jaws (Gathongor the Mauler)
[84212] = { avoid = true, priority = 1 }, -- Bog Slam (Gathongor the Mauler)
-- World Boss - Thodundor's View
[83155] = { block = true, bs = true, dodge = true, priority = 1 }, -- Thunderous Smash (Thodundor of the Hill)
[83160] = { block = true, avoid = true, priority = 1 }, -- Stone Crusher (Thodundor of the Hill)
[83136] = { block = true, avoid = true, priority = 1 }, -- Ground Shock (Thodundor of the Hill)
--------------------------------------------------
-- VVARDENFELL -----------------------------------
--------------------------------------------------
-- Tutorial
-- [83416] = { block = true, priority = 1}, -- Heavy Attack (Tutorial) -- Default game tutorials display regardless
-- [92233] = { interrupt = true, priority = 1}, -- Throw Dagger (Tutorial) -- Default game tutorials display regardless
[92668] = { block = true, dodge = true, priority = 3, eventdetect = true, result = ACTION_RESULT_BEGIN }, -- Whirlwind (Slaver Cutthroat)
-- Main Quest
[87958] = { avoid = true, interrupt = true, priority = 2 }, -- Ash Storm (Divine Delusions)
[90139] = { block = true, dodge = true, priority = 2, bs = true }, -- Empowered Strike (Divine Intervention)
[90181] = { avoid = true, priority = 2 , refire = 1500 }, -- Oily Smoke (Divine Restoration)
[87038] = { block = true, dodge = true, priority = 2, bs = true}, -- Spinning Blades (Divine Restoration)
[87047] = { block = true, dodge = true, priority = 2, refire = 1500 }, -- Lunge (Divine Restoration)
[87090] = { block = true, dodge = true, priority = 2}, -- Barbs (Divine Restoration)
[90616] = { block = true, avoid = true, priority = 2, refire = 10000, skipcheck = true}, -- Divine Hijack (Divine Restoration)
-- Sidequests
[92720] = { block = true, avoid = true, priority = 2}, -- Necrotic Wave (Ancestral Adversity)
[77541] = { block = true, dodge = true, priority = 2}, -- Brand's Cleave (The Heart of a Telvanni)
-- Delves/Public Dungeons/World
[88427] = { block = true, dodge = true, priority = 3, bs = true, auradetect = true}, -- Charge (Kwama Worker - Matus-Akin Egg Mine)
[86983] = { interrupt = true, priority = 2}, -- Succubus Touch (Echoes of a Fallen House)
[86930] = { block = true, dodge = true, interrupt = true, priority = 2}, -- Volcanic Debris (The Forgotten Wastes)
[92702] = { block = true, dodge = true, interrupt = true, priority = 2}, -- Volcanic Debris (The Forgotten Wastes)
[89210] = { block = true, avoid = true, priority = 3}, -- Boulder Toss (Nchuleftingth - Mud-Tusk)
[86570] = { block = true, dodge = true, priority = 3}, -- Shield Charge (Nchuleftingth - Renduril the Hammer)
[90597] = { block = true, avoid = true, priority = 2}, -- Overcharge Expulsion
--------------------------------------------------
-- SUMMERSET -------------------------------------
--------------------------------------------------
[105601] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Explosive Toxins (Yaghra Larva)
[107282] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Impale (Yaghra Nightmare)
[105867] = { avoid = true, priority = 2, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Pustulant Explosion (Yaghra Nightmare)
--------------------------------------------------
-- ARENAS ----------------------------------------
--------------------------------------------------
-- Dragonstar Arena
-- Stage 1
[52729] = { power = true, priority = 1, auradetect = true }, -- Expert Hunter (Fighters Guild Swordmaster)
[52738] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Ring of Preservation (Fighters Guild Gladiator)
[82996] = { power = true, priority = 1, auradetect = true }, -- Enrage (Fighters Guild Gladiator)
[52746] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.Boss_Champion_Marcauld }, -- Flawless Dawnbreaker (Champion Marcauld)
-- Stage 2 - The Frozen Ring
[53264] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true }, -- Rally (Sovngarde Slayer)
[53313] = { avoid = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1500 }, -- Volley (Sovngarde Slayer)
[53286] = { interrupt = true, block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Crushing Shock (Sovngarde Icemage)
[53274] = { avoid = true, priority = 1, auradetect = true, bossMatch = U.Boss_Katti_Ice_Turner }, -- Unstable Wall of Frost (Sovngarde Icemage)
[53250] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Wrecking Blow (Yavni Frost-Skin)
[53301] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossMatch = U.Boss_Katti_Ice_Turner }, -- Icy Pulsar (Katti Ice-Turner)
-- Stage 3 - The Marsh
[8244] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Devastate (Corprus Husk)
[8247] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 1750 }, -- Vomit (Corprus Husk)
[22109] = { avoid = true, priority = 3, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, refire = 250 }, -- Contaminate (Corprus Husk)
[83493] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1000 }, -- CLST - Poison Cloud (Poison Cloud)
[56796] = { power = true, priority = 1, auradetect = true }, -- Bound Aegis (Dragonclaw Hedge Wizard)
[53613] = { power = true, priority = 1, auradetect = true }, -- Thundering Presence (Nak'tah)
[53624] = { avoid = true, priority = 1, auradetect = true, bossMatch = U.Boss_Nak_tah }, -- Lightning Flood (Nak'tah)
[53659] = { block = true, avoid = true, interrupt = true, priority = 1, auradetect = true }, -- Power Overload Heavy Attack (Nak'tah)
-- Stage 4 - The Slave Pit
[54160] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, refire = 750, eventdetect = true, fakeName = U.NPC_House_Dres_Slaver }, -- Berserker Frenzy (House Dres Slaver)
[83774] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, refire = 750 }, -- Enslavement (House Dres Slaver)
[54056] = { power = true, priority = 1, auradetect = true, refire = 500 }, -- Molten Armaments (Earthen Heart Knight)
[54065] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Igneous Shield (Earthen Heart Knight)
[54077] = { avoid = true, priority = 1, auradetect = true, bossMatch = U.Boss_Earthen_Heart_Knight }, -- Cinder Storm (Earthen Heart Knight)
[54053] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Stone Giant (Earthen Heart Knight)
[54083] = { power = true, priority = 1, auradetect = true }, -- Corrosive Armor (Earthen Heart Knight)
[54067] = { block = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Fossilize (Earth Heart Knight)
-- Stage 5 - The Celestial Ring
[51352] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Petrify (Gargoyle)
[54411] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_Anka_Ra_Shadowcaster }, -- Celestial Blast (Anka-Ra Shadowcaster)
[54404] = { unmit = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, fakeName = U.NPC_Anka_Ra_Shadowcaster }, -- Celestial Blast (Anka-Ra Shadowcaster)
[52897] = { avoid = true, priority = 1, auradetect = true, bossName = true }, -- Standard of Might (Anal'a Tu'wha)
[52891] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossMatch = U.Boss_Anala_tuwha }, -- Flames of Oblivion (Anal'a Tu'wha)
-- Stage 6 - The Grove
[54608] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Drain Resource (Pacthunter Ranger)
--[54512] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true }, -- Regeneration Aura (Nature's Blessing)
[52820] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Acid Spray (Pishna Longshot)
[52825] = { block = true, dodge = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Lethal Arrow (Pishna Longshot)
-- Stage 7 - Circle of Rituals
[56946] = { power = true, priority = 1, auradetect = true }, -- Dragon Fire Scale (Bloodwraith Kynval)
[54634] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true }, -- CLDA - Sacrifice (Daedric Sacrifice)
[54635] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true }, -- CLDA - Sacrifice (Daedric Sacrifice)
[54612] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true }, -- CLDA - Sacrifice (Daedric Sacrifice)
[52907] = { block = true, dodge = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Dark Flare (Shadow Knight)
[52912] = { interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Purifying Light (Shadow Knight)
[52927] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = U.Boss_Shadow_Knight, bossMatch = U.Boss_Hiath_the_Battlemaster }, -- Solar Disturbance (Shadow Knight)
[54792] = { block = true, dodge = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Crystal Blast (Dark Mage)
[54819] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossMatch = U.Boss_Dark_Mage }, -- Daedric Minefield (Dark Mage)
[54829] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = U.Boss_Dark_Mage, bossMatch = U.Boss_Hiath_the_Battlemaster }, -- Suppression Field (Dark Mage)
[54809] = { interrupt = true, priority = 1, auradetect = true }, -- Dark Deal (Dark Mage)
-- Stage 8 - Steamworks
[25211] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Whirlwind Function (Dwarven Fire Centurion)
[54841] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Ice Charge (Dwarven Ice Centurion)
[56065] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, noSelf = true }, -- Ice Charge (Dwarven Ice Centurion)
[72180] = { avoid = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_Dwarven_Sphere }, -- Electric Wave (Dwarven Sphere)
[52773] = { block = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED }, -- Ice Comet (Mavus Talnarith)
[52765] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, fakeName = U.Boss_Mavus_Talnarith }, -- Volcanic Rune (Mavus Talnarith)
-- Stage 9 - Crypts of the Lost
[56985] = { power = true, priority = 1, auradetect = true }, -- Spirit Shield (Zakael/Rubyn Jonnicent)
[55089] = { avoid = true, priority = 1, auradetect = true}, -- Poison Mist (Vampire Lord Thisa)
[55090] = { avoid = true, priority = 1, auradetect = true}, -- Devouring Swarm (Vampire Lord Thisa)
[55081] = { interrupt = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, noSelf = true, fakeName = U.Boss_Vampire_Lord_Thisa }, -- Vampire Lord Thisa
[55479] = { block = true, interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Malefic Wreath (Hiath the Battlemaster)
[55496] = { power = true, priority = 1, auradetect = true }, -- Power Extraction (Hiath the Battlemaster)
[55174] = { unmit = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED }, -- Marked for Death (Hiath the Battlemaster)
-- Maelstrom Arena
-- Stage 1 - Vale of the Surreal
[70892] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Bone Cage (Maxus the Many)
[72148] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Bone Cage (Maxus the Many)
[67765] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Maxus the Many)
[67656] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Maxus the Many)
[69515] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Maxus the Many)
[67691] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Reunite (Maxus the Many)
-- Stage 2 - Seht's Balcony
--[71047] = { block = true, avoid = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Thunderbolt (Clockwork Sentry)
[72067] = { power = true, priority = 2, auradetect = true }, -- Energizing (Clockwork Sentry)
[69364] = { avoid = true, priority = 1, auradetect = true }, -- Barrage Function (Centurion Champion)
[66904] = { power = true, priority = 1, auradetect = true }, -- Full Defense (Centurion Champion)
-- Stage 3 - The Drome of Toxic Shock
[67635] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Shock Water (Lamia Queen)
[73879] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED }, -- Lightning X (Lamia Queen)
[67757] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Queen's Poison (Lamia Queen)
[68357] = { power = true, priority = 1, auradetect = true }, -- Queen's Radiance (Lamia Queen)
[73876] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1000 }, -- Piercing Shriek (Lamia Queen)
-- Stage 4 - Seht's Flywheel
[71045] = { power = true, priority = 1, auradetect = true }, -- Turret Mode (Clockwork Sentry)
[71050] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Static Shield (Clockwork Sentry)
[73850] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Static Shield (Clockwork Sentry)
[69268] = { power = true, priority = 1, auradetect = true }, -- Enrage (Achelir)
[72157] = { power = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = U.NPC_Dwarven_Spider }, -- Static Field (Dwarven Spider)
[72166] = { block = true, avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, refire = 250 }, -- Overcharge (Dwarven Spider)
[72174] = { block = true, avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, refire = 250 }, -- Overcharge (Dwarven Spider)
[68524] = { power = true, priority = 1, auradetect = true }, -- Overcharged (The Control Guardian)
[68539] = { power = true, priority = 1, auradetect = true }, -- Overheated (The Control Guardian)
[68558] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, refire = 20000 }, -- Overheated Volley (The Control Guardian)
[72195] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Thunder Hammer (Scavenger Thunder-Smith)
[72198] = { block = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Wrecking Blow (Scavenger Thunder-Smith)
[72202] = { avoid = true, priority = 2, eventdetect = true, result = ACTION_RESULT_BEGIN, fakeName = U.NPC_Scavenger_Thunder_Smith }, -- Overcharge (Scavenger Thunder-Smith)
-- Stage 5 - Rink of Frozen Blood
[70898] = { summon = true, priority = 2, auradetect = true, fakeName = "" }, -- Call Ally (Huntsman Chillbane)
[71939] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Frost Breath (Huntsman Chillbane)
[71937] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Frost Nova (Huntsman Chillbane)
[72446] = { interrupt = true, priority = 1, auradetect = true }, -- Smash Iceberg (Troll Breaker)
[71926] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Frenzy of Blows (Angirgoth)
[72438] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Shatter (Giant)
[68439] = { power = true, priority = 1, auradetect = true }, -- Enrage (Aki/Vigi)
[74130] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Intimidating Roar (Aki/Vigi)
[66378] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Sweep (Matriarch Runa)
[72749] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Freezing Stomp (Matriarch Runa)
[67088] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Intimidating Roar (Matriarch Runa)
[66325] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Shatter (Matriarch Runa)
[72409] = { avoid = true, priority = 1, auradetect = true }, -- Taunt (Matriarch Runa)
--------------------------------------------------
-- DUNGEONS --------------------------------------
--------------------------------------------------
-- Banished Cells I
[19028] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, refire = 1500 }, -- Drain Essence (Cell Haunter)
[47587] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Tail Smite (Shadowrend)
[21886] = { summon = true, priority = 1, auradetect = true }, -- Summon Dark Proxy (Shadowrend)
[18772] = { interrupt = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Feeding (Shadowrend)
[18708] = { summon = true, priority = 1, auradetect = true }, -- Summon Clannfear (Angata the Clannfear Handler)
[19025] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Dead Zone (Skeletal Destroyer)
[33189] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Crushing Blow (High Kinlord Rilis)
[18840] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Soul Blast (High Kinlord Rilis)
[18875] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Daedric Tempest (High Kinlord Rilis)
-- Banished Cells II
[49150] = { block = true, avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1500, bossName = true }, -- Cone of Rot (Maw of the Infernal)
[27826] = { block = true, bs = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Crushing Blow (Keeper Voranil)
[29018] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, refire = 750, eventdetect = true, bossName = true }, -- Berserker Frenzy (Keeper Voranil)
[28750] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Essence Siphon (Keeper Voranil)
[29143] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Daedric Blast (Keeper Imiril)
[28962] = { power = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Sister's Love (Sister Sihna / Sister Vera)
[48799] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1500, bossName = true }, -- Daedric Tempest (High Kinlord Rilis)
[48814] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1500, bossName = true }, -- Daedric Tempest (High Kinlord Rilis)
[28570] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Levitate (High Kinlord Rilis)
[28462] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Levitate (High Kinlord Rilis)
-- Elden Hollow I
[16834] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Executioner's Strike (Akash gra-Mal)
[15999] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Leaping Strike (Akash gra-Mal)
[16016] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Berserker Frenzy (Akash gra-Mal)
[9910] = { destroy = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Summon Saplings (Chokethorn)
[9930] = { interrupt = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 1000, fakeName = U.NPC_Strangler_Saplings }, -- Heal Spores (Chokethorn)
[9875] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Fungal Burst (Chokethorn)
[44223] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.Boss_Leafseether }, -- Inhale (Leafseether)
[9845] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Rotting Bolt (Canonreeve Oraneth)
[16262] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Necrotic Circle (Canonreeve Oraneth)
[9944] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Necrotic Burst (Canonreeve Oraneth)
[9839] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Bone Hurricane (Canonreeve Oraneth)
-- Elden Hollow II
[34376] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, refire = 1500 }, -- Flame Geyser (Dubroze the Infestor)
[32707] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Summon Guardians (Dark Root)
[33334] = { interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_Frenzied_Guardian }, -- Latch On Stamina (Frenzied Guardian)
[33337] = { interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_Mystic_Guardian }, -- Latch On Magicka (Mystic Guardian)
[32890] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Gleaming Light (Dark Root)
[33533] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Glaring Light (Dark Root)
[33535] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Brightening Light (Dark Root)
[33170] = { destroy = true, priority = 1, auradetect = true }, -- Hate (Shadow Tendril)
[33052] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Shadow Stomp (Murklight)
[32832] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1750, bossName = true }, -- Consuming Shadow (Murklight)
[32975] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Eclipse (Murklight)
[33102] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 1250, bossName = true }, -- Spout Shadow (The Shadow Guard)
[33432] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Daedric Flame (Bogdan the Nightflame)
[33480] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Pulverize (Bogdan the Nightflame)
[33492] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Pulverize (Bogdan the Nightflame)
[33494] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Pulverize (Bogdan the Nightflame)
[34260] = { destroy = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = U.Boss_Nova_Tendril, refire = 1000 }, -- Shadow (Nova Tendril)
-- City of Ash I
[31101] = { block = true, avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Cleave (Golor the Banekin Handler)
[25034] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Crushing Blow (Golor the Banekin Handler)
[33604] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Summon Banekin (Golor the Banekin Handler)
[34607] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Measured Uppercut (Warden of the Shrine)
[34654] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true, bossName = true }, -- Fan of Flames (Warden of the Shrine)
[34620] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true, bossName = true }, -- Fan of Flames (Warden of the Shrine)
[34190] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Thorny Backhand (Infernal Guardian)
[34189] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Ground Slam (Infernal Guardian)
[35061] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Consuming Fire (Infernal Guardian)
[34183] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Tunneling Roots (Infernal Guardian)
[44278] = { block = true, avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED }, -- Lava Geyser (Dark Ember)
[34198] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true}, -- Burning Field (Rothariel Flameheart)
[34205] = { power = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true }, -- Deception (Rothariel Flameheart)
[34901] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Blazing Arrow (Razor Master Erthas)
[34805] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Release Flame (Razor Master Erthas)
[34623] = { summon = true, priority = 1, auradetect = true, bossName = true }, -- Summon Flame Atronach (Razor Master Erthas)
[34780] = { summon = true, priority = 1, auradetect = true, bossName = true }, -- Summon Flame Atranach (Razor Master Erthas)
-- City of Ash II
[53999] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, fakeName = A.Skill_Oblivion_Gate }, -- Summon (Flame Atronach)
[54021] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Release Flame (Marruz)
[53976] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Blazing Arrow (Marruz)
[54025] = { interrupt = true, priority = 1, auradetect = true, fakeName = U.Boss_Akezel }, -- Spell Absorption (Akezel)
[53994] = { interrupt = true, priority = 1, eventdetect = true, fakeName = U.Boss_Akezel, result = ACTION_RESULT_BEGIN }, -- Focused Healing (Akezel)
[54096] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.Boss_Rukhan }, -- Pyrocasm (Rukhan)
[56811] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_Xivilai_Ravager }, -- Pyrocasm (Xivilai Ravager)
[56414] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Fire Runes (Urata the Legion)
[54225] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Urata the Legion)
[56098] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Urata the Legion)
[56104] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Multiply (Urata the Legion)
[56131] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Reunite (Urata the Legion)
[56186] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, fakeName = U.NPC_Flame_Colossus }, -- Voice to Wake the Dead (Bone Colossus)
[55203] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Seismic Tremor (Horvantud the Fire Maw)
[56002] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Seismic Tremor (Horvantud the Fire Maw)
[55312] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Slag Breath (Horvantud the Fire Maw)
[55333] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Fiery Breath (Horvantud the Fire Maw)
[55320] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Fiery Breath (Horvantud the Fire Maw)
[55335] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Fiery Breath (Horvantud the Fire Maw)
[55326] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Fiery Breath (Horvantud the Fire Maw)
[55337] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Fiery Breath (Horvantud the Fire Maw)
[57618] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Damage Shield (Horvantud the Fire Maw)
[55315] = { power = true, priority = 1, auradetect = true }, -- Slag Breath (Horvantud the Fire Maw)
[55324] = { power = true, priority = 1, auradetect = true }, -- Enrage 2 (Horvantud the Fire Maw)
[55329] = { power = true, priority = 1, auradetect = true }, -- Enrage 3 (Horvantud the Fire Maw)
[54218] = { block = true, dodge = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Monstrous Cleave (Ash Titan)
[54895] = { block = true, avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Molten Rain (Ash Titan)
[54699] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossName = true }, -- Fire Swarm (Ash Titan)
[58468] = { power = true, auradetect = true, priority = 1 }, -- Shadow Cloak (Ash Titan)
[54783] = { power = true, auradetect = true, priority = 1 }, -- Air Atronach Flame (Air Atronach)
[54366] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, refire = 1500, fakeName = U.NPC_Air_Atronach }, -- Flame Tornado (Air Atronach)
[58280] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossName = true }, -- Scary Summon 1 (Xivilai Fulminator / Boltaic)
[56601] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossName = true }, -- Scary Summon 2 (Xivilai Fulminator / Boltaic)
[55513] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Flame Bolt (Valkyn Skoria)
[55387] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Meteor Strike (Valkyn Skoria)
[55514] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Call the Flames (Valkyn Skoria)
[55426] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Magma Prison (Valkyn Skoria)
[55024] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Lava Quake (Valkyn Skoria)
[55500] = { power = true, priority = 1, auradetect = true, ignoreRefresh = true }, -- Rock Shield (Valkyn Skoria)
-- Tempest Island
[46732] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 1000 }, -- Sonic Scream (Sonolia the Matriarch)
[26370] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Slash (Valaran Stormcaller)
[26628] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Enervating Bolt (Valaran Stormcaller)
[26592] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, bossName = true }, -- Lightning Avatar (Valaran Stormcaller)
[6106] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Lightning Storm (Yalorasse the Speaker)
[26748] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 1000 }, -- Enervating Stone (Stormfist)
[26714] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Skyward Slam (Stormfist)
[26833] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Summon Storm Atronach (Stormfist)
[26790] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 60000 }, -- Unstable Explosion (Stormfist)
[27039] = { interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 600 }, -- Ethereal Chain (Commodore Ohmanil)
[27596] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Lightning Strike (Stormreeve Neider)
[26741] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Swift Wind (Stormreeve Neider)
[26712] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Gust of Wind (Stormreeve Neider)
-- Selene's Web
[30909] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, refire = 2000, bossName = true }, -- Ensnare (Treethane Kerninn)
[30907] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Summon Primal Swarm (Treethane Kerninn)
[30781] = { power = true, priority = 1, auradetect = true }, -- Mirror Ward (Longclaw)
[30772] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 1250 }, -- Arrow Rain (Longclaw)
[30779] = { summon = true, priority = 1, auradetect = true, refire = 500, fakeName = "" }, -- Spirit Form (Senche Spirit)
[31096] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Poison Burst (Longclaw)
[31202] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Venomous Burst (Queen Aklayah)
[31205] = { power = true, priority = 1, auradetect = true, noSelf = true }, -- Venomous Burst (Queen Aklayah)
[30996] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Vicious Maul (Foulhide)
[30812] = { avoid = true, block = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Trampling Charge (Foulhide)
[31002] = { summon = true, priority = 1, auradetect = true, fakeName = "", refire = 5000 }, -- Intro (Selene's Rose)
[31241] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED, bossName = true }, -- Summon Spiders (Mennir Many-Legs)
[31052] = { power = true, priority = 1, auradetect = true, noSelf = true }, -- Web Wrap (Selene)
[30731] = { block = true, dodge = true, priority = 1, auradetect = true }, -- Summon Primal Spirit (Selene)
[30896] = { dodge = true, priority = 1, auradetect = true, bossName = true }, -- Summon Senche Spirit (Selene)
[31986] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Summon Melee (Selene)
[31984] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Summon Healer (Selene)
[31985] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_EFFECT_GAINED }, -- Summon Archer (Selene)
-- Spindleclutch I
[46147] = { summon = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Summon Swarm (Spindlekin)
[22034] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Inject Poison (Swarm Mother)
[17964] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Impeding Webs (Swarm Mother)
[17960] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Arachnid Leap (Swarm Mother)
[18559] = { summon = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, eventdetect = true, refire = 1000, bossName = true }, -- Spawn Broodling (Swarm Mother)
[18111] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Arachnophobia (Swarm Mother)
[18078] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Web Blast (Swarm Mother)
[35572] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Grappling Web (Swarm Mother)
[18058] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Daedric Explosion (Swarm Mother)
-- Spindleclutch II
[28093] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Vicious Smash (Blood Spawn)
[27995] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Cave-In (Blood Spawn)
[47331] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 60000 }, -- Cave-In (Blood Spawn)
[47198] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, auradetect = true, refire = 5000, fakeName = "" }, -- Falling Rocks (Cave In)
[28438] = { summon = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Dummy (Praxin Douare)
[18036] = { block = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, fakeName = U.NPC_The_Whisperer_Nightmare, refire = 2500 }, -- Grappling Web (The Whisperer Nightmare)
[27965] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Despair (Praxin Douare)
[27741] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Despair (Praxin Douare)
[27703] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Harrowing Ring (Praxin Douare)
[61443] = { power = true, priority = 1, auradetect = true, noSelf = true }, -- Harrowing Ring (Praxin Douare)
[27435] = { power = true, priority = 1, auradetect = true }, -- Monstrous Growth (Flesh Atronach)
[27437] = { power = true, priority = 1, auradetect = true }, -- Monstrous Growth (Flesh Atronach)
[27600] = { avoid = true, priority = 1, result = ACTION_RESULT_EFFECT_GAINED, auradetect = true }, -- Blood Pool (Urvan Veleth)
[27905] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Blood Pool (Vorenor Winterbourne)
[27897] = { unmit = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Open Wounds (Vorenor Winterbourne)
[27791] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Blood Frenzy (Vorenor Winterbourne)
[31672] = { power = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true, refire = 2500 }, -- Thrall Feast (Vorenor Winterbourne)
-- Wayrest Sewers I
[34846] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Primal Sweep (Slimecraw)
[9441] = { block = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Dark Lance (Investigator Garron)
[25593] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true, bossName = true }, -- Summon Necrotic Orb (Investigator Garron)
[9740] = { summon = true, priority = 1, auradetect = true, bossName = true }, -- Tormented Summoning (Restless Soul)
[25548] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Smite (Varaine Pellingare)
[9648] = { block = true, dodge = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Spinning Cleave (Varaine Pellingare)
[36435] = { avoid = true, priority = 1, eventdetect = true, result = ACTION_RESULT_BEGIN, bossName = true }, -- Tidal Slash (Varaine Pellingare)
[9656] = { dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Poisoned Blade (Varaine Pellingare)
[11752] = { block = true, bs = true, dodge = true, priority = 1, result = ACTION_RESULT_BEGIN }, -- Penetrating Daggers (Allene Pellingare)
[35006] = { power = true, priority = 1, auradetect = true }, -- Hallucinogenic Fumes (Allene Pellingare)
[35021] = { power = true, priority = 1, auradetect = true }, -- Mind-Bending Mist (Allene Pellingare)
[35041] = { power = true, priority = 1, auradetect = true }, -- Mind-Bending Mist (Allene Pellingare)
-- Frostvault
[109574] = { block = true, interrupt = true, priority = 3, result = ACTION_RESULT_BEGIN, refire = 3250 }, -- Fire Power (Coldsnap Harrier)
[117352] = { block = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Whirlwind (Coldsnap Snowstalker)
[117290] = { block = true, avoid = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Shockwave (Coldsnap Ogre)
[117287] = { block = true, bs = true, dodge = true, priority = 2, result = ACTION_RESULT_BEGIN }, -- Crushing Blow (Coldsnap Ogre)
[117326] = { block = true, priority = 3, result = ACTION_RESULT_EFFECT_GAINED, refire = 250 }, -- Ice Comet (Coldsnap Skysplitter)
[109827] = { block = true, avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Boulder Toss (Icestalker)
[109811] = { avoid = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Ground Slam (Icestalker)
[109837] = { interrupt = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Frenzied Pummeling (Icestalker)
[109806] = { block = true, priority = 1, result = ACTION_RESULT_BEGIN, eventdetect = true }, -- Frozen Aura (Icestalker)
[83430] = { block = true, bs = true, dodge = true, priority = 3, result = ACTION_RESULT_BEGIN }, -- Skeletal Smash (Ice Wraith)
}
|
local util = require("spec.util")
describe("binary metamethod __add", function()
it("can be set on a record", util.check [[
local type Rec = record
x: number
metamethod __call: function(Rec, string, number): string
metamethod __add: function(Rec, Rec): Rec
end
local rec_mt: metatable<Rec>
rec_mt = {
__call = function(self: Rec, s: string, n: number): string
return tostring(self.x + n) .. s
end,
__add = function(a: Rec, b: Rec): Rec
local res = setmetatable({} as Rec, rec_mt)
res.x = a.x + b.x
return res
end
}
local r = setmetatable({ x = 10 } as Rec, rec_mt)
local s = setmetatable({ x = 20 } as Rec, rec_mt)
print((r + s).x)
print(r("!!!", 34))
]])
it("can be used via the second argument", util.check [[
local type Rec = record
x: number
metamethod __add: function(number, Rec): Rec
end
local rec_mt: metatable<Rec>
rec_mt = {
__add = function(a: number, b: Rec): Rec
local res = setmetatable({} as Rec, rec_mt)
res.x = a + b.x
return res
end
}
local s = setmetatable({ y = 20 } as Rec, rec_mt)
print((10 + s).x)
]])
end)
|
local cjson = require("cjson")
local _M = {}
_M.mysql = {}
function _M.mysql.replace_meta_value(store,key,value)
return store:update({
sql = "replace into meta SET `key`=?, `value`=?",
params = { key, value }
})
end
function _M.mysql.select_meta_value(store,key)
return store:query({
sql = "select `value` from meta where `key`=?",
params = { key }
})
end
function _M.mysql.select_monitor_rules(store)
return store:query({
sql = "select `value` from monitor order by id asc"
})
end
function _M.mysql.insert_monitor_rules(store,key,value)
return store:insert({
sql = "insert into monitor(`key`, `value`) values(?,?)",
params = { key, cjson.encode(value) }
})
end
function _M.mysql.delete_monitor_rules(store,key)
return store:delete({
sql = "delete from monitor where `key`=?",
params ={key}
})
end
function _M.mysql.update_monitor_rules(store,key,value)
return store:query({
sql = "update monitor set `value`=? where `key`=?",
params ={cjson.encode(value), rule.id}
})
end
_M.pgsql = {}
function _M.pgsql.replace_meta_value(store,key,value)
return store:update({
sql = "select replace_meta_value(?,?);",
params = { key, value }
})
end
function _M.pgsql.select_meta_value(store,key)
return store:query({
sql = "select value from meta where key=?",
params = { key }
})
end
function _M.pgsql.select_monitor_rules(store)
return store:query({
sql = "select value from monitor order by id asc"
})
end
function _M.pgsql.insert_monitor_rules(store,key,value)
return store:insert({
sql = "insert into monitor(key, value) values(?,?)",
params = { key, value }
})
end
function _M.pgsql.delete_monitor_rules(store,key)
return store:delete({
sql = "delete from monitor where key=?",
params ={key}
})
end
function _M.pgsql.update_monitor_rules(store,key,value)
return store:query({
sql = "update monitor set value=? where key=?",
params ={value, key}
})
end
function _M.replace_meta_value(store,key,value)
return _M[store.store_type].replace_meta_value(store,key,value)
end
function _M.select_meta_value(store,key)
return _M[store.store_type].select_meta_value(store,key)
end
function _M.select_monitor_rules(store)
return _M[store.store_type].select_meta_value(store)
end
function _M.insert_monitor_rules(store,key,value)
return _M[store.store_type].insert_monitor_rules(store,key,value)
end
function _M.delete_monitor_rules(store,key)
return _M[store.store_type].delete_monitor_rules(store,key)
end
function _M.update_monitor_rules(store,key,value)
return _M[store.store_type].update_monitor_rules(store,key,value)
end
return _M
|
-- This gets all the data associated with the job with the
-- provided id.
--
-- Args:
-- 1) jid
if #KEYS > 0 then error('Get(): No Keys should be provided') end
local jid = assert(ARGV[1], 'Get(): Arg "jid" missing')
-- Let's get all the data we can
local job = redis.call(
'hmget', 'ql:j:' .. jid, 'jid', 'klass', 'state', 'queue', 'worker', 'priority',
'expires', 'retries', 'remaining', 'data', 'tags', 'history', 'failure')
if not job[1] then
return false
end
return cjson.encode({
jid = job[1],
klass = job[2],
state = job[3],
queue = job[4],
worker = job[5] or '',
tracked = redis.call('zscore', 'ql:tracked', jid) ~= false,
priority = tonumber(job[6]),
expires = tonumber(job[7]) or 0,
retries = tonumber(job[8]),
remaining = tonumber(job[9]),
data = cjson.decode(job[10]),
tags = cjson.decode(job[11]),
history = cjson.decode(job[12]),
failure = cjson.decode(job[13] or '{}'),
dependents = redis.call('smembers', 'ql:j:' .. jid .. '-dependents'),
dependencies = redis.call('smembers', 'ql:j:' .. jid .. '-dependencies')
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.