content stringlengths 5 1.05M |
|---|
local config = require('config')
local Vector2D = require('utils/vector2d')
local tlm = {}
local quad = love.graphics.newQuad
-- TODO: take config from tilemap
local y = 6
local x = 8
local tileWidth = config.tileWidth
local tileHeight = config.tileHeight
local tilesheetWidth = config.tilesheetWidth
local tilesheetHeight = config.tilesheetHeight
local quads = {}
for i = 0, y - 1 do
for j = 0, x - 1 do
table.insert(quads, quad((tileWidth * j), (tileWidth * i), tileWidth, tileHeight, tilesheetWidth, tilesheetHeight))
end
end
function tile(x, y, w, h, quad)
local tile = {}
tile.pos = Vector2D:new(x, y)
tile.size = Vector2D:new(w, h)
tile.quad = quad
return tile
end
function tlm:load()
self.tiles = {}
self.img = asm:get("lvl1_tiles")
self.img:setFilter("nearest", "nearest")
renderer:addRenderer(self)
end
function tlm:loadMap(mapName)
local map = require('assets/maps/'..mapName)
for i = 1, map.height do self.tiles[i] = {} end
for layer = 1, #map.layers do
local data = map.layers[layer].data
local propt = map.layers[layer].prop
for y = 1, map.height do
for x = 1, map.width do
-- take index from the tiles array
local index = (y * map.height + (x + 1) - map.width) + 1
-- if data is not zero then we have a tile to draw
if data[index] ~= 0 then
local q = quads[data[index]]
-- TODO: 16 -> config.tileSize
-- self.tiles[y][x] = tile((16 * x) - 16, (16 * y) - 16, 16, 16, q)
-- print('x', x)
self.tiles[y][x] = tile((tileWidth * x) - tileWidth, (tileHeight * y) - tileHeight, tileWidth, tileHeight, q)
end
end
end
end
end
function tlm:draw()
for i = 1, #self.tiles do
-- for j = 1, #self.tiles[i] do
for j = 1, #self.tiles do
if self.tiles[i][j] ~= nil then
local tile = self.tiles[i][j]
if tile.quad ~= nil then
love.graphics.draw(self.img, tile.quad, tile.pos.x, tile.pos.y)
end
end
end
end
end
function tlm:destroy()
end
return tlm
|
local jid_bare = require "util.jid".bare;
local xmlns_pubsub = "http://jabber.org/protocol/pubsub";
local xmlns_pubsub_event = "http://jabber.org/protocol/pubsub#event";
local xmlns_pubsub_errors = "http://jabber.org/protocol/pubsub#errors";
local pubsub = {};
local pubsub_mt = { __index = pubsub };
function verse.plugins.pubsub(stream)
stream.pubsub = setmetatable({ stream = stream }, pubsub_mt);
stream:hook("message", function (message)
for pubsub_event in message:childtags("event", xmlns_pubsub_event) do
local items = pubsub_event:get_child("items");
if items then
local node = items.attr.node;
for item in items:childtags("item") do
stream:event("pubsub/event", {
from = message.attr.from;
node = node;
item = item;
});
end
end
end
end);
return true;
end
function pubsub:subscribe(server, node, jid, callback)
self.stream:send_iq(verse.iq({ to = server, type = "set" })
:tag("pubsub", { xmlns = xmlns_pubsub })
:tag("subscribe", { node = node, jid = jid or jid_bare(self.stream.jid) })
, function (result)
if callback then
if result.attr.type == "result" then
callback(true);
else
callback(false, result:get_error());
end
end
end
);
end
function pubsub:publish(server, node, id, item, callback)
self.stream:send_iq(verse.iq({ to = server, type = "set" })
:tag("pubsub", { xmlns = xmlns_pubsub })
:tag("publish", { node = node })
:tag("item", { id = id })
:add_child(item)
, function (result)
if callback then
if result.attr.type == "result" then
callback(true);
else
callback(false, result:get_error());
end
end
end
);
end
|
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- Integrator options -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- Algorithmic paramters (for rho_infinity = 0.9)
alpha_m = 8/ 19
alpha_f = 9/ 19
beta = 100/361
gamma = 21/ 38
-- Use constant mass matrix
const_mass_matrix = 1
-- Use diagonal mass matrix
diag_mass_matrix = 1
-- Use banded solvers for the iteration matrix
banded_iteration_matrix = 1
-- Recalculate the iteration matrix in ever Newton step
recalc_iteration_matrix = 0
-- Perturb initial values (only applies to the constrained case with direct integration of the index-3 formulation)
perturb = 0
perturb_s = 1.0
-- Use numerical approximation for stiffness matrix K
use_num_K = 1
-- Use numerical approximation for damping matrix D
use_num_D = 1
-- Omit stiffness matrix K in the iteration matrix
no_K = 0
-- Omit damping matrix D in the iteration matrix
no_D = 0
-- Relative error bound for the Newton-Raphson method
rtol = 1.0e-6
-- Absolute error bound for the Newton-Raphson method
atol = 1.0e-8
-- Maximum unsuccessful iteration steps after which the method is considered not to converge
imax = 100
-- Integration interval and step size
t0 = 0
te = 1
steps = 2^12
-- Use stabilized index-2 formulation (only applies to the constrained case)
stab2 = 0
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- Problem options -- -- -- -- -- -- -- -- -- -- -- --
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
problem_name = 'pendulum'
-- Kirchhoff model
kirchhoff = 0
-- inextensible model
inextensible = 0
-- Simplified model assumptions
use_SMA = 0
-- Calculate number of subdiagonals and superdiagonals of the iteration matrix
additional_subdiag = 0
if kirchhoff then
additional_subdiag = 2
end
if inextensible then
additional_subdiag = additional_subdiag + 1
end
if stab2 then
additional_subdiag = 2*additional_subdiag
end
-- In the unconstrained case there are 9 subdiagonals
nr_subdiag = 9 + additional_subdiag
-- The number of sub- and superdiagonals is equal
nr_superdiag = nr_subdiag
-- Number of discretization points of the position
N = 2^4
-- Length
L = 1
-- Density
rho = 1.1e3
-- Elastic modulus
E = 5.0e6
-- Poisson number
nu = 0.5
-- Shear modulus
G = E/(2*(1+nu))
-- Radius
r = 5.0e-3
-- Area
A = math.pi* r^2
-- Inertia terms
iner = { r^4 * math.pi/4,
r^4 * math.pi/4,
r^4 * math.pi/2 }
-- Dissipative material constants
CGamd = { 1.0e-1,
1.0e-1,
2.0e2 }
CKd = { 2.0e-4,
2.0e-4,
8.0e-6 }
-- Timoshenko shear correction factors
kappa = { 6*(1+nu)/(7+6*nu),
6*(1+nu)/(7+6*nu) }
-- Material properties
CGam = { A*G*kappa[1],
A*G*kappa[2],
A*E }
CK = { E*iner[1],
E*iner[2],
G*iner[3] }
-- Difference between two discretization points
ds = L/(N-1)
-- Mass of beam segment
m = rho * A * ds
-- Inertial mass of a beam segment
mI = { rho*iner[1]*ds,
rho*iner[2]*ds,
rho*iner[3]*ds }
-- -- -- Initial values -- -- --
-- Note that 0 <= s <= 1, independent of the beam length
-- Initial positions
function x0(s)
return { s*L, 0, 0 }
end
-- Initial velocities
function xd0(s)
return { 0, 0, 0 }
end
-- Initial rotations
function p0(s)
return { math.sqrt(0.5), 0, math.sqrt(0.5), 0 }
end
-- Initial angular velocities
function Om0(s)
return { 0, 0, 0 }
end
-- External forces and moments
external = 'gravity'
external_parameters = { g = -9.81 }
-- Fixing
fixed_x1 = 1
fixed_x1_position = { 0, 0, 0 }
fixed_xN = 0
fixed_xN_position = nil
-- -- -- Output options -- -- --
output_t_at = 1
t_output_at_multiples_of = 1/2^7
output_xp_at = 0
s_output_x = { 0.0, 0.25, 0.5, 0.75, 1.0 }
s_output_p = { 0.125, 0.375, 0.625, 0.875 }
|
ROOKI = ROOKI or {}
local ply = FindMetaTable("Player")
function ply:getJob()
if (self.getJobTable and isfunction(self.getJobTable)) then return self:getJobTable() or {} end
return false
end
function ply:getJobName()
if (self.getJobTable and isfunction(self.getJobTable)) then return self:getJobTable().name or "" end
return false
end
function ply:getCategory()
if (self.getJobTable and isfunction(self.getJobTable)) then return self:getJobTable().name or "" end
return false
end |
-- Lua stuff
function onCreate()
-- triggered when the lua file is started
-- create a lua sprite called "sexualintercourse"
end
-- Gameplay interactions
function onBeatHit()
-- triggered 4 times per section
if curBeat == 196 or curBeat == 312 then
makeAnimatedLuaSprite('sexualintercourse', 'characters/uh', 0, 578);
addAnimationByPrefix('sexualintercourse', 'first', 'idle', 24, false);
objectPlayAnimation('sexualintercourse', 'first');
addLuaSprite('sexualintercourse', false);-- false = add behind characters, true = add over characters
end
if curBeat % 2 == 0 then
objectPlayAnimation('sexualintercourse', 'first');
end
if curBeat == 216 then
removeLuaSprite('sexualintercourse');
end
end
function onStepHit()
-- triggered 16 times per section
setProperty('sexualintercourse.scale.x', getProperty('sexualintercourse.scale.x') + 0.01);
end
function onCountdownTick(counter)
-- counter = 0 -> "Three"
-- counter = 1 -> "Two"
-- counter = 2 -> "One"
-- counter = 3 -> "Go!"
-- counter = 4 -> Nothing happens lol, tho it is triggered at the same time as onSongStart i think
if counter % 2 == 0 then
objectPlayAnimation('sexualintercourse', 'first');
end
end
function opponentNoteHit()
health = getProperty('health')
if getProperty('health') > 0.05 and curBeat > 195 and curBeat < 216 then
setProperty('health', health- 0.005);
end
end |
local MODNAME = minetest.get_current_modname()
local api = rawget(_G, MODNAME)
function api.also_register_loaded_tool(name, def, user_loaded_def)
local loaded_def = table.copy(def)
if user_loaded_def then
user_loaded_def(loaded_def)
end
loaded_def.unloaded_name = name
def.loaded_name = name.."_loaded"
minetest.register_tool(def.loaded_name, loaded_def)
return name, def
end
function api.unload_weapon(weapon, amount)
local iname = weapon:get_name()
local rounds = assert(
minetest.registered_tools[iname].rounds,
"Must define 'rounds' property for ranged weapon "..dump(iname)
)
local new_wear = (65535 / (rounds-1)) * (amount or 1)
new_wear = weapon:get_wear() + new_wear
if new_wear >= 65535 then
return ItemStack(weapon:get_definition().unloaded_name)
end
weapon:set_wear(new_wear)
return weapon
end
function api.load_weapon(weapon, inv, lists)
local idef = weapon:get_definition()
assert(idef.loaded_name, "Item "..idef.name.." doesn't have 'loaded_name' set!")
assert(idef.ammo, "Item "..idef.name.." doesn't have 'ammo' set!")
if type(idef.ammo) ~= "table" then
idef.ammo = {idef.ammo}
end
if not lists then
lists = {"main"}
elseif type(lists) ~= "table" then
lists = {lists}
end
for _, item in pairs(idef.ammo) do
for _, list in pairs(lists) do
if inv:contains_item(list, item) then
inv:remove_item(list, item)
return ItemStack(idef.loaded_name)
end
end
end
return weapon
end
|
local config = require('orgmode.config')
local highlights = require('orgmode.colors.highlights')
---@class TodoState
---@field current_state string
---@field hl_map table
---@field todos table
local TodoState = {}
---@param data table
function TodoState:new(data)
local opts = {}
opts.current_state = data.current_state or ''
local todo_keywords = config:get_todo_keywords()
opts.todos = {
TODO = vim.tbl_add_reverse_lookup({ unpack(todo_keywords.TODO) }),
DONE = vim.tbl_add_reverse_lookup({ unpack(todo_keywords.DONE) }),
ALL = vim.tbl_add_reverse_lookup({ unpack(todo_keywords.ALL) }),
FAST_ACCESS = todo_keywords.FAST_ACCESS,
has_fast_access = todo_keywords.has_fast_access,
}
opts.hl_map = highlights.get_agenda_hl_map()
setmetatable(opts, self)
self.__index = self
return opts
end
---@return boolean
function TodoState:has_fast_access()
return self.todos.has_fast_access
end
function TodoState:open_fast_access()
local output = {}
for _, todo in ipairs(self.todos.FAST_ACCESS) do
table.insert(output, { string.format('[%s] ', todo.shortcut) })
table.insert(output, { todo.value, self.hl_map[todo.value] or self.hl_map[todo.type] })
table.insert(output, { ' ' })
end
table.insert(output, { '\n' })
vim.api.nvim_echo(output, true, {})
local char = vim.fn.nr2char(vim.fn.getchar())
vim.cmd([[redraw!]])
if char == ' ' then
self.current_state = ''
return { value = '', type = '' }
end
for _, todo in ipairs(self.todos.FAST_ACCESS) do
if char == todo.shortcut then
self.current_state = todo.value
return { value = todo.value, type = todo.type, hl = self.hl_map[todo.value] or self.hl_map[todo.type] }
end
end
end
---@return table
function TodoState:get_next()
if self.current_state == '' then
self.current_state = self.todos.ALL[1]
local val = self.todos.ALL[1]
return { value = val, type = 'TODO', hl = self.hl_map[val] or self.hl_map.TODO }
end
local current_item_index = self.todos.ALL[self.current_state]
local next_state = self.todos.ALL[current_item_index + 1]
if not next_state then
self.current_state = ''
return { value = '', type = '' }
end
self.current_state = next_state
local type = self.todos.TODO[next_state] and 'TODO' or 'DONE'
return { value = next_state, type = type, hl = self.hl_map[next_state] or self.hl_map[type] }
end
---@return table
function TodoState:get_prev()
if self.current_state == '' then
local last_item = self.todos.ALL[#self.todos.ALL]
self.current_state = last_item
return { value = last_item, type = 'DONE', hl = self.hl_map[last_item] or self.hl_map.DONE }
end
local current_item_index = self.todos.ALL[self.current_state]
local prev_state = self.todos.ALL[current_item_index - 1]
if not prev_state then
self.current_state = ''
return { value = '', type = '' }
end
self.current_state = prev_state
local type = self.todos.TODO[prev_state] and 'TODO' or 'DONE'
return { value = prev_state, type = type, hl = self.hl_map[prev_state] or self.hl_map[type] }
end
function TodoState:get_todo()
local first = self.todos.TODO[1]
return { value = first, type = 'TODO', hl = self.hl_map[first] or self.hl_map.TODO }
end
return TodoState
|
--[[
/*
* V4L2 video capture example
*
* This program can be used and distributed without restrictions.
*
* This program is provided with the V4L2 API
* see http://linuxtv.org/docs.php for more information
*/
--]]
require ("videodev2")()
local int = ffi.typeof("int")
local function CLEAR(x)
libc.memset(x, 0, ffi.sizeof(x))
end
ffi.cdef[[
struct buffer {
void *start;
size_t length;
};
]]
static char *dev_name;
local io = io_method.IO_METHOD_MMAP;
static int fd = -1;
struct buffer *buffers;
static unsigned int n_buffers;
static int out_buf;
static int force_format;
static int frame_count = 70;
local function errno_exit(s)
libc.fprintf(io.stderr, "%s error %d, %s\n", s, errno, strerror(errno));
error(EXOT_FAILURE);
end
local function xioctl(int fh, int request, void *arg)
local r;
do {
r = libc.ioctl(fh, request, arg);
} while (-1 == r && EINTR == errno);
return r;
end
local function process_image(const void *p, int size)
if (out_buf ~= nil) then
fwrite(p, size, 1, stdout);
end
libc.fflush(io.stderr);
libc.fprintf(io.stderr, ".");
libc.fflush(io.stdout);
end
local function read_frame(fd)
struct v4l2_buffer buf;
unsigned int i;
switch (io) {
case IO_METHOD_READ:
if (-1 == read(fd, buffers[0].start, buffers[0].length)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("read");
}
}
process_image(buffers[0].start, buffers[0].length);
break;
case IO_METHOD_MMAP:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
assert(buf.index < n_buffers);
process_image(buffers[buf.index].start, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
case IO_METHOD_USERPTR:
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_USERPTR;
if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
switch (errno) {
case EAGAIN:
return 0;
case EIO:
/* Could ignore EIO, see spec. */
/* fall through */
default:
errno_exit("VIDIOC_DQBUF");
}
}
for (i = 0; i < n_buffers; ++i)
if (buf.m.userptr == (unsigned long)buffers[i].start
&& buf.length == buffers[i].length)
break;
assert(i < n_buffers);
process_image((void *)buf.m.userptr, buf.bytesused);
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
break;
}
return 1;
end
local function mainloop(fd)
local count = frame_count;
while (count > 0) do
while true do
fd_set fds;
struct timeval tv;
int r;
FD_ZERO(&fds);
FD_SET(fd, &fds);
/* Timeout. */
tv.tv_sec = 2;
tv.tv_usec = 0;
r = select(fd + 1, &fds, NULL, NULL, &tv);
if (-1 == r) then
if (EINTR == errno) then
continue;
end
errno_exit("select");
end
if (0 == r) then
fprintf(stderr, "select timeout\n");
exit(EXIT_FAILURE);
end
if (read_frame(fd)) then
break;
end
-- EAGAIN - continue select loop.
end
count = count - 1;
end
end
local function stop_capturing(fd)
local atype = ffi.new("int[1]", V4L2_BUF_TYPE_VIDEO_CAPTURE);
if (-1 == xioctl(fd, VIDIOC_STREAMOFF, atype)) then
errno_exit("VIDIOC_STREAMOFF");
end
end
local function start_capturing(fd)
unsigned int i;
enum v4l2_buf_type type;
for (i = 0; i < n_buffers; ++i) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
errno_exit("VIDIOC_QBUF");
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
errno_exit("VIDIOC_STREAMON");
end
local function uninit_device()
unsigned int i;
for i = 0, n_buffers-1 do
if (-1 == libc.munmap(buffers[i].start, buffers[i].length)) then
errno_exit("munmap");
end
end
libc.free(buffers);
end
local function init_mmap(fd)
struct v4l2_requestbuffers req;
CLEAR(req);
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
if (EINVAL == errno) {
fprintf(stderr, "%s does not support "
"memory mapping\n", dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_REQBUFS");
}
}
if (req.count < 2)
{
fprintf(stderr, "Insufficient buffer memory on %s\n",
dev_name);
exit(EXIT_FAILURE);
}
buffers = calloc(req.count, sizeof(*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory\n");
exit(EXIT_FAILURE);
}
for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
struct v4l2_buffer buf;
CLEAR(buf);
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
errno_exit("VIDIOC_QUERYBUF");
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start =
mmap(NULL /* start anywhere */,
buf.length,
PROT_READ | PROT_WRITE /* required */,
MAP_SHARED /* recommended */,
fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start)
errno_exit("mmap");
}
end
local function init_device(fd)
struct v4l2_capability cap;
struct v4l2_cropcap cropcap;
struct v4l2_crop crop;
struct v4l2_format fmt;
unsigned int min;
if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
if (EINVAL == errno) {
fprintf(stderr, "%s is no V4L2 device\n",
dev_name);
exit(EXIT_FAILURE);
} else {
errno_exit("VIDIOC_QUERYCAP");
}
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
fprintf(stderr, "%s is no video capture device\n",
dev_name);
exit(EXIT_FAILURE);
}
-- case IO_METHOD_MMAP:
if (!(cap.capabilities & V4L2_CAP_STREAMING)) then
fprintf(io.stderr, "%s does not support streaming i/o\n",
dev_name);
exit(EXIT_FAILURE);
end
-- Select video input, video standard and tune here.
CLEAR(cropcap);
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) then
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; -- reset to default
if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) then
switch (errno) {
case EINVAL:
-- Cropping not supported.
break;
default:
-- Errors ignored.
break;
}
end
else
-- Errors ignored.
end
CLEAR(fmt);
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (force_format) then
fmt.fmt.pix.width = 640;
fmt.fmt.pix.height = 480;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt)) then
errno_exit("VIDIOC_S_FMT");
end
-- Note VIDIOC_S_FMT may change width and height.
else
-- Preserve original settings as set by v4l2-ctl for example
if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt)) then
errno_exit("VIDIOC_G_FMT");
end
end
-- Buggy driver paranoia.
min = fmt.fmt.pix.width * 2;
if (fmt.fmt.pix.bytesperline < min) then
fmt.fmt.pix.bytesperline = min;
end
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if (fmt.fmt.pix.sizeimage < min) then
fmt.fmt.pix.sizeimage = min;
end
init_mmap(fd);
end
local function close_device(fd)
if (-1 == libc.close(fd)) then
errno_exit("close");
end
fd = -1;
end
local function open_device(dev_name)
local fd = -1;
local st = ffi.new("struct stat");
if (-1 == libc.stat(dev_name, st)) then
fprintf(io.stderr, "Cannot identify '%s': %d, %s\n",
dev_name, ffi.errno(), libc.strerror(ffi.errno()));
exit(EXIT_FAILURE);
end
if (!S_ISCHR(st.st_mode)) then
libc.fprintf(io.stderr, "%s is no device\n", dev_name);
error(EXIT_FAILURE);
end
fd = open(dev_name, bor(libc.O_RDWR, libc.O_NONBLOCK), int(0));
if (-1 == fd) then
libc.fprintf(stderr, "Cannot open '%s': %d, %s\n",
dev_name, errno, strerror(errno));
error(EXIT_FAILURE);
end
end
local function usage(FILE *fp, int argc, char **argv)
libc.fprintf(fp,
"Usage: %s [options]\n\n"
"Version 1.0\n"
"Options:\n"
"-d | --device name Video device name [%s]\n"
"-h | --help Print this message\n"
"-o | --output Outputs stream to stdout\n"
"-f | --format Force format to 640x480 YUYV\n"
"-c | --count Number of frames to grab [%i]\n"
"",
argv[0], dev_name, frame_count);
end
--[[
local short_options[] = "d:hmruofc:";
static const struct option
long_options[] = {
{ "device", required_argument, NULL, 'd' },
{ "help", no_argument, NULL, 'h' },
{ "mmap", no_argument, NULL, 'm' },
{ "read", no_argument, NULL, 'r' },
{ "userp", no_argument, NULL, 'u' },
{ "output", no_argument, NULL, 'o' },
{ "format", no_argument, NULL, 'f' },
{ "count", required_argument, NULL, 'c' },
{ 0, 0, 0, 0 }
};
--]]
local function main(argc, argv)
local dev_name = "/dev/video0";
for (;;) {
int idx;
int c;open_device
c = getopt_long(argc, argv,
short_options, long_options, &idx);
if (-1 == c)
break;
switch (c) {
case 0: /* getopt_long() flag */
break;
case 'd':
dev_name = optarg;
break;
case 'h':
usage(stdout, argc, argv);
exit(EXIT_SUCCESS);
case 'm':
io = IO_METHOD_MMAP;
break;
case 'o':
out_buf++;
break;
case 'f':
force_format++;
break;
case 'c':
errno = 0;
frame_count = strtol(optarg, NULL, 0);
if (errno)
errno_exit(optarg);
break;
default:
usage(io.stderr, argc, argv);
error(EXIT_FAILURE);
}
}
local fd = open_device(dev_name);
init_device(fd);
start_capturing(fd);
mainloop();
stop_capturing(fd);
uninit_device();
close_device(fd);
libc.fprintf(io.stderr, "\n");
return true;
end
main(#arg, arg)
|
require "initenv"
function create_network(args)
local net = nn.Sequential()
net:add(nn.Reshape(unpack(args.input_dims)))
--- first convolutional layer
local convLayer = nn.SpatialConvolution
net:add(convLayer(args.hist_len*args.ncols, args.n_units[1],
args.filter_size[1], args.filter_size[1],
args.filter_stride[1], args.filter_stride[1],1))
net:add(args.nl())
-- Add convolutional layers
for i=1,(#args.n_units-1) do
-- second convolutional layer
net:add(convLayer(args.n_units[i], args.n_units[i+1],
args.filter_size[i+1], args.filter_size[i+1],
args.filter_stride[i+1], args.filter_stride[i+1]))
net:add(args.nl())
end
local nel
if args.gpu >= 0 then
nel = net:cuda():forward(torch.zeros(1,unpack(args.input_dims))
:cuda()):nElement()
else
nel = net:forward(torch.zeros(1,unpack(args.input_dims))):nElement()
end
-- reshape all feature planes into a vector per example
net:add(nn.Reshape(nel))
-- fully connected layer
net:add(nn.Linear(nel, args.n_hid[1]))
net:add(args.nl())
local last_layer_size = args.n_hid[1]
for i=1,(#args.n_hid-1) do
-- add Linear layer
last_layer_size = args.n_hid[i+1]
net:add(nn.Linear(args.n_hid[i], last_layer_size))
net:add(args.nl())
end
local sr_splitter = nn.Sequential()
local sr_output_ftrs_dimensions = args.srdims-- 10
sr_splitter:add(nn.Linear(last_layer_size, sr_output_ftrs_dimensions))
sr_splitter:add(nn.Tanh())--args.nl())
sr_splitter:add(nn.Replicate(2)) -- one goes to reward and other to SR
sr_splitter:add(nn.SplitTable(1))
sr_fork = nn.ParallelTable();
mnet = nn.Sequential()
mnet:add(nn.GradScale(0)) --don't backprop through SR representation down to features. only reward should do this!
-- mnet:add(nn.Dropout(0.2))
mnet:add(nn.Replicate(args.n_actions))
mnet:add(nn.SplitTable(1))
mnet_subnets = nn.ParallelTable()
for i=1,args.n_actions do
mnet_fork = nn.Sequential()
mnet_fork:add(nn.Linear(sr_output_ftrs_dimensions, 512))
mnet_fork:add(args.nl())
mnet_fork:add(nn.Linear(512, 256))
mnet_fork:add(args.nl())
mnet_fork:add(nn.Linear(256, sr_output_ftrs_dimensions))
mnet_subnets:add(mnet_fork)
end
mnet:add(mnet_subnets)
sr_fork:add(mnet) -- SR prediction
rnet = nn.Sequential()
-- rnet:add(nn.Identity())
rnet:add(nn.Replicate(2))
rnet:add(nn.SplitTable(1))
rnet_fork = nn.ParallelTable()
-- extrinsic net
extrinsic_net = nn.Sequential()
extrinsic_net:add(nn.GradScale(1))
extrinsic_net:add(nn.Linear(sr_output_ftrs_dimensions, 1))
extrinsic_net:add(nn.Identity())
rnet_fork:add(extrinsic_net)
-- decoder
decoder = nn.Sequential()
decoder:add(nn.Reshape(sr_output_ftrs_dimensions, 1,1))
decoder:add(nn.SpatialFullConvolution(sr_output_ftrs_dimensions, 8*64, 4, 4))
decoder:add(nn.ReLU(true))
decoder:add(nn.SpatialFullConvolution(8*64, 4*64, 4, 4, 2, 2))
decoder:add(nn.ReLU(true))
decoder:add(nn.SpatialFullConvolution(4*64, 2*64, 4, 4, 2, 2,1,1))
decoder:add(nn.ReLU(true))
decoder:add(nn.SpatialFullConvolution(2*64, 64, 4, 4, 2, 2))
decoder:add(nn.ReLU(true))
decoder:add(nn.SpatialFullConvolution(64, args.ncols*args.hist_len, 4, 4, 2, 2,1,1))
-- decoder:add(nn.Tanh())
decoder:add(nn.Reshape(args.state_dim*args.hist_len))
decoder:add(nn.GradScale(1))
rnet_fork:add(decoder)
rnet:add(rnet_fork)
sr_fork:add(rnet) -- reward prediction
sr_splitter:add(sr_fork)
net:add(sr_splitter)
if args.gpu >=0 then
net:cuda()
end
if args.verbose >= 2 then
print(net)
print('Convolutional layers flattened output size:', nel)
end
return net
end
|
local ffi = require("ffi")
local levee = require("levee")
local _ = levee._
return {
test_spawn = function()
local h = levee.Hub()
local beats = {}
h:spawn(function()
for i = 1, 2 do
h:sleep(10)
table.insert(beats, "tick")
end
end)
for i = 1, 2 do
h:sleep(10)
table.insert(beats, "tock")
end
assert.same(beats, {"tick", "tock", "tick", "tock"})
end,
test_spawn_later = function()
local h = levee.Hub()
local trace = {}
h:spawn_later(30, function() table.insert(trace, {"f"}) end)
table.insert(trace, {"m", 1})
h:sleep(20)
table.insert(trace, {"m", 2})
h:sleep(20)
table.insert(trace, {"m", 3})
assert.same(trace, {
{"m", 1},
{"m", 2},
{"f"},
{"m", 3}, })
end,
test_spawn_return_value = function()
local h = levee.Hub()
local check
h:spawn(function()
check = 1
return check
end)
assert.equal(check, 1)
end,
test_coro = function()
local h = levee.Hub()
local trace = {}
local coros = {}
local function f(no)
table.insert(trace, {"f", no, 1})
coros[no] = coroutine.running()
local err, sender, value = h:pause()
table.insert(trace, {"f", no, 2, err, sender, value})
local err, sender, value = h:pause(20)
table.insert(trace, {"f", no, 3, err, sender, value})
end
table.insert(trace, {"m", 1})
h:spawn(f, 1)
table.insert(trace, {"m", 2})
h:spawn(f, 2)
table.insert(trace, {"m", 3})
h:resume(coros[2], "e2", "s2", "v2")
table.insert(trace, {"m", 4})
h:resume(coros[1], "e1", "s1", "v1")
table.insert(trace, {"m", 5})
h:continue()
table.insert(trace, {"m", 6})
assert.same(trace, {
{"m", 1},
{"f", 1, 1},
{"m", 2},
{"f", 2, 1},
{"m", 3},
{"m", 4},
{"m", 5},
{"f", 2, 2, "e2", "s2", "v2"},
{"f", 1, 2, "e1", "s1", "v1"},
{"m", 6}, })
trace = {}
h:sleep(30)
table.insert(trace, {"m", 7})
assert.same(trace, {
{"f", 2, 3, levee.errors.TIMEOUT},
{"f", 1, 3, levee.errors.TIMEOUT},
{"m", 7}, })
end,
test_register = function()
local h = levee.Hub()
local r, w = _.pipe()
local r_ev = h:register(r, true)
local pass, w_ev = h:register(w, false, true)
local err, sender, no = w_ev:recv(2000)
assert(not err)
assert.equal(no, 1)
local err, sender, no = w_ev:recv(20)
assert(err.is_levee_TIMEOUT)
_.write(w, "foo")
-- linux requires a read until writable will signal again
if ffi.os:lower() ~= "linux" then
local err, sender, no = w_ev:recv(2000)
assert(not err)
assert.equal(no, 1)
end
local err, sender, no = r_ev:recv()
assert(not err)
assert.equal(no, 1)
_.close(w)
local err, sender, no = r_ev:recv()
assert(not err)
assert.equal(no, -1)
assert(h:in_use())
h:unregister(r, true)
h:unregister(w, false, true)
assert(not h:in_use())
local err, sender, no = r_ev:recv()
assert(not err)
assert.equal(no, -1)
local err, sender, no = w_ev:recv()
assert(not err)
assert.equal(no, -1)
end,
test_times = function()
local h = levee.Hub()
local abs = h.poller:abstime(100LL)
local rel = h.poller:reltime(abs)
assert.equal(100LL, rel)
end,
test_sleep = function()
local h = levee.Hub()
local start = _.time.now()
h:sleep(100)
local stop = _.time.now()
local diff = (stop - start):seconds()
assert(diff > 0.09 and diff < 0.11, diff)
end,
test_error = function()
-- investigate the behavior of error reporting when a coroutine errors
-- skipped as this would trigger a FAIL otherwise
-- TODO: should it be possible to capture coroutines that crash?
do return "SKIP" end
local h = levee.Hub()
function foo()
assert(false)
end
h:spawn(function() foo() end)
end,
test_trace = function()
-- print()
-- print()
local h = levee.Hub({trace=true})
for i = 1, 3 do h:spawn(function() C.usleep(50*1000) end) end
local err, serve = h.stream:listen()
serve:close()
local a, b = h.trace:context(function()
local err, serve = h.stream:listen()
serve:close()
return 1, 2
end)
assert.equal(a, 1)
assert.equal(b, 2)
-- h.trace:pprint()
-- print()
h.trace:stop()
local filename = debug.getinfo(1, 'S').source:sub(2)
local M = loadfile(_.path.dirname(filename) .. "/../p/http/test_0_3.lua")()
h.trace:start()
M.test_proxy(h)
-- h.trace:pprint()
h.trace:stop()
h.trace:context(function() M.test_proxy(h) end)
-- print()
h.trace:start()
h.trace:context(function() M.test_proxy(h) end)
-- h.trace:pprint()
h.trace:stop()
end,
}
|
--
-- LANES.LUA
--
-- Multithreading and -core support for Lua
--
-- Author: Asko Kauppi <akauppi@gmail.com>
--
-- History:
-- Jun-08 AKa: major revise
-- 15-May-07 AKa: pthread_join():less version, some speedup & ability to
-- handle more threads (~ 8000-9000, up from ~ 5000)
-- 26-Feb-07 AKa: serialization working (C side)
-- 17-Sep-06 AKa: started the module (serialization)
--
--[[
===============================================================================
Copyright (C) 2007-08 Asko Kauppi <akauppi@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================================================
]]--
module( "lanes", package.seeall )
--require "lua51-lanes"
assert( type(lanes)=="table" )
local mm= lanes
local linda_id= assert( mm.linda_id )
local thread_new= assert(mm.thread_new)
local thread_status= assert(mm.thread_status)
local thread_join= assert(mm.thread_join)
local thread_cancel= assert(mm.thread_cancel)
local _single= assert(mm._single)
local _version= assert(mm._version)
local _deep_userdata= assert(mm._deep_userdata)
local now_secs= assert( mm.now_secs )
local wakeup_conv= assert( mm.wakeup_conv )
local timer_gateway= assert( mm.timer_gateway )
local max_prio= assert( mm.max_prio )
-- This check is for sublanes requiring Lanes
--
-- TBD: We could also have the C level expose 'string.gmatch' for us. But this is simpler.
--
if not string then
error( "To use 'lanes', you will also need to have 'string' available.", 2 )
end
--
-- Cache globals for code that might run under sandboxing
--
local assert= assert
local string_gmatch= assert( string.gmatch )
local select= assert( select )
local type= assert( type )
local pairs= assert( pairs )
local tostring= assert( tostring )
local error= assert( error )
local setmetatable= assert( setmetatable )
local rawget= assert( rawget )
ABOUT=
{
author= "Asko Kauppi <akauppi@gmail.com>",
description= "Running multiple Lua states in parallel",
license= "MIT/X11",
copyright= "Copyright (c) 2007-08, Asko Kauppi",
version= _version,
}
-- Making copies of necessary system libs will pass them on as upvalues;
-- only the first state doing "require 'lanes'" will need to have 'string'
-- and 'table' visible.
--
local function WR(str)
io.stderr:write( str.."\n" )
end
local function DUMP( tbl )
if not tbl then return end
local str=""
for k,v in pairs(tbl) do
str= str..k.."="..tostring(v).."\n"
end
WR(str)
end
---=== Laning ===---
-- lane_h[1..n]: lane results, same as via 'lane_h:join()'
-- lane_h[0]: can be read to make sure a thread has finished (always gives 'true')
-- lane_h[-1]: error message, without propagating the error
--
-- Reading a Lane result (or [0]) propagates a possible error in the lane
-- (and execution does not return). Cancelled lanes give 'nil' values.
--
-- lane_h.state: "pending"/"running"/"waiting"/"done"/"error"/"cancelled"
--
local lane_mt= {
__index= function( me, k )
if type(k) == "number" then
-- 'me[0]=true' marks we've already taken in the results
--
if not rawget( me, 0 ) then
-- Wait indefinately; either propagates an error or
-- returns the return values
--
me[0]= true -- marker, even on errors
local t= { thread_join(me._ud) } -- wait indefinate
--
-- { ... } "done": regular return, 0..N results
-- { } "cancelled"
-- { nil, err_str, stack_tbl } "error"
local st= thread_status(me._ud)
if st=="done" then
-- Use 'pairs' and not 'ipairs' so that nil holes in
-- the returned values are tolerated.
--
for i,v in pairs(t) do
me[i]= v
end
elseif st=="error" then
assert( t[1]==nil and t[2] and type(t[3])=="table" )
me[-1]= t[2]
-- me[-2] could carry the stack table, but even
-- me[-1] is rather unnecessary (and undocumented);
-- use ':join()' instead. --AKa 22-Jan-2009
elseif st=="cancelled" then
-- do nothing
else
error( "Unexpected status: "..st )
end
end
-- Check errors even if we'd first peeked them via [-1]
-- and then came for the actual results.
--
local err= rawget(me, -1)
if err~=nil and k~=-1 then
-- Note: Lua 5.1 interpreter is not prepared to show
-- non-string errors, so we use 'tostring()' here
-- to get meaningful output. --AKa 22-Jan-2009
--
-- Also, the stack dump we get is no good; it only
-- lists our internal Lanes functions. There seems
-- to be no way to switch it off, though.
-- Level 3 should show the line where 'h[x]' was read
-- but this only seems to work for string messages
-- (Lua 5.1.4). No idea, why. --AKa 22-Jan-2009
--
error( tostring(err), 3 ) -- level 3 should show the line where 'h[x]' was read
end
return rawget( me, k )
--
elseif k=="status" then -- me.status
return thread_status(me._ud)
--
else
error( "Unknown key: "..k )
end
end
}
-----
-- h= lanes.gen( [libs_str|opt_tbl [, ...],] lane_func ) ( [...] )
--
-- 'libs': nil: no libraries available (default)
-- "": only base library ('assert', 'print', 'unpack' etc.)
-- "math,os": math + os + base libraries (named ones + base)
-- "*": all standard libraries available
--
-- 'opt': .priority: int (-2..+2) smaller is lower priority (0 = default)
--
-- .cancelstep: bool | uint
-- false: cancellation check only at pending Linda operations
-- (send/receive) so no runtime performance penalty (default)
-- true: adequate cancellation check (same as 100)
-- >0: cancellation check every x Lua lines (small number= faster
-- reaction but more performance overhead)
--
-- .globals: table of globals to set for a new thread (passed by value)
--
-- ... (more options may be introduced later) ...
--
-- Calling with a function parameter ('lane_func') ends the string/table
-- modifiers, and prepares a lane generator. One can either finish here,
-- and call the generator later (maybe multiple times, with different parameters)
-- or add on actual thread arguments to also ignite the thread on the same call.
--
local lane_proxy
local valid_libs= {
["package"]= true,
["table"]= true,
["io"]= true,
["os"]= true,
["string"]= true,
["math"]= true,
["debug"]= true,
--
["base"]= true,
["coroutine"]= true,
["*"]= true
}
function gen( ... )
local opt= {}
local libs= nil
local lev= 2 -- level for errors
local n= select('#',...)
if n==0 then
error( "No parameters!" )
end
for i=1,n-1 do
local v= select(i,...)
if type(v)=="string" then
libs= libs and libs..","..v or v
elseif type(v)=="table" then
for k,vv in pairs(v) do
opt[k]= vv
end
elseif v==nil then
-- skip
else
error( "Bad parameter: "..tostring(v) )
end
end
local func= select(n,...)
if type(func)~="function" then
error( "Last parameter not function: "..tostring(func) )
end
-- Check 'libs' already here, so the error goes in the right place
-- (otherwise will be noticed only once the generator is called)
--
if libs then
for s in string_gmatch(libs, "[%a*]+") do
if not valid_libs[s] then
error( "Bad library name: "..s )
end
end
end
local prio, cs, g_tbl
for k,v in pairs(opt) do
if k=="priority" then prio= v
elseif k=="cancelstep" then cs= (v==true) and 100 or
(v==false) and 0 or
type(v)=="number" and v or
error( "Bad cancelstep: "..tostring(v), lev )
elseif k=="globals" then g_tbl= v
--..
elseif k==1 then error( "unkeyed option: ".. tostring(v), lev )
else error( "Bad option: ".. tostring(k), lev )
end
end
-- Lane generator
--
return function(...)
return lane_proxy( thread_new( func, libs, cs, prio, g_tbl,
... ) ) -- args
end
end
lane_proxy= function( ud )
local proxy= {
_ud= ud,
-- void= me:cancel()
--
cancel= function(me) thread_cancel(me._ud) end,
-- [...] | [nil,err,stack_tbl]= me:join( [wait_secs=-1] )
--
join= function( me, wait )
return thread_join( me._ud, wait )
end,
}
assert( proxy._ud )
setmetatable( proxy, lane_mt )
return proxy
end
---=== Lindas ===---
-- We let the C code attach methods to userdata directly
-----
-- linda_ud= lanes.linda()
--
function linda()
local proxy= _deep_userdata( linda_id )
assert( (type(proxy) == "userdata") and getmetatable(proxy) )
return proxy
end
---=== Timers ===---
--
-- On first 'require "lanes"', a timer lane is spawned that will maintain
-- timer tables and sleep in between the timer events. All interaction with
-- the timer lane happens via a 'timer_gateway' Linda, which is common to
-- all that 'require "lanes"'.
--
-- Linda protocol to timer lane:
--
-- TGW_KEY: linda_h, key, [wakeup_at_secs], [repeat_secs]
--
local TGW_KEY= "(timer control)" -- the key does not matter, a 'weird' key may help debugging
local first_time_key= "first time"
local first_time= timer_gateway:get(first_time_key) == nil
timer_gateway:set(first_time_key,true)
--
-- Timer lane; initialize only on the first 'require "lanes"' instance (which naturally
-- has 'table' always declared)
--
if first_time then
local table_remove= assert( table.remove )
local table_insert= assert( table.insert )
--
-- { [deep_linda_lightuserdata]= { [deep_linda_lightuserdata]=linda_h,
-- [key]= { wakeup_secs [,period_secs] } [, ...] },
-- }
--
-- Collection of all running timers, indexed with linda's & key.
--
-- Note that we need to use the deep lightuserdata identifiers, instead
-- of 'linda_h' themselves as table indices. Otherwise, we'd get multiple
-- entries for the same timer.
--
-- The 'hidden' reference to Linda proxy is used in 'check_timers()' but
-- also important to keep the Linda alive, even if all outside world threw
-- away pointers to it (which would ruin uniqueness of the deep pointer).
-- Now we're safe.
--
local collection= {}
--
-- set_timer( linda_h, key [,wakeup_at_secs [,period_secs]] )
--
local function set_timer( linda, key, wakeup_at, period )
assert( wakeup_at==nil or wakeup_at>0.0 )
assert( period==nil or period>0.0 )
local linda_deep= linda:deep()
assert( linda_deep )
-- Find or make a lookup for this timer
--
local t1= collection[linda_deep]
if not t1 then
t1= { [linda_deep]= linda } -- proxy to use the Linda
collection[linda_deep]= t1
end
if wakeup_at==nil then
-- Clear the timer
--
t1[key]= nil
-- Remove empty tables from collection; speeds timer checks and
-- lets our 'safety reference' proxy be gc:ed as well.
--
local empty= true
for k,_ in pairs(t1) do
if k~= linda_deep then
empty= false; break
end
end
if empty then
collection[linda_deep]= nil
end
-- Note: any unread timer value is left at 'linda[key]' intensionally;
-- clearing a timer just stops it.
else
-- New timer or changing the timings
--
local t2= t1[key]
if not t2 then
t2= {}; t1[key]= t2
end
t2[1]= wakeup_at
t2[2]= period -- can be 'nil'
end
end
-----
-- [next_wakeup_at]= check_timers()
--
-- Check timers, and wake up the ones expired (if any)
--
-- Returns the closest upcoming (remaining) wakeup time (or 'nil' if none).
--
local function check_timers()
local now= now_secs()
local next_wakeup
for linda_deep,t1 in pairs(collection) do
for key,t2 in pairs(t1) do
--
if key==linda_deep then
-- no 'continue' in Lua :/
else
-- 't2': { wakeup_at_secs [,period_secs] }
--
local wakeup_at= t2[1]
local period= t2[2] -- may be 'nil'
if wakeup_at <= now then
local linda= t1[linda_deep]
assert(linda)
linda:set( key, now )
-- 'pairs()' allows the values to be modified (and even
-- removed) as far as keys are not touched
if not period then
-- one-time timer; gone
--
t1[key]= nil
wakeup_at= nil -- no 'continue' in Lua :/
else
-- repeating timer; find next wakeup (may jump multiple repeats)
--
repeat
wakeup_at= wakeup_at+period
until wakeup_at > now
t2[1]= wakeup_at
end
end
if wakeup_at and ((not next_wakeup) or (wakeup_at < next_wakeup)) then
next_wakeup= wakeup_at
end
end
end -- t2 loop
end -- t1 loop
return next_wakeup -- may be 'nil'
end
-----
-- Snore loop (run as a lane on the background)
--
-- High priority, to get trustworthy timings.
--
-- We let the timer lane be a "free running" thread; no handle to it
-- remains.
--
gen( "io", { priority=max_prio }, function()
while true do
local next_wakeup= check_timers()
-- Sleep until next timer to wake up, or a set/clear command
--
local secs= next_wakeup and (next_wakeup - now_secs()) or nil
local linda= timer_gateway:receive( secs, TGW_KEY )
if linda then
local key= timer_gateway:receive( 0.0, TGW_KEY )
local wakeup_at= timer_gateway:receive( 0.0, TGW_KEY )
local period= timer_gateway:receive( 0.0, TGW_KEY )
assert( key and wakeup_at and period )
set_timer( linda, key, wakeup_at, period>0 and period or nil )
end
end
end )()
end
-----
-- = timer( linda_h, key_val, date_tbl|first_secs [,period_secs] )
--
function timer( linda, key, a, period )
if a==0.0 then
-- Caller expects to get current time stamp in Linda, on return
-- (like the timer had expired instantly); it would be good to set this
-- as late as possible (to give most current time) but also we want it
-- to precede any possible timers that might start striking.
--
linda:set( key, now_secs() )
if not period or period==0.0 then
timer_gateway:send( TGW_KEY, linda, key, nil, nil ) -- clear the timer
return -- nothing more to do
end
a= period
end
local wakeup_at= type(a)=="table" and wakeup_conv(a) -- given point of time
or now_secs()+a
-- queue to timer
--
timer_gateway:send( TGW_KEY, linda, key, wakeup_at, period )
end
---=== Lock & atomic generators ===---
-- These functions are just surface sugar, but make solutions easier to read.
-- Not many applications should even need explicit locks or atomic counters.
--
-- lock_f= lanes.genlock( linda_h, key [,N_uint=1] )
--
-- = lock_f( +M ) -- acquire M
-- ...locked...
-- = lock_f( -M ) -- release M
--
-- Returns an access function that allows 'N' simultaneous entries between
-- acquire (+M) and release (-M). For binary locks, use M==1.
--
function genlock( linda, key, N )
linda:limit(key,N)
linda:set(key,nil) -- clears existing data
--
-- [true [, ...]= trues(uint)
--
local function trues(n)
if n>0 then return true,trues(n-1) end
end
return
function(M)
if M>0 then
-- 'nil' timeout allows 'key' to be numeric
linda:send( nil, key, trues(M) ) -- suspends until been able to push them
else
for i=1,-M do
linda:receive( key )
end
end
end
end
--
-- atomic_f= lanes.genatomic( linda_h, key [,initial_num=0.0] )
--
-- int= atomic_f( [diff_num=1.0] )
--
-- Returns an access function that allows atomic increment/decrement of the
-- number in 'key'.
--
function genatomic( linda, key, initial_val )
linda:limit(key,2) -- value [,true]
linda:set(key,initial_val or 0.0) -- clears existing data (also queue)
return
function(diff)
-- 'nil' allows 'key' to be numeric
linda:send( nil, key, true ) -- suspends until our 'true' is in
local val= linda:get(key) + (diff or 1.0)
linda:set( key, val ) -- releases the lock, by emptying queue
return val
end
end
--the end
|
--[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2016 Paul Norman, MIT license
]]--
require "landform"
print("landform.lua tests")
print("TESTING: accept_landform_point")
assert(not accept_landform_point({}), "test failed: untagged")
assert(not accept_landform_point({foo="bar"}), "test failed: other tags")
assert(accept_landform_point({natural="peak"}), "test failed: natural=peak")
assert(accept_landform_point({natural="saddle"}), "test failed: natural=saddle")
assert(accept_landform_point({natural="volcano"}), "test failed: natural=volcano")
assert(accept_landform_point({natural="cave_entrance"}), "test failed: natural=cave_entrance")
assert(accept_landform_point({natural="cliff"}), "test failed: natural=cliff")
print("TESTING: transform_landform_point")
assert(deepcompare(transform_landform_point({}), {}), "test failed: no tags")
assert(transform_landform_point({natural="peak"}).landform == "peak", "test failed: peak")
assert(transform_landform_point({natural="saddle"}).landform == "saddle", "test failed: saddle")
assert(transform_landform_point({natural="volcano"}).landform == "volcano", "test failed: volcano")
assert(transform_landform_point({natural="cave_entrance"}).landform == "cave_entrance", "test failed: cave_entrance")
assert(transform_landform_point({natural="cliff"}).landform == "rock_spire", "test failed: rock_spire")
assert(transform_landform_point({name="foo"}).name == "foo", "test failed: name")
assert(transform_landform_point({["name:en"]="foo"}).names == '"en"=>"foo"', "test failed: names")
assert(transform_landform_point({["ele"]="5"}).elevation == "5", "test failed: ele")
print("TESTING: accept_landform_line")
assert(not accept_landform_line({}), "test failed: untagged")
assert(not accept_landform_line({foo="bar"}), "test failed: other tags")
assert(accept_landform_line({natural="cliff"}), "test failed: natural=cliff")
assert(accept_landform_line({natural="ridge"}), "test failed: natural=ridge")
assert(accept_landform_line({natural="arete"}), "test failed: natural=arete")
assert(accept_landform_line({man_made="embankment"}), "test failed: man_made=embankment")
print("TESTING: transform_landform_line")
assert(deepcompare(transform_landform_line({}), {}), "test failed: no tags")
assert(transform_landform_line({natural="cliff"}).landform == "cliff", "test failed: cliff")
assert(transform_landform_line({natural="ridge"}).landform == "ridge", "test failed: ridge")
assert(transform_landform_line({natural="arete"}).landform == "arete", "test failed: arete")
assert(transform_landform_line({man_made="embankment"}).landform == "embankment", "test failed: embankment")
assert(transform_landform_line({natural="cliff", man_made="embankment"}).landform == "cliff", "test failed: cliff+embankment")
assert(transform_landform_line({name="foo"}).name == "foo", "test failed: name")
assert(transform_landform_line({["name:en"]="foo"}).names == '"en"=>"foo"', "test failed: names")
|
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937'
files {}
server_scripts {"server.lua"}
client_scripts {"client.lua"} |
data:extend({
{
type = "selection-tool",
name = "ore-move-planner",
icon = "__KingsOmniMatterMove__/graphics/planner.png",
icon_size = 32,
stack_size = 1,
stackable = false,
subgroup = "tool",
order = "c[automated-construction]-d[dirty-planner]",
flags = {"only-in-cursor", "spawnable"},
selection_color = {r = 1.0, g = 0.2, b = 1.0, a = 0.3},
alt_selection_color = {r = 0.2, g = 0.8, b = 0.3, a = 0.3},
selection_mode = "any-entity",
alt_selection_mode = "any-entity",
selection_cursor_box_type = "entity",
alt_selection_cursor_box_type = "entity"
},
{
type = "custom-input",
name = "give-ore-move-planner",
key_sequence = "ALT + M",
consuming = "game-only",
action = "lua"
},
{
type = "shortcut",
name = "ore-move-planner-shortcut",
localised_name = {"item-name.ore-move-planner"},
action = "lua",
associated_control_input = "give-ore-move-planner",
icon = {
filename = "__KingsOmniMatterMove__/graphics/planner-shortcut.png",
size = 128,
scale = 1,
flags = {"gui-icon"}
},
disabled_icon = {
filename = "__KingsOmniMatterMove__/graphics/planner-shortcut-white.png",
size = 128,
scale = 1,
flags = {"gui-icon"}
},
small_icon = {
filename = "__KingsOmniMatterMove__/graphics/planner-shortcut-white.png",
size = 128,
scale = 1,
flags = {"gui-icon"}
},
}
}) |
----------------------------------------------------------------------
-- sys - a package that provides simple system (unix) tools
----------------------------------------------------------------------
local os = require 'os'
local io = require 'io'
local paths = require 'paths'
sys = {}
--------------------------------------------------------------------------------
-- load all functions from lib
--------------------------------------------------------------------------------
local _lib = require 'libsys'
for k,v in pairs(_lib) do
sys[k] = v
end
--------------------------------------------------------------------------------
-- tic/toc (matlab-like) timers
--------------------------------------------------------------------------------
local __t__
function sys.tic()
__t__ = sys.clock()
end
function sys.toc(verbose)
local __dt__ = sys.clock() - __t__
if verbose then print(__dt__) end
return __dt__
end
--------------------------------------------------------------------------------
-- execute an OS command, but retrieves the result in a string
--------------------------------------------------------------------------------
local function execute(cmd)
local cmd = cmd .. ' 2>&1'
local f = io.popen(cmd)
local s = f:read('*all')
f:close()
s = s:gsub('^%s*',''):gsub('%s*$','')
return s
end
sys.execute = execute
--------------------------------------------------------------------------------
-- execute an OS command, but retrieves the result in a string
-- side effect: file in /tmp
-- this call is typically more robust than the one above (on some systems)
--------------------------------------------------------------------------------
function sys.fexecute(cmd, readwhat)
readwhat = readwhat or '*all'
local tmpfile = os.tmpname()
local cmd = cmd .. ' >'.. tmpfile..' 2>&1'
os.execute(cmd)
local file = _G.assert(io.open(tmpfile))
local s= file:read(readwhat)
file:close()
s = s:gsub('^%s*',''):gsub('%s*$','')
os.remove(tmpfile)
return s
end
--------------------------------------------------------------------------------
-- returns the name of the OS in use
-- warning, this method is extremely dumb, and should be replaced by something
-- more reliable
--------------------------------------------------------------------------------
function sys.uname()
if paths.dirp('C:\\') then
return 'windows'
else
local ffi = require 'ffi'
local os = ffi.os
if os:find('Linux') then
return 'linux'
elseif os:find('OSX') then
return 'macos'
else
return '?'
end
end
end
sys.OS = sys.uname()
--------------------------------------------------------------------------------
-- ls (list dir)
--------------------------------------------------------------------------------
sys.ls = function(d) d = d or ' ' return execute('ls ' ..d) end
sys.ll = function(d) d = d or ' ' return execute('ls -l ' ..d) end
sys.la = function(d) d = d or ' ' return execute('ls -a ' ..d) end
sys.lla = function(d) d = d or ' ' return execute('ls -la '..d) end
--------------------------------------------------------------------------------
-- prefix
--------------------------------------------------------------------------------
local function find_prefix()
if arg then
for i, v in pairs(arg) do
if type(i) == "number" and type(v) == "string" and i <= 0 then
local lua_path = paths.basename(v)
if lua_path == "luajit" or lua_path == "lua" then
local bin_dir = paths.dirname(v)
if paths.basename(bin_dir) == "bin" then
return paths.dirname(bin_dir)
else
return bin_dir
end
end
end
end
end
return ""
end
sys.prefix = find_prefix()
--------------------------------------------------------------------------------
-- always returns the path of the file running
--------------------------------------------------------------------------------
sys.fpath = require 'sys.fpath'
--------------------------------------------------------------------------------
-- split string based on pattern pat
--------------------------------------------------------------------------------
function sys.split(str, pat)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, last_end)
while s do
if s ~= 1 or cap ~= "" then
_G.table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
_G.table.insert(t, cap)
end
return t
end
--------------------------------------------------------------------------------
-- check if a number is NaN
--------------------------------------------------------------------------------
function sys.isNaN(number)
-- We rely on the property that NaN is the only value that doesn't equal itself.
return (number ~= number)
end
--------------------------------------------------------------------------------
-- sleep
--------------------------------------------------------------------------------
function sys.sleep(seconds)
sys.usleep(seconds*1000000)
end
--------------------------------------------------------------------------------
-- colors, can be used to print things in color
--------------------------------------------------------------------------------
sys.COLORS = require 'sys.colors'
--------------------------------------------------------------------------------
-- backward compat
--------------------------------------------------------------------------------
sys.dirname = paths.dirname
sys.concat = paths.concat
return sys
|
return {'bjorn','bjorn','bjorns','bjorns'} |
--Commands
COMM_INIT = "\27@"
COMM_CLR = "\12"
COMM_HOM = "\11"
COMM_CSR_OFF = "\31\67\00"
COMM_CSR_ON = "\31\67\01"
--Constants
PORT = 2342
ROW_LENGTH = 20
--State variables
first_msg = true
function info(ip, port)
uart.write(0, COMM_CLR)
uart.write(0, COMM_CSR_OFF)
local sIP = "IP"
local sPORT = "PORT"
local sPortNum = tostring(port)
sIP = sIP .. string.rep(' ', ROW_LENGTH - #sIP - #ip) .. ip
sPORT = sPORT .. string.rep(' ', ROW_LENGTH - #sPORT - #sPortNum) .. sPortNum
uart.write(0, sIP .. sPORT)
uart.write(0, COMM_HOM)
end
function init()
--Initialize display
uart.setup(0, 9600, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1)
uart.write(0, COMM_INIT)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(t)
info(t.IP, PORT)
end)
--Start tcp-server
s = net.createServer(net.TCP, 180)
s:listen(PORT, function(c)
c:on("receive", function(c,l)
--clear the info
if first_msg then
first_msg = false
uart.write(0, COMM_CLR)
uart.write(0, COMM_CSR_ON)
end
uart.write(0, l)
end)
end)
end
init()
|
-- Docfarming Cucumber imported into Farming_Plus by MTDad
-- main `S` code in init.lua
local S
S = farming.S
minetest.register_craftitem("farming_plus:cucumber_seed", {
description = S("Cucumber Seeds"),
inventory_image = "farming_cucumber_seed.png",
on_place = function(itemstack, placer, pointed_thing)
return farming.place_seed(itemstack, placer, pointed_thing, "farming_plus:cucumber_1")
end
})
minetest.register_node("farming_plus:cucumber_1", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_1.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+3/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber_2", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_2.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+5/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber_3", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_3.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+7/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber_4", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_4.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+9/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber_5", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_5.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+11/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber_6", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
drop = "",
tiles = {"farming_cucumber_6.png"},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.5+13/16, 0.5}
},
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_node("farming_plus:cucumber", {
paramtype = "light",
walkable = false,
drawtype = "plantlike",
tiles = {"farming_cucumber_7.png"},
drop = {
max_items = 3, --reduced from 6>3
items = {
-- { items = {'farming_plus:cucumber_seed'} },
-- { items = {'farming_plus:cucumber_seed'}, rarity = 2},
-- { items = {'farming_plus:cucumber_seed'}, rarity = 5},
{ items = {'farming_plus:cucumber_item'} },
{ items = {'farming_plus:cucumber_item'}, rarity = 2 },
{ items = {'farming_plus:cucumber_item'}, rarity = 5 }
}
},
groups = {snappy=3, flammable=2, not_in_creative_inventory=1, plant=1},
sounds = default.node_sound_leaves_defaults(),
})
minetest.register_craftitem("farming_plus:cucumber_item", {
description = S("Cucumber"),
inventory_image = "farming_cucumber.png",
groups = {food_cucumber = 1},
on_use = minetest.item_eat(3),
})
-- Craft added for seed acquisition
minetest.register_craft({
output = "farming_plus:cucumber_seed 4",
recipe = {
{"farming_plus:cucumber_item"},
}
})
farming.add_plant("farming_plus:cucumber", {"farming_plus:cucumber_1", "farming_plus:cucumber_2", "farming_plus:cucumber_3", "farming_plus:cucumber_4", "farming_plus:cucumber_5", "farming_plus:cucumber_6"}, 250, 2)
minetest.register_alias("docfarming:cucumberseed", "farming_plus:cucumber_seed")
minetest.register_alias("docfarming:cucumber", "farming_plus:cucumber_item")
minetest.register_alias("farming:cucumber", "farming_plus:cucumber_item")
minetest.register_alias("docfarming:cucumber1", "farming_plus:cucumber_1")
minetest.register_alias("farming:cucumber_1", "farming_plus:cucumber_1")
minetest.register_alias("docfarming:cucumber2", "farming_plus:cucumber_2")
minetest.register_alias("farming:cucumber_2", "farming_plus:cucumber_2")
minetest.register_alias("docfarming:cucumber3", "farming_plus:cucumber_5")
minetest.register_alias("farming:cucumber_3", "farming_plus:cucumber_5")
minetest.register_alias("docfarming:cucumber4", "farming_plus:cucumber")
minetest.register_alias("farming:cucumber_4", "farming_plus:cucumber")
|
local M = {}
vim.g.mapleader = ' '
vim.g.maplocalleader = ' '
M.prefix = {
bufferline = '<leader>b',
coderunner = '<leader>c',
hop = '<leader>h',
lsp = '<leader>l',
nvimtree = '<leader>n',
playground = '<leader>p',
telescope = '<leader>t',
visualmulti = '<leader>v',
}
M.register_prefix = function(plugin_name, prefix, prefix_name)
if prefix == nil then
require('which-key').register {
[M.prefix[plugin_name]] = { name = '+[' .. plugin_name .. ']' },
}
else
require('which-key').register {
[M.prefix[plugin_name] .. prefix] = { name = '+[' .. plugin_name .. '] ' .. prefix_name },
}
end
end
M.register_keymap = function(plugin_name, mode, lhs, rhs, desc, bufnr, opts)
opts = opts or {}
opts.noremap = true
opts.silent = true
if bufnr == nil then
vim.api.nvim_set_keymap(mode, M.prefix[plugin_name] .. lhs, rhs, opts)
require('which-key').register {
[M.prefix[plugin_name] .. lhs] = { rhs, '[' .. plugin_name .. '] ' .. desc },
}
else
vim.api.nvim_buf_set_keymap(bufnr, mode, M.prefix[plugin_name] .. lhs, rhs, opts)
require('which-key').register({
[M.prefix[plugin_name] .. lhs] = { rhs, '[' .. plugin_name .. '] ' .. desc },
}, { buffer = bufnr })
end
end
return M
|
data:extend(
{
{
type = "recipe",
name = "MOX-recipe",
icon = graphics .. "MOX.png",
icon_size = 64, mipmap_count = 4,
category = "centrifuging",
energy_required = 20,
enabled = false,
order = "d",
subgroup = "resources",
ingredients =
{
{"uranium-235", 9},
{"plutonium", 1}
},
always_show_made_in = true,
results = {
{"MOX", 8},
},
}
}) |
-- Nuclear Winter
--------------------------------------------------------------
function CountFalloutPlots() -------Count the Fallout plots on the map
local iFallout = 0
for plotLoop = 0, Map.GetNumPlots() - 1, 1 do
local plot = Map.GetPlotByIndex(plotLoop);
local featureType = plot:GetFeatureType();
if ( featureType == FeatureTypes.FEATURE_FALLOUT ) then
iFallout = iFallout + 1
end
end
print("Fallout Plots:"..iFallout)
return iFallout
end
function NukeExploded()----------When nuke exploded, start the counter
local MapTotalPlots = Map.GetNumPlots()
-- local TotallandPlots = Map.GetNumLandAreas() -------------get the total number of plots
print ("Map Plots:" ..MapTotalPlots)
-- print ("land Area" ..TotallandPlots)
local FalloutTotal = CountFalloutPlots()
local FalloutPerCent = FalloutTotal/MapTotalPlots
print ("Fallout Percent:"..FalloutPerCent)
if FalloutPerCent > 0.005 and FalloutPerCent <= 0.01 then
PlayerNotice(0)
elseif FalloutPerCent > 0.01 and FalloutPerCent <= 0.05 then ------------------------When the fallout plots reaches beyond the thershold, trigger the nuclear winter
NuclearWinterLV1()
PlayerNotice(1)
elseif FalloutPerCent > 0.05 and FalloutPerCent <= 0.1 then
NuclearWinterLV2()
PlayerNotice(2)
elseif FalloutPerCent > 0.1 then
NuclearWinterLV3()
PlayerNotice(3)
end
end
GameEvents.NuclearDetonation.Add(NukeExploded)
function NuclearWinterLV1()
print ( "Nuclear Winter Strikes: LV1")
for plotLoop = 0, Map.GetNumPlots() - 1, 1 do
local plot = Map.GetPlotByIndex(plotLoop);
local FoodYield = plot:GetYield(YieldTypes.YIELD_FOOD) ---------All plots with Food Yield >4 will reduce its food yield to 4
if ( FoodYield > 3 ) then
local pPlotX = plot:GetX()
local pPlotY = plot:GetY()
Game.SetPlotExtraYield(pPlotX, pPlotY, GameInfoTypes.YIELD_FOOD, -1)
end
end
end
function NuclearWinterLV2()
print ( "Nuclear Winter Strikes: LV2")
for plotLoop = 0, Map.GetNumPlots() - 1, 1 do
local plot = Map.GetPlotByIndex(plotLoop);
local FoodYield = plot:GetYield(YieldTypes.YIELD_FOOD) ---------All plots with Food Yield >1 will reduce its food yield to 1
if ( FoodYield > 1 ) then
local pPlotX = plot:GetX()
local pPlotY = plot:GetY()
Game.SetPlotExtraYield(pPlotX, pPlotY, GameInfoTypes.YIELD_FOOD, -1)
end
end
end
function NuclearWinterLV3()
print ( "Nuclear Winter Strikes: LV3")
for plotLoop = 0, Map.GetNumPlots() - 1, 1 do
local plot = Map.GetPlotByIndex(plotLoop);
local FoodYield = plot:GetYield(YieldTypes.YIELD_FOOD) ---------All plots reduce its food yield to 0!
local ProductionYield = plot:GetYield(YieldTypes.YIELD_PRODUCTION) ---------All plots reduce its production yield to 0!
if ( FoodYield > 0 ) then
local pPlotX = plot:GetX()
local pPlotY = plot:GetY()
Game.SetPlotExtraYield(pPlotX, pPlotY, GameInfoTypes.YIELD_FOOD, -1)
end
if ( ProductionYield > 0 ) then
local pPlotX = plot:GetX()
local pPlotY = plot:GetY()
Game.SetPlotExtraYield(pPlotX, pPlotY, GameInfoTypes.YIELD_PRODUCTION, -1)
end
end
end
function PlayerNotice(iCounter)
local player = Players[Game.GetActivePlayer()]
if iCounter == 0 then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER" )
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_SHORT")
player:AddNotification(NotificationTypes.NOTIFICATION_GENERIC, text, heading, -1, -1);
elseif iCounter == 1 then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV1" )
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV1_SHORT")
player:AddNotification(NotificationTypes.NOTIFICATION_STARVING, text, heading, -1, -1);
elseif iCounter == 2 then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV2" )
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV2_SHORT")
player:AddNotification(NotificationTypes.NOTIFICATION_STARVING, text, heading, -1, -1);
elseif iCounter == 3 then
local text = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV3" )
local heading = Locale.ConvertTextKey("TXT_KEY_SP_NOTIFICATION_NUCLEAR_WINTER_LV3_SHORT")
player:AddNotification(NotificationTypes.NOTIFICATION_STARVING, text, heading, -1, -1);
end
end
print("Nuclear Winter Check Pass!")
|
local beautiful = require("beautiful")
local mstab = require(... .. ".mstab")
beautiful.layout_mstab = mstab.get_icon()
local vertical = require(... .. ".vertical")
beautiful.layout_vertical = vertical.get_icon()
local horizontal = require(... .. ".horizontal")
beautiful.layout_horizontal = horizontal.get_icon()
local centered = require(... .. ".centered")
beautiful.layout_centered = centered.get_icon()
local layout = {
mstab = mstab.layout,
centered = centered.layout,
vertical = vertical.layout,
horizontal = horizontal.layout
}
return layout
|
local chatSharp = clr.ChatSharp
local client = chatSharp.IrcClient('irc.rizon.net', chatSharp.IrcUser('citimate', 'mateyate'), false)
-- temporary workaround for connections that never triggered playerActivated but triggered playerDropped
local activatedPlayers = {}
client.ConnectionComplete:add(function(s : object, e : System.EventArgs) : void
client:JoinChannel('#meow')
end)
-- why is 'received' even misspelled here?
client.ChannelMessageRecieved:add(function(s : object, e : ChatSharp.Events.PrivateMessageEventArgs) : void
local msg = e.PrivateMessage
TriggerClientEvent('chatMessage', -1, msg.User.Nick, { 0, 0x99, 255 }, msg.Message)
end)
AddEventHandler('playerActivated', function()
client:SendMessage('* ' .. GetPlayerName(source) .. '(' .. GetPlayerGuid(source) .. '@' .. GetPlayerEP(source) .. ') joined the server', '#fourdeltaone')
table.insert(activatedPlayers, GetPlayerGuid(source))
end)
AddEventHandler('playerDropped', function()
-- find out if this connection ever triggered playerActivated
for index,guid in pairs(activatedPlayers) do
if guid == playerGuid then
-- show player dropping connection in chat
client:SendMessage('* ' .. GetPlayerName(source) .. '(' .. GetPlayerGuid(source) .. '@' .. GetPlayerEP(source) .. ') left the server', '#fourdeltaone')
table.remove(activatedPlayers, index)
return
end
end
end)
AddEventHandler('chatMessage', function(source, name, message)
print('hey there ' .. name)
local displayMessage = gsub(message, '^%d', '')
-- ignore zero-length messages
if string.len(displayMessage) == 0 then
return
end
-- ignore chat messages that are actually commands
if string.sub(displayMessage, 1, 1) == "/" then
return
end
client:SendMessage('[' .. tostring(GetPlayerName(source)) .. ']: ' .. displayMessage, '#fourdeltaone')
end)
AddEventHandler('onPlayerKilled', function(playerId, attackerId, reason, position)
local player = GetPlayerByServerId(playerId)
local attacker = GetPlayerByServerId(attackerId)
local reasonString = 'killed'
if reason == 0 or reason == 56 or reason == 1 or reason == 2 then
reasonString = 'meleed'
elseif reason == 3 then
reasonString = 'knifed'
elseif reason == 4 or reason == 6 or reason == 18 or reason == 51 then
reasonString = 'bombed'
elseif reason == 5 or reason == 19 then
reasonString = 'burned'
elseif reason == 7 or reason == 9 then
reasonString = 'pistoled'
elseif reason == 10 or reason == 11 then
reasonString = 'shotgunned'
elseif reason == 12 or reason == 13 or reason == 52 then
reasonString = 'SMGd'
elseif reason == 14 or reason == 15 or reason == 20 then
reasonString = 'assaulted'
elseif reason == 16 or reason == 17 then
reasonString = 'sniped'
elseif reason == 49 or reason == 50 then
reasonString = 'ran over'
end
client:SendMessage('* ' .. attacker.name .. ' ' .. reasonString .. ' ' .. player.name, '#fourdeltaone')
end)
client:ConnectAsync()
AddEventHandler('onResourceStop', function(name)
if name == GetInvokingResource() then
client:Quit('Resource stopping.')
end
end) |
--flee.lua
local SUCCESS = luabt.SUCCESS
local RUNNING = luabt.RUNNING
local Flee = class()
function Flee:__init(tick_num)
self.name = "flee"
self.tick_num = tick_num
end
function Flee:open(tree)
if self.tick_num <= 0 then
return SUCCESS
end
print(self.tick_num, "start flee....")
end
function Flee:run(tree)
self.tick_num = self.tick_num - 1
tree.robot.hp = tree.robot.hp + 2;
print(tree.robot.hp, "fleeing.......")
if self.tick_num <= 0 then
print(tree.robot.hp, "finish flee")
return SUCCESS
end
return RUNNING
end
function Flee:close(tree)
print("close flee")
end
return Flee
|
function plugindef()
-- This function and the 'finaleplugin' namespace
-- are both reserved for the plug-in definition.
finaleplugin.RequireSelection = true
finaleplugin.Author = "Robert Patterson"
finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/"
finaleplugin.Version = "1.1"
finaleplugin.Date = "March 20, 2021"
finaleplugin.CategoryTags = "Expression"
return "Expression Add Opaque Background", "Expression Add Opaque Background", "Add an opaque background to any single-staff text expression in the currenly selected region."
end
local path = finale.FCString()
path:SetRunningLuaFolderPath()
package.path = package.path .. ";" .. path.LuaString .. "?.lua"
local library = require("library.general_library")
local expression = require("library.expression")
-- note: if an expression already has an enclosure, this routine simply makes it opaque
-- As of June 22, 2020 the PDK Framework does not export the constructor for FCEnclosure into JW Lua, so we have to
-- find an existing enclosure to copy. Hopefully we can dispense with this hack at some point,
-- hence it is not in the main routine.
local enclosure = nil
local text_expression_defs = finale.FCTextExpressionDefs()
text_expression_defs:LoadAll()
for text_expression_def in each(text_expression_defs) do
if text_expression_def.UseEnclosure then
enclosure = text_expression_def:CreateEnclosure()
if (nil ~= enclosure) then
break
end
end
end
if (nil == enclosure) then
finenv.UI():AlertNeutral("Please create or modify any text expression to have an enclosure, and then rerun this script.", "Create Enclosure Needed")
return
end
function expression_add_opaque_background()
local current_part = library.get_current_part()
local expression_assignments = finale.FCExpressions()
expression_assignments:LoadAllForRegion(finenv.Region())
for expression_assignment in each(expression_assignments) do
if not expression_assignment:IsShape() and expression_assignment:IsSingleStaffAssigned() then
if expression.is_for_current_part(expression_assignment, current_part) then
local expression_def = finale.FCTextExpressionDef()
if expression_def:Load(expression_assignment.ID) then
if not expression_def.UseEnclosure then -- this prevents us from modifying existing enclosures
enclosure.FixedSize = false
enclosure.HorizontalMargin = 0
enclosure.HorizontalOffset = 0
enclosure.LineWidth = 0
enclosure.Mode = finale.ENCLOSUREMODE_NONE
enclosure.Opaque = true
enclosure.RoundedCornerRadius = 0
enclosure.RoundedCorners = false
enclosure.Shape = finale.ENCLOSURE_RECTANGLE
enclosure.VerticalMargin = 0
enclosure.VerticalOffset = 0
enclosure:SaveAs(expression_def.ItemNo)
expression_def:SetUseEnclosure(true)
else
local my_enclosure = expression_def:CreateEnclosure()
if (nil ~= my_enclosure) then
my_enclosure.Opaque = true
my_enclosure:Save()
end
end
expression_def:Save()
end
end
end
end
end
expression_add_opaque_background()
|
local a=game.Players.LocalPlayer;repeat wait()until a.Character;local b=a.Character;local c=game.Workspace.CurrentCamera;local d=b:WaitForChild('Head')local e=game:GetService('UserInputService')local f=1337;local g=true;local h=Enum.KeyCode.LeftAlt;local function i(a)if a and a.Character and a.Character:FindFirstChild('Head')then if a.Character:FindFirstChild('Humanoid')and a.Character.Humanoid.Health>0 then if not a.Character.Head:FindFirstChild('FuckMyAss')then local j=Instance.new('SphereHandleAdornment')j.AlwaysOnTop=true;j.Name='FuckMyAss'j.Adornee=a.Character.Head;j.ZIndex=1;j.Color3=Color3.new(1,0,0)j.Parent=a.Character.Head end else if a.Character.Head:FindFirstChild('FuckMyAss')then a.Character.head.FuckMyAss:Destroy()end end end end;game:GetService('RunService').RenderStepped:connect(function()local k=nil;local l=nil;for m,n in pairs(game.Players:GetChildren())do if n~=a and(not g or n.TeamColor~=a.TeamColor)and n.Character then spawn(function()i(n)end)if e:IsKeyDown(h)then local o=game.Workspace:FindPartOnRay(Ray.new(d.CFrame.p,(n.Character.Head.CFrame.p-d.CFrame.p).unit*f),b,true,true)local p=(n.Character.Head.CFrame.p-d.CFrame.p).magnitude;if o and n.Character:FindFirstChild(o.Name)and(not l or p<l)then l=p;k=n end end end end;if e:IsKeyDown(h)then if k~=nil and k.Character and k.Character:FindFirstChild('Humanoid')and k.Character.Humanoid.Health>0 then c.CFrame=CFrame.new(c.CFrame.p,k.Character.Head.CFrame.p)end end end) |
---------------------------------------------------
-- Statistics collecting module.
-- Calling the module table is a shortcut to calling the `init` function.
-- @class module
-- @name luacov.runner
local runner = {}
--- LuaCov version in `MAJOR.MINOR.PATCH` format.
runner.version = "0.14.0"
local stats = require("luacov.stats")
local util = require("luacov.util")
runner.defaults = require("luacov.defaults")
local debug = require("debug")
local raw_os_exit = os.exit
local new_anchor = newproxy or function() return {} end -- luacheck: compat
-- Returns an anchor that runs fn when collected.
local function on_exit_wrap(fn)
local anchor = new_anchor()
debug.setmetatable(anchor, {__gc = fn})
return anchor
end
runner.data = {}
runner.paused = true
runner.initialized = false
runner.tick = false
-- Checks if a string matches at least one of patterns.
-- @param patterns array of patterns or nil
-- @param str string to match
-- @param on_empty return value in case of empty pattern array
local function match_any(patterns, str, on_empty)
if not patterns or not patterns[1] then
return on_empty
end
for _, pattern in ipairs(patterns) do
if string.match(str, pattern) then
return true
end
end
return false
end
--------------------------------------------------
-- Uses LuaCov's configuration to check if a file is included for
-- coverage data collection.
-- @param filename name of the file.
-- @return true if file is included, false otherwise.
function runner.file_included(filename)
-- Normalize file names before using patterns.
filename = string.gsub(filename, "\\", "/")
filename = string.gsub(filename, "%.lua$", "")
-- If include list is empty, everything is included by default.
-- If exclude list is empty, nothing is excluded by default.
return match_any(runner.configuration.include, filename, true) and
not match_any(runner.configuration.exclude, filename, false)
end
--------------------------------------------------
-- Adds stats to an existing file stats table.
-- @param old_stats stats to be updated.
-- @param extra_stats another stats table, will be broken during update.
function runner.update_stats(old_stats, extra_stats)
old_stats.max = math.max(old_stats.max, extra_stats.max)
-- Remove string keys so that they do not appear when iterating
-- over 'extra_stats'.
extra_stats.max = nil
extra_stats.max_hits = nil
for line_nr, run_nr in pairs(extra_stats) do
old_stats[line_nr] = (old_stats[line_nr] or 0) + run_nr
old_stats.max_hits = math.max(old_stats.max_hits, old_stats[line_nr])
end
end
-- Adds accumulated stats to existing stats file or writes a new one, then resets data.
function runner.save_stats()
local loaded = stats.load(runner.configuration.statsfile) or {}
for name, file_data in pairs(runner.data) do
if loaded[name] then
runner.update_stats(loaded[name], file_data)
else
loaded[name] = file_data
end
end
stats.save(runner.configuration.statsfile, loaded)
runner.data = {}
end
local cluacov_ok = pcall(require, "cluacov.version")
--------------------------------------------------
-- Debug hook set by LuaCov.
-- Acknowledges that a line is executed, but does nothing
-- if called manually before coverage gathering is started.
-- @param _ event type, should always be "line".
-- @param line_nr line number.
-- @param[opt] level passed to debug.getinfo to get name of processed file,
-- 2 by default. Increase it if this function is called manually
-- from another debug hook.
-- @usage
-- local function custom_hook(_, line)
-- runner.debug_hook(_, line, 3)
-- extra_processing(line)
-- end
-- @function debug_hook
runner.debug_hook = require(cluacov_ok and "cluacov.hook" or "luacov.hook").new(runner)
------------------------------------------------------
-- Runs the reporter specified in configuration.
-- @param[opt] configuration if string, filename of config file (used to call `load_config`).
-- If table then config table (see file `luacov.default.lua` for an example).
-- If `configuration.reporter` is not set, runs the default reporter;
-- otherwise, it must be a module name in 'luacov.reporter' namespace.
-- The module must contain 'report' function, which is called without arguments.
function runner.run_report(configuration)
configuration = runner.load_config(configuration)
local reporter = "luacov.reporter"
if configuration.reporter then
reporter = reporter .. "." .. configuration.reporter
end
require(reporter).report()
end
local on_exit_run_once = false
local function on_exit()
-- Lua >= 5.2 could call __gc when user call os.exit
-- so this method could be called twice
if on_exit_run_once then return end
on_exit_run_once = true
runner.save_stats()
if runner.configuration.runreport then
runner.run_report(runner.configuration)
end
end
local dir_sep = package.config:sub(1, 1)
local wildcard_expansion = "[^/]+"
if not dir_sep:find("[/\\]") then
dir_sep = "/"
end
local function escape_module_punctuation(ch)
if ch == "." then
return "/"
elseif ch == "*" then
return wildcard_expansion
else
return "%" .. ch
end
end
local function reversed_module_name_parts(name)
local parts = {}
for part in name:gmatch("[^%.]+") do
table.insert(parts, 1, part)
end
return parts
end
-- This function is used for sorting module names.
-- More specific names should come first.
-- E.g. rule for 'foo.bar' should override rule for 'foo.*',
-- rule for 'foo.*' should override rule for 'foo.*.*',
-- and rule for 'a.b' should override rule for 'b'.
-- To be more precise, because names become patterns that are matched
-- from the end, the name that has the first (from the end) literal part
-- (and the corresponding part for the other name is not literal)
-- is considered more specific.
local function compare_names(name1, name2)
local parts1 = reversed_module_name_parts(name1)
local parts2 = reversed_module_name_parts(name2)
for i = 1, math.max(#parts1, #parts2) do
if not parts1[i] then return false end
if not parts2[i] then return true end
local is_literal1 = not parts1[i]:find("%*")
local is_literal2 = not parts2[i]:find("%*")
if is_literal1 ~= is_literal2 then
return is_literal1
end
end
-- Names are at the same level of specificness,
-- fall back to lexicographical comparison.
return name1 < name2
end
-- Sets runner.modules using runner.configuration.modules.
-- Produces arrays of module patterns and filenames and sets
-- them as runner.modules.patterns and runner.modules.filenames.
-- Appends these patterns to the include list.
local function acknowledge_modules()
runner.modules = {patterns = {}, filenames = {}}
if not runner.configuration.modules then
return
end
if not runner.configuration.include then
runner.configuration.include = {}
end
local names = {}
for name in pairs(runner.configuration.modules) do
table.insert(names, name)
end
table.sort(names, compare_names)
for _, name in ipairs(names) do
local pattern = name:gsub("%p", escape_module_punctuation) .. "$"
local filename = runner.configuration.modules[name]:gsub("[/\\]", dir_sep)
table.insert(runner.modules.patterns, pattern)
table.insert(runner.configuration.include, pattern)
table.insert(runner.modules.filenames, filename)
if filename:match("init%.lua$") then
pattern = pattern:gsub("$$", "/init$")
table.insert(runner.modules.patterns, pattern)
table.insert(runner.configuration.include, pattern)
table.insert(runner.modules.filenames, filename)
end
end
end
--------------------------------------------------
-- Returns real name for a source file name
-- using `luacov.defaults.modules` option.
-- @param filename name of the file.
function runner.real_name(filename)
local orig_filename = filename
-- Normalize file names before using patterns.
filename = filename:gsub("\\", "/"):gsub("%.lua$", "")
for i, pattern in ipairs(runner.modules.patterns) do
local match = filename:match(pattern)
if match then
local new_filename = runner.modules.filenames[i]
if pattern:find(wildcard_expansion, 1, true) then
-- Given a prefix directory, join it
-- with matched part of source file name.
if not new_filename:match("/$") then
new_filename = new_filename .. "/"
end
new_filename = new_filename .. match .. ".lua"
end
-- Switch slashes back to native.
return (new_filename:gsub("^%.[/\\]", ""):gsub("[/\\]", dir_sep))
end
end
return orig_filename
end
-- Always exclude luacov's own files.
local luacov_excludes = {
"luacov$",
"luacov/hook$",
"luacov/reporter$",
"luacov/reporter/default$",
"luacov/defaults$",
"luacov/runner$",
"luacov/stats$",
"luacov/tick$",
"luacov/util$",
"cluacov/version$"
}
local function is_absolute(path)
if path:sub(1, 1) == dir_sep or path:sub(1, 1) == "/" then
return true
end
if dir_sep == "\\" and path:find("^%a:") then
return true
end
return false
end
local function get_cur_dir()
local pwd_cmd = dir_sep == "\\" and "cd 2>nul" or "pwd 2>/dev/null"
local handler = io.popen(pwd_cmd, "r")
local cur_dir = handler:read()
handler:close()
cur_dir = cur_dir:gsub("\r?\n$", "")
if cur_dir:sub(-1) ~= dir_sep and cur_dir:sub(-1) ~= "/" then
cur_dir = cur_dir .. dir_sep
end
return cur_dir
end
-- Sets configuration. If some options are missing, default values are used instead.
local function set_config(configuration)
runner.configuration = {}
for option, default_value in pairs(runner.defaults) do
runner.configuration[option] = default_value
end
for option, value in pairs(configuration) do
runner.configuration[option] = value
end
-- Program using LuaCov may change directory during its execution.
-- Convert path options to absolute paths to use correct paths anyway.
local cur_dir
for _, option in ipairs({"statsfile", "reportfile"}) do
local path = runner.configuration[option]
if not is_absolute(path) then
cur_dir = cur_dir or get_cur_dir()
runner.configuration[option] = cur_dir .. path
end
end
acknowledge_modules()
for _, patt in ipairs(luacov_excludes) do
table.insert(runner.configuration.exclude, patt)
end
runner.tick = runner.tick or runner.configuration.tick
end
local function load_config_file(name, is_default)
local conf = setmetatable({}, {__index = _G})
local ok, ret, error_msg = util.load_config(name, conf)
if ok then
if type(ret) == "table" then
for key, value in pairs(ret) do
if conf[key] == nil then
conf[key] = value
end
end
end
return conf
end
local error_type = ret
if error_type == "read" and is_default then
return nil
end
io.stderr:write(("Error: couldn't %s config file %s: %s\n"):format(error_type, name, error_msg))
raw_os_exit(1)
end
local default_config_file = ".luacov"
------------------------------------------------------
-- Loads a valid configuration.
-- @param[opt] configuration user provided config (config-table or filename)
-- @return existing configuration if already set, otherwise loads a new
-- config from the provided data or the defaults.
-- When loading a new config, if some options are missing, default values
-- from `luacov.defaults` are used instead.
function runner.load_config(configuration)
if not runner.configuration then
if not configuration then
-- Nothing provided, load from default location if possible.
set_config(load_config_file(default_config_file, true) or runner.defaults)
elseif type(configuration) == "string" then
set_config(load_config_file(configuration))
elseif type(configuration) == "table" then
set_config(configuration)
else
error("Expected filename, config table or nil. Got " .. type(configuration))
end
end
return runner.configuration
end
--------------------------------------------------
-- Pauses saving data collected by LuaCov's runner.
-- Allows other processes to write to the same stats file.
-- Data is still collected during pause.
function runner.pause()
runner.paused = true
end
--------------------------------------------------
-- Resumes saving data collected by LuaCov's runner.
function runner.resume()
runner.paused = false
end
local hook_per_thread
-- Determines whether debug hooks are separate for each thread.
local function has_hook_per_thread()
if hook_per_thread == nil then
local old_hook, old_mask, old_count = debug.gethook()
local noop = function() end
debug.sethook(noop, "l")
local thread_hook = coroutine.wrap(function() return debug.gethook() end)()
hook_per_thread = thread_hook ~= noop
debug.sethook(old_hook, old_mask, old_count)
end
return hook_per_thread
end
--------------------------------------------------
-- Wraps a function, enabling coverage gathering in it explicitly.
-- LuaCov gathers coverage using a debug hook, and patches coroutine
-- library to set it on created threads when under standard Lua, where each
-- coroutine has its own hook. If a coroutine is created using Lua C API
-- or before the monkey-patching, this wrapper should be applied to the
-- main function of the coroutine. Under LuaJIT this function is redundant,
-- as there is only one, global debug hook.
-- @param f a function
-- @return a function that enables coverage gathering and calls the original function.
-- @usage
-- local coro = coroutine.create(runner.with_luacov(func))
function runner.with_luacov(f)
return function(...)
if has_hook_per_thread() then
debug.sethook(runner.debug_hook, "l")
end
return f(...)
end
end
--------------------------------------------------
-- Initializes LuaCov runner to start collecting data.
-- @param[opt] configuration if string, filename of config file (used to call `load_config`).
-- If table then config table (see file `luacov.default.lua` for an example)
function runner.init(configuration)
runner.configuration = runner.load_config(configuration)
-- metatable trick on filehandle won't work if Lua exits through
-- os.exit() hence wrap that with exit code as well
os.exit = function(...) -- luacheck: no global
on_exit()
raw_os_exit(...)
end
debug.sethook(runner.debug_hook, "l")
if has_hook_per_thread() then
-- debug must be set for each coroutine separately
-- hence wrap coroutine function to set the hook there
-- as well
local rawcoroutinecreate = coroutine.create
coroutine.create = function(...) -- luacheck: no global
local co = rawcoroutinecreate(...)
debug.sethook(co, runner.debug_hook, "l")
return co
end
-- Version of assert which handles non-string errors properly.
local function safeassert(ok, ...)
if ok then
return ...
else
error(..., 0)
end
end
coroutine.wrap = function(...) -- luacheck: no global
local co = rawcoroutinecreate(...)
debug.sethook(co, runner.debug_hook, "l")
return function(...)
return safeassert(coroutine.resume(co, ...))
end
end
end
if not runner.tick then
runner.on_exit_trick = on_exit_wrap(on_exit)
end
runner.initialized = true
runner.paused = false
end
--------------------------------------------------
-- Shuts down LuaCov's runner.
-- This should only be called from daemon processes or sandboxes which have
-- disabled os.exit and other hooks that are used to determine shutdown.
function runner.shutdown()
on_exit()
end
-- Gets the sourcefilename from a function.
-- @param func function to lookup.
-- @return sourcefilename or nil when not found.
local function getsourcefile(func)
assert(type(func) == "function")
local d = debug.getinfo(func).source
if d and d:sub(1, 1) == "@" then
return d:sub(2)
end
end
-- Looks for a function inside a table.
-- @param searched set of already checked tables.
local function findfunction(t, searched)
if searched[t] then
return
end
searched[t] = true
for _, v in pairs(t) do
if type(v) == "function" then
return v
elseif type(v) == "table" then
local func = findfunction(v, searched)
if func then return func end
end
end
end
-- Gets source filename from a file name, module name, function or table.
-- @param name string; filename,
-- string; modulename as passed to require(),
-- function; where containing file is looked up,
-- table; module table where containing file is looked up
-- @raise error message if could not find source filename.
-- @return source filename.
local function getfilename(name)
if type(name) == "function" then
local sourcefile = getsourcefile(name)
if not sourcefile then
error("Could not infer source filename")
end
return sourcefile
elseif type(name) == "table" then
local func = findfunction(name, {})
if not func then
error("Could not find a function within " .. tostring(name))
end
return getfilename(func)
else
if type(name) ~= "string" then
error("Bad argument: " .. tostring(name))
end
if util.file_exists(name) then
return name
end
local success, result = pcall(require, name)
if not success then
error("Module/file '" .. name .. "' was not found")
end
if type(result) ~= "table" and type(result) ~= "function" then
error("Module '" .. name .. "' did not return a result to lookup its file name")
end
return getfilename(result)
end
end
-- Escapes a filename.
-- Escapes magic pattern characters, removes .lua extension
-- and replaces dir seps by '/'.
local function escapefilename(name)
return name:gsub("%.lua$", ""):gsub("[%%%^%$%.%(%)%[%]%+%*%-%?]","%%%0"):gsub("\\", "/")
end
local function addfiletolist(name, list)
local f = "^"..escapefilename(getfilename(name)).."$"
table.insert(list, f)
return f
end
local function addtreetolist(name, level, list)
local f = escapefilename(getfilename(name))
if level or f:match("/init$") then
-- chop the last backslash and everything after it
f = f:match("^(.*)/") or f
end
local t = "^"..f.."/" -- the tree behind the file
f = "^"..f.."$" -- the file
table.insert(list, f)
table.insert(list, t)
return f, t
end
-- Returns a pcall result, with the initial 'true' value removed
-- and 'false' replaced with nil.
local function checkresult(ok, ...)
if ok then
return ... -- success, strip 'true' value
else
return nil, ... -- failure; nil + error
end
end
-------------------------------------------------------------------
-- Adds a file to the exclude list (see `luacov.defaults`).
-- If passed a function, then through debuginfo the source filename is collected. In case of a table
-- it will recursively search the table for a function, which is then resolved to a filename through debuginfo.
-- If the parameter is a string, it will first check if a file by that name exists. If it doesn't exist
-- it will call `require(name)` to load a module by that name, and the result of require (function or
-- table expected) is used as described above to get the sourcefile.
-- @param name
-- * string; literal filename,
-- * string; modulename as passed to require(),
-- * function; where containing file is looked up,
-- * table; module table where containing file is looked up
-- @return the pattern as added to the list, or nil + error
function runner.excludefile(name)
return checkresult(pcall(addfiletolist, name, runner.configuration.exclude))
end
-------------------------------------------------------------------
-- Adds a file to the include list (see `luacov.defaults`).
-- @param name see `excludefile`
-- @return the pattern as added to the list, or nil + error
function runner.includefile(name)
return checkresult(pcall(addfiletolist, name, runner.configuration.include))
end
-------------------------------------------------------------------
-- Adds a tree to the exclude list (see `luacov.defaults`).
-- If `name = 'luacov'` and `level = nil` then
-- module 'luacov' (luacov.lua) and the tree 'luacov' (containing `luacov/runner.lua` etc.) is excluded.
-- If `name = 'pl.path'` and `level = true` then
-- module 'pl' (pl.lua) and the tree 'pl' (containing `pl/path.lua` etc.) is excluded.
-- NOTE: in case of an 'init.lua' file, the 'level' parameter will always be set
-- @param name see `excludefile`
-- @param level if truthy then one level up is added, including the tree
-- @return the 2 patterns as added to the list (file and tree), or nil + error
function runner.excludetree(name, level)
return checkresult(pcall(addtreetolist, name, level, runner.configuration.exclude))
end
-------------------------------------------------------------------
-- Adds a tree to the include list (see `luacov.defaults`).
-- @param name see `excludefile`
-- @param level see `includetree`
-- @return the 2 patterns as added to the list (file and tree), or nil + error
function runner.includetree(name, level)
return checkresult(pcall(addtreetolist, name, level, runner.configuration.include))
end
return setmetatable(runner, {__call = function(_, configfile) runner.init(configfile) end})
|
--[[--
text = -- text with the value formatted as a percentage
format.percentage(
value, -- a number, a fraction or nil
{
nil_as = nil_text -- text to be returned for a nil value
digits = digits, -- digits before decimal point (of the percentage value)
precision = precision, -- digits after decimal point (of the percentage value)
decimal_shift = decimal_shift -- divide the value by 10^decimal_shift (setting true uses precision + 2)
}
)
Formats a number or fraction as a percentage.
--]]--
function format.percentage(value, options)
local options = table.new(options)
local f
if value == nil then
return options.nil_as or ""
elseif atom.has_type(value, atom.number) then
f = value
elseif atom.has_type(value, atom.fraction) then
f = value.float
else
error("Value passed to format.percentage(...) is neither a number nor a fraction nor nil.")
end
options.precision = options.precision or 0
if options.decimal_shift == true then
options.decimal_shift = options.precision + 2
end
local suffix = options.hide_unit and "" or " %"
return format.decimal(f * 100, options) .. suffix
end
|
-- maps.lua
-- source https://icyphox.sh/blog/nvim-lua/
local map = vim.api.nvim_set_keymap
-- map the leader key
map('n', '<Space>', '', {})
vim.g.mapleader = ' ' -- 'vim.g' sets global variables
options = { noremap = true }
map('n', '<leader><esc>', ':nohlsearch<cr>', options)
map('n', '<leader>n', ':bnext<cr>', options)
map('n', '<leader>p', ':bprev<cr>', options)
-- LSP (source https://bryankegley.me/posts/nvim-getting-started/)
map('n', 'gd', ':lua vim.lsp.buf.definition()<CR>', options)
map('n', 'gD', ':lua vim.lsp.buf.declaration()<CR>', options)
map('n', 'gi', ':lua vim.lsp.buf.implementation()<CR>', options)
map('n', 'gw', ':lua vim.lsp.buf.document_symbol()<CR>', options)
map('n', 'gW', ':lua vim.lsp.buf.workspace_symbol()<CR>', options)
map('n', 'gr', ':lua vim.lsp.buf.references()<CR>', options)
map('n', 'gt', ':lua vim.lsp.buf.type_definition()<CR>', options)
map('n', 'K', ':lua vim.lsp.buf.hover()<CR>', options)
map('n', '<c-k>', ':lua vim.lsp.buf.signature_help()<CR>', options)
map('n', '<leader>af', ':lua vim.lsp.buf.code_action()<CR>', options)
map('n', '<leader>rn', ':lua vim.lsp.buf.rename()<CR>', options)
-- Fuzzy Finder (source https://bryankegley.me/posts/nvim-getting-started/)
map('n', '<C-p>', ':lua require"telescope.builtin".find_files()<CR>', options)
map('n', '<leader>fs', ':lua require"telescope.builtin".live_grep()<CR>', options)
map('n', '<leader>fh', ':lua require"telescope.builtin".help_tags()<CR>', options)
map('n', '<leader>fb', ':lua require"telescope.builtin".buffers()<CR>', options)
-- Fugitive
-- config of [ThePrimeagen](https://youtu.be/PO6DxfGPQvw?t=98)
-- vim-fugitive
-- https://github.com/tpope/vim-fugitive
--
-- commands:
-- :G git status
-- s - toggle to staged
-- u - toggle to unstaged
-- dv on the file to see changes
-- do diffget: (o => obtain). The change under the cursor is
-- replaced by the content of the other file
-- making them identical.
-- dp diffput: puts changes under the cursor into the other
-- file making them identical (thus removing the diff).
-- ]c Jump to the next diff
-- [c Jump to the previous diff
-- dv on the file to resolve for resolving merge conflicts
-- jump to the '<<<<<<HEAD' line
-- :diffget //2 take the selection of the left side
-- :diffget //3 take the selection of the right side
-- or change manually in the middle
-- end merging of this file by closing the window: <ctrl>+w <ctrl>+o
-- (after that coc restart is neccessary `:CocRestart`)
-- :Gcommit starts commit editor screen, with :wq the commit is done
-- :Gpush push to origin
-- :Git merge <ToBranch> ddd
map('n', '<leader>gj', ':diffget //3<CR>', options)
map('n', '<leader>gf', ':diffget //2<CR>', options)
map('n', '<leader>gs', ':G<CR>', options)
-- map('n', '<C-b>', ':lua require"configs".myNERDTreeToggle()<CR>', options)
--" nnoremap <silent> <C-b> :NERDTreeToggle<CR>
|
addEvent( "mdc.vehiclesearch", true )
addEventHandler( "mdc.vehiclesearch", getRootElement( ),
function( plate, owner, model, stolen, page )
local where = { }
if plate and #plate > 0 then
table.insert( where, "v.plate LIKE '" .. mysql_escape_string( handler, plate ):gsub('%*', '%%') .. "'" )
end
if owner and #owner > 0 then
if owner == "Civilian" then
table.insert( where, "v.owner < 0" )
elseif getTeamFromName( owner ) then
table.insert( where, "v.faction = " .. getElementData( getTeamFromName( owner ), "id" ) )
else
table.insert( where, "c.charactername LIKE '" .. mysql_escape_string( handler, owner ):gsub('_', '\\_'):gsub(' ','\\_'):gsub('?','_'):gsub('%*', '%%') .. "'" ) -- use ?, % and * as single/multiple escape chars, can't use _ as it's used in character names
table.insert( where, "v.faction = -1" )
end
end
if model ~= 0 then
table.insert( where, "v.model = " .. model )
end
if stolen >= 0 then
table.insert( where, "v.stolen = " .. stolen )
end
-- find out how many vehicles we have
local _count = 0
local count = mysql_query( handler, "SELECT COUNT(*) FROM vehicles v LEFT JOIN characters c ON v.owner = c.id WHERE " .. table.concat( where, " AND " ) )
if count then
_count = tonumber( mysql_result( count, 1, 1 ) ) or 0
mysql_free_result( count )
end
-- find the actual vehicles
local result = mysql_query( handler, "SELECT v.model, v.plate, c.charactername, v.stolen, v.faction FROM vehicles v LEFT JOIN characters c ON v.owner = c.id WHERE " .. table.concat( where, " AND " ) .. " ORDER BY plate LIMIT " .. ( ( page or 0 ) * 25 ) .. ", 25" )
if result then
local vehicles = {}
for result, row in mysql_rows( result ) do
table.insert( vehicles, { tonumber( row[1] ), row[2], row[3] == mysql_null( ) and "Civilian" or row[3], tonumber( row[4] ) == 1, tonumber( row[5] ) } )
end
mysql_free_result( result )
triggerClientEvent( source, "mdc.vehiclesearchresult", source, { vehicles, plate, owner, model, stolen, page or 0, _count } )
else
outputDebugString( mysql_error( handler ) )
outputChatBox( "MDC Vehicle Search failed - Report on Mantis.", source, 255, 0, 0 )
end
end
) |
return {
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 7000,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 7330,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 7660,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 7990,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 8320,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 8650,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 8980,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 9310,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 9640,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
{
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 10000,
target = "TargetSelf",
skill_id = 105120
}
}
}
},
init_effect = "",
name = "梦见好梦的「WAVE」",
time = 0,
color = "yellow",
picture = "",
desc = "",
stack = 1,
id = 105120,
icon = 105120,
last_effect = "",
effect_list = {
{
type = "BattleBuffCastSkill",
trigger = {
"onAllInStrikeSteady"
},
arg_list = {
rant = 7000,
target = "TargetSelf",
skill_id = 105120
}
}
}
}
|
local spawnedVehicles = {}
function OpenVehicleSpawnerMenuSociety(authorizedVehicles, type, playerData, options)
local insideShop = options.insideShop or Config.InsideShop
local playerCoords = GetEntityCoords(PlayerPedId())
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'vehicle', {
title = 'Firemní garáž',
align = 'right',
elements = {
{label = _U('garage_storeditem'), action = 'garage'},
{label = _U('garage_storeitem'), action = 'store_garage'},
{label = _U('garage_buyitem'), action = 'buy_vehicle'}
}}, function(data, menu)
if data.current.action == 'buy_vehicle' then
local shopElements = {}
local shopCoords = insideShop
local authorizedVehicles = authorizedVehicles[playerData.job.grade_name]
if authorizedVehicles then
if #authorizedVehicles > 0 then
for k,vehicle in ipairs(authorizedVehicles) do
if IsModelInCdimage(vehicle.model) then
local vehicleLabel = GetLabelText(GetDisplayNameFromVehicleModel(vehicle.model))
local label = ('%s - <span style="color:green;">%s</span>'):format(vehicleLabel, _U('shop_item', ESX.Math.GroupDigits(vehicle.price)))
if vehicle.price == -1 then
label = ('%s - <span style="color:green;">zdarma</span>'):format(vehicleLabel, _U('shop_item', ESX.Math.GroupDigits(vehicle.price)))
end
table.insert(shopElements, {
label = label,
name = vehicleLabel,
model = vehicle.model,
price = vehicle.price,
props = vehicle.props,
type = type
})
end
end
if #shopElements > 0 then
OpenShopMenu(shopElements, playerCoords, shopCoords)
else
ESX.ShowNotification(_U('garage_notauthorized'))
end
else
ESX.ShowNotification(_U('garage_notauthorized'))
end
else
ESX.ShowNotification(_U('garage_notauthorized'))
end
elseif data.current.action == 'garage' then
local garage = {}
ESX.TriggerServerCallback('esx_vehicleshop:retrieveJobVehicles', function(jobVehicles)
if #jobVehicles > 0 then
local allVehicleProps = {}
for k,v in ipairs(jobVehicles) do
local props = json.decode(v.vehicle)
if IsModelInCdimage(props.model) then
local vehicleName = GetLabelText(GetDisplayNameFromVehicleModel(props.model))
local label = ('%s - <span style="color:darkgoldenrod;">%s</span>: '):format(vehicleName, props.plate)
if v.stored then
label = label .. ('<span style="color:green;">%s</span>'):format(_U('garage_stored'))
else
label = label .. ('<span style="color:darkred;">%s</span>'):format(_U('garage_notstored'))
end
table.insert(garage, {
label = label,
stored = v.stored,
model = props.model,
plate = props.plate
})
allVehicleProps[props.plate] = props
end
end
if #garage > 0 then
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'vehicle_garage', {
title = _U('garage_title'),
align = 'right',
elements = garage
}, function(data2, menu2)
if data2.current.stored then
local foundSpawn, spawnPoint = GetAvailableVehicleSpawnPoint(station, part, partNum)
if foundSpawn then
menu2.close()
ESX.Game.SpawnVehicle(data2.current.model, spawnPoint.coords, spawnPoint.heading, function(vehicle)
local vehicleProps = allVehicleProps[data2.current.plate]
ESX.Game.SetVehicleProperties(vehicle, vehicleProps)
TriggerServerEvent('esx_vehicleshop:setJobVehicleState', data2.current.plate, false)
ESX.ShowNotification(_U('garage_released'))
end)
end
else
ESX.ShowNotification(_U('garage_notavailable'))
end
end, function(data2, menu2)
menu2.close()
end)
else
ESX.ShowNotification(_U('garage_empty'))
end
else
ESX.ShowNotification(_U('garage_empty'))
end
end, type)
elseif data.current.action == 'store_garage' then
StoreNearbyVehicle(playerCoords)
end
end, function(data, menu)
menu.close()
end)
end
function StoreNearbyVehicle(playerCoords)
local vehicles, vehiclePlates = ESX.Game.GetVehiclesInArea(playerCoords, 30.0), {}
if #vehicles > 0 then
for k,v in ipairs(vehicles) do
-- Make sure the vehicle we're saving is empty, or else it wont be deleted
if GetVehicleNumberOfPassengers(v) == 0 and IsVehicleSeatFree(v, -1) then
table.insert(vehiclePlates, {
vehicle = v,
plate = ESX.Math.Trim(GetVehicleNumberPlateText(v))
})
end
end
else
ESX.ShowNotification(_U('garage_store_nearby'))
return
end
ESX.TriggerServerCallback('esx_vigneronjob:storeNearbyVehicle', function(storeSuccess, foundNum)
if storeSuccess then
local vehicleId = vehiclePlates[foundNum]
local attempts = 0
ESX.Game.DeleteVehicle(vehicleId.vehicle)
IsBusy = true
Citizen.CreateThread(function()
BeginTextCommandBusyspinnerOn('STRING')
AddTextComponentSubstringPlayerName(_U('garage_storing'))
EndTextCommandBusyspinnerOn(4)
while IsBusy do
Citizen.Wait(100)
end
BusyspinnerOff()
end)
-- Workaround for vehicle not deleting when other players are near it.
while DoesEntityExist(vehicleId.vehicle) do
Citizen.Wait(500)
attempts = attempts + 1
-- Give up
if attempts > 30 then
break
end
vehicles = ESX.Game.GetVehiclesInArea(playerCoords, 30.0)
if #vehicles > 0 then
for k,v in ipairs(vehicles) do
if ESX.Math.Trim(GetVehicleNumberPlateText(v)) == vehicleId.plate then
ESX.Game.DeleteVehicle(v)
break
end
end
end
end
IsBusy = false
ESX.ShowNotification(_U('garage_has_stored'))
else
ESX.ShowNotification(_U('garage_has_notstored'))
end
end, vehiclePlates)
end
function GetAvailableVehicleSpawnPoint(station, part, partNum)
local spawnPoints = Config.SpawnPoints
local found, foundSpawnPoint = false, nil
for i=1, #spawnPoints, 1 do
if ESX.Game.IsSpawnPointClear(spawnPoints[i].coords, spawnPoints[i].radius) then
found, foundSpawnPoint = true, spawnPoints[i]
break
end
end
if found then
return true, foundSpawnPoint
else
ESX.ShowNotification(_U('vehicle_blocked'))
return false
end
end
function OpenShopMenu(elements, restoreCoords, shopCoords)
local playerPed = PlayerPedId()
isInShopMenu = true
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'vehicle_shop', {
title = _U('vehicleshop_title'),
align = 'right',
elements = elements
}, function(data, menu)
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'vehicle_shop_confirm', {
title = _U('vehicleshop_confirm', data.current.name, data.current.price),
align = 'right',
elements = {
{label = _U('confirm_no'), value = 'no'},
{label = _U('confirm_yes'), value = 'yes'}
}}, function(data2, menu2)
if data2.current.value == 'yes' then
local newPlate = exports['esx_vehicleshop']:GeneratePlate()
local vehicle = GetVehiclePedIsIn(playerPed, false)
local props = ESX.Game.GetVehicleProperties(vehicle)
props.plate = newPlate
ESX.TriggerServerCallback('esx_vigneronjob:buyJobVehicle', function (bought)
if bought then
ESX.ShowNotification(_U('vehicleshop_bought', data.current.name, ESX.Math.GroupDigits(data.current.price)))
isInShopMenu = false
ESX.UI.Menu.CloseAll()
DeleteSpawnedVehicles()
FreezeEntityPosition(playerPed, false)
SetEntityVisible(playerPed, true)
ESX.Game.Teleport(playerPed, restoreCoords)
else
ESX.ShowNotification(_U('vehicleshop_money'))
menu2.close()
end
end, props, data.current.type)
else
menu2.close()
end
end, function(data2, menu2)
menu2.close()
end)
end, function(data, menu)
isInShopMenu = false
ESX.UI.Menu.CloseAll()
DeleteSpawnedVehicles()
FreezeEntityPosition(playerPed, false)
SetEntityVisible(playerPed, true)
ESX.Game.Teleport(playerPed, restoreCoords)
end, function(data, menu)
DeleteSpawnedVehicles()
WaitForVehicleToLoad(data.current.model)
ESX.Game.SpawnLocalVehicle(data.current.model, shopCoords, 0.0, function(vehicle)
table.insert(spawnedVehicles, vehicle)
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
FreezeEntityPosition(vehicle, true)
SetModelAsNoLongerNeeded(data.current.model)
if data.current.props then
ESX.Game.SetVehicleProperties(vehicle, data.current.props)
end
end)
end)
WaitForVehicleToLoad(elements[1].model)
ESX.Game.SpawnLocalVehicle(elements[1].model, shopCoords, 0.0, function(vehicle)
table.insert(spawnedVehicles, vehicle)
TaskWarpPedIntoVehicle(playerPed, vehicle, -1)
FreezeEntityPosition(vehicle, true)
SetModelAsNoLongerNeeded(elements[1].model)
if elements[1].props then
ESX.Game.SetVehicleProperties(vehicle, elements[1].props)
end
end)
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if isInShopMenu then
DisableControlAction(0, 75, true) -- Disable exit vehicle
DisableControlAction(27, 75, true) -- Disable exit vehicle
else
Citizen.Wait(500)
end
end
end)
function DeleteSpawnedVehicles()
while #spawnedVehicles > 0 do
local vehicle = spawnedVehicles[1]
ESX.Game.DeleteVehicle(vehicle)
table.remove(spawnedVehicles, 1)
end
end
function WaitForVehicleToLoad(modelHash)
modelHash = (type(modelHash) == 'number' and modelHash or GetHashKey(modelHash))
if not HasModelLoaded(modelHash) then
RequestModel(modelHash)
BeginTextCommandBusyspinnerOn('STRING')
AddTextComponentSubstringPlayerName(_U('vehicleshop_awaiting_model'))
EndTextCommandBusyspinnerOn(4)
while not HasModelLoaded(modelHash) do
Citizen.Wait(0)
DisableAllControlActions(0)
end
BusyspinnerOff()
end
end
|
--- Turbo.lua Mustache test
--
-- Copyright 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local turbo = require "turbo"
describe("turbo.web.Mustache Namespace", function()
it("Basic usage", function()
local simple_template = [[
<body>
<h1>
{{heading }}
</h1>
{{!
Some comment section that
even spans across multiple lines,
that I just have to have to explain my flawless code.
}}
<h2>
{{{desc}}} {{! No escape with triple mustaches allow HTML tags! }}
{{&desc}} {{! No escape can also be accomplished by & char }}
</h2>
<p>I am {{age}} years old. What would {{you}} like to buy in my shop?</p>
{{ #items }} {{! I like spaces alot! }}
Item: {{item}}
{{#types}}
{{! Only print items if available.}}
Type available: {{type}}
{{/types}}
{{^types}} Only one type available.
{{! Apparently only one type is available because types is not set,
determined by the hat char ^}}
{{/types}}
{{/items}}
{{^items}}
No items available!
{{/items}}
{{{ >disclaimer }}} {{!! I like partials alot too. }}
</body>]]
-- We basically rely on the fact that compile will throw error
-- if the compiling is erroring on valid input.
local tmpl = turbo.web.Mustache.compile(simple_template)
local compiled_tmpl = turbo.web.Mustache.render(tmpl, {
heading="My website!",
desc="<b>Big important website</b>",
age=27,
items={
{item="Bread",
types={
{type="light"},
{type="fatty"}
}
},
{item="Milk"},
{item="Sugar"}
}
}, {disclaimer=[[Disclaimer for {{heading}}.]]})
end)
it("Support no whitespace in partial operator.", function()
assert.equal(turbo.web.Mustache.render(
"{{>disclaimer}}",
{heading="My website"},
{disclaimer=[[Disclaimer for {{{heading}}}.]]}), "Disclaimer for My website.")
end)
it("Support whitespace in partial operator.", function()
assert.equal(turbo.web.Mustache.render(
"{{> disclaimer}}{{! Whitespace between operator and name.}}",
{heading="My website"},
{disclaimer=[[Disclaimer for {{{heading}}}.]]}), "Disclaimer for My website.")
end)
it("Support whitespace before middle and after partial operator.", function()
assert.equal(turbo.web.Mustache.render(
"{{ > disclaimer }}",
{heading="My website"},
{disclaimer=[[Disclaimer for {{{heading}}}.]]}), "Disclaimer for My website.")
end)
it("Support whitespace before middle after key operator.", function()
assert.equal(turbo.web.Mustache.render(
"{{{ whitespacer }}}",
{whitespacer="My website"}), "My website")
end)
it("Support whitespace before middle after section operator.", function()
assert.equal(turbo.web.Mustache.render(
"{{ #test }}Klein{{ /test }}",
{test="My website"}), "Klein")
end)
end) |
meta.name = "More Frog Types"
meta.description = [[More frog types have been added in this mod.
There is currently just the Anubian frog, which shoots a normal Anubis shot upon death.]]
meta.version = "0.1"
meta.author = "C_ffeeStain"
local anubian_frog_texture = get_texture_definition(TEXTURE.DATA_TEXTURES_MONSTERS03_0)
anubian_frog_texture.texture_path = "anubian_frog.png"
local anubian_frog_texture_id = define_texture(anubian_frog_texture)
local all_anubian_frogs = {}
define_tile_code("anubian_frog")
set_pre_tile_code_callback(function(x, y, layer)
local uid = spawn_entity(ENT_TYPE.MONS_FROG, x, y, layer, 0, 0)
set_post_statemachine(uid, function (movable)
movable:set_texture(anubian_frog_texture_id)
all_anubian_frogs[#all_anubian_frogs+1] = {uid = movable.uid, x = x, y = y, layer = layer}
end)
return true
end, "anubian_frog")
set_callback(function()
for i, v in ipairs(all_anubian_frogs) do
if not get_entity(v.uid) then
spawn(ENT_TYPE.ITEM_SCEPTER_ANUBISSHOT, all_anubian_frogs[i].x, all_anubian_frogs[i].y, all_anubian_frogs[i].layer, 0, 0)
all_anubian_frogs[i] = nil
else
local frog_x, frog_y, frog_l = get_position(v.uid)
all_anubian_frogs[i].x, all_anubian_frogs[i].y, all_anubian_frogs.layer = frog_x, frog_y, frog_l
end
end
end, ON.FRAME) |
------------------------------------------------------------------------------
-- ImageRGB class
------------------------------------------------------------------------------
local ctrl = {
nick = "imagergb",
parent = iup.WIDGET,
creation = "nns", -- fake definition
funcname = "ImageRGB",
callback = {},
createfunc = [[
static int ImageRGB(lua_State *L)
{
int w = luaL_checkint(L, 1);
int h = luaL_checkint(L, 2);
unsigned char *pixels = iuplua_checkuchar_array(L, 3, w*h*3);
Ihandle *ih = IupImageRGB(w, h, pixels);
iuplua_plugstate(L, ih);
iuplua_pushihandle_raw(L, ih);
free(pixels);
return 1;
}
]]
}
function ctrl.createElement(class, param)
return iup.ImageRGB(param.width, param.height, param.pixels)
end
iup.RegisterWidget(ctrl)
iup.SetClass(ctrl, "iup widget")
|
local cwd = (...):gsub('%.init$', '') .. "."
return {
math = require(cwd .. "math"),
graphics = require(cwd .. "graphics")
}
|
--[[
name: Connect Four
author: Charlie Cheever <ccheever@expo.io>
description: An implementation of the classic game Connect Four
]]
local sync = require "https://raw.githubusercontent.com/expo/sync.lua/master/sync.lua"
local Controller = sync.registerType("Controller")
local server, client
function love.draw()
if client and client.controller then
for _, ent in pairs(client.all) do
if ent.__typeName == "Player" then
ent:draw(ent.__id == client.controller.playerId)
elseif ent.draw then
ent:draw()
end
end
else
love.graphics.print("not connected", 20, 20)
end
end
local function keyEvent(key)
if client and client.controller then
if key == "up" or key == "down" or key == "left" or key == "right" then
client.controller:setWalkState(
love.keyboard.isDown("up"),
love.keyboard.isDown("down"),
love.keyboard.isDown("left"),
love.keyboard.isDown("right")
)
end
end
end
function love.keypressed(key)
if key == "1" then
server = sync.newServer {address = "*:22122", controllerTypeName = "Controller"}
end
if key == "2" then
client = sync.newClient {address = "127.0.0.1:22122"}
end
keyEvent(key)
end
function love.keyreleased(key)
keyEvent(key)
end
function love.update(dt)
if server then
for _, ent in pairs(server.all) do
if ent.update then
ent:update(dt)
end
end
end
if server then
server:process()
end
if client then
client:process()
end
end
function Controller:didSpawn()
print("a client connected")
end
function Controller:willDespawn()
print("a client disconnected")
end
local Player = sync.registerType("Player")
function Player:didSpawn()
self.vx, self.vy = 0, 0
self.x, self.y = love.graphics.getWidth() * math.random(), love.graphics.getHeight() * math.random()
self.r, self.g, self.b = 0.2 + 0.8 * math.random(), 0.2 + 0.8 * math.random(), 0.2 + 0.8 * math.random()
end
function Player:draw(isOwn)
love.graphics.push("all")
love.graphics.setColor(self.r, self.g, self.b)
love.graphics.ellipse("fill", self.x, self.y, 40, 40)
if isOwn then
love.graphics.setColor(1, 1, 1)
love.graphics.setLineWidth(5)
love.graphics.ellipse("line", self.x, self.y, 48, 48)
end
love.graphics.pop()
end
-- function Player:draw()
-- love.graphics.push("all")
-- love.graphics.setColor(self.r, self.g, self.b)
-- love.graphics.ellipse("fill", self.x, self.y, 40, 40)
-- love.graphics.pop()
-- end
function Controller:didSpawn()
self.playerId = self.__mgr:spawn("Player")
end
function Controller:willDespawn()
self.__mgr:despawn(self.playerId)
end
function Controller:setWalkState(up, down, left, right)
self.__mgr:byId(self.playerId):setWalkState(up, down, left, right)
end
function Player:setWalkState(up, down, left, right)
self.vx, self.vy = 0, 0
if up then
self.vy = self.vy - 240
end
if down then
self.vy = self.vy + 240
end
if left then
self.vx = self.vx - 240
end
if right then
self.vx = self.vx + 240
end
end
function Player:update(dt)
self.x = self.x + self.vx * dt
self.y = self.y + self.vy * dt
self.__mgr:sync(self)
end
|
-- https://modit.store
-- ModFreakz
SqlFetch = function(statement,payload,callback)
exports['ghmattimysql']:execute(statement,payload,callback)
end
SqlExecute = function(statement,payload,callback)
exports['ghmattimysql']:execute(statement,payload,callback)
end |
-----------------------------------
-- Area: Kazham
-- NPC: Kakapp
-- Standard Info NPC
-----------------------------------
function onTrade(player,npc,trade)
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(905,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(1157,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(904,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 7 or failed == 8 then
if goodtrade then
player:startEvent(226);
elseif badtrade then
player:startEvent(236);
end
end
end
end;
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, tpz.quest.id.outlands.THE_OPO_OPO_AND_I);
local progress = player:getCharVar("OPO_OPO_PROGRESS");
local failed = player:getCharVar("OPO_OPO_FAILED");
local retry = player:getCharVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(204);
elseif (progress == 7 or failed == 8) then
player:startEvent(213); -- asking for wyvern skull
elseif (progress >= 8 or failed >= 9) then
player:startEvent(249); -- happy with wyvern skull
end
else
player:startEvent(204);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 226) then -- correct trade, onto next opo
if player:getCharVar("OPO_OPO_PROGRESS") == 7 then
player:tradeComplete();
player:setCharVar("OPO_OPO_PROGRESS",8);
player:setCharVar("OPO_OPO_FAILED",0);
else
player:setCharVar("OPO_OPO_FAILED",9);
end
elseif (csid == 236) then -- wrong trade, restart at first opo
player:setCharVar("OPO_OPO_FAILED",1);
player:setCharVar("OPO_OPO_RETRY",8);
end
end;
|
local source = {}
local cmp = require("cmp")
local luv = vim.loop
local utf8 = require("cmp_dictionary.lib.utf8")
local caches = require("cmp_dictionary.caches")
local config = require("cmp_dictionary.config")
local util = require("cmp_dictionary.util")
function source.new()
return setmetatable({}, { __index = source })
end
function source:is_available()
return config.ready
end
function source.get_keyword_pattern()
return [[\k\+]]
end
local candidate_cache = {
req = "",
items = {},
}
local function is_capital(str)
return str:find("^%u") and true or false
end
local function to_lower_first(str)
local l = str:gsub("^.", string.lower)
return l
end
local function to_upper_first(str)
local u = str:gsub("^.", string.upper)
return u
end
local function get_from_caches(req)
local items = {}
local ok, offset, codepoint
ok, offset = pcall(utf8.offset, req, -1, #req)
if not ok then
return items
end
ok, codepoint = pcall(utf8.codepoint, req, offset)
if not ok then
return items
end
local req_next = req:sub(1, offset - 1) .. utf8.char(codepoint + 1)
for _, cache in pairs(caches.get()) do
local start = util.binary_search(cache.item, req, function(vector, index, key)
return vector[index].label >= key
end)
local last = util.binary_search(cache.item, req_next, function(vector, index, key)
return vector[index].label >= key
end) - 1
if start > 0 and last > 0 and start <= last then
for i = start, last do
local item = cache.item[i]
item.label = item._label or item.label
table.insert(items, item)
end
end
end
return items
end
function source.get_candidate(req, isIncomplete)
if candidate_cache.req == req then
return { items = candidate_cache.items, isIncomplete = isIncomplete }
end
local items = get_from_caches(req)
if config.get("first_case_insensitive") then
if is_capital(req) then
for _, item in ipairs(get_from_caches(to_lower_first(req))) do
item._label = item._label or item.label
item.label = to_upper_first(item._label)
table.insert(items, item)
end
else
for _, item in ipairs(get_from_caches(to_upper_first(req))) do
item._label = item._label or item.label
item.label = to_lower_first(item._label)
table.insert(items, item)
end
end
end
candidate_cache.req = req
candidate_cache.items = items
return { items = items, isIncomplete = isIncomplete }
end
function source:complete(request, callback)
if caches.is_just_updated() then
candidate_cache = {}
end
local exact = config.get("exact")
local req = request.context.cursor_before_line:sub(request.offset, request.offset + exact - 1)
local isIncomplete = #req < exact
callback(source.get_candidate(req, isIncomplete))
end
local document_cache = require("cmp_dictionary.lfu").init(100)
local function get_command(word)
local command = config.get("document_command")
local args
if type(command) == "table" then
-- copy
args = {}
for i, v in ipairs(command) do
args[i] = v
end
elseif type(command) == "string" then
args = vim.split(command, " ")
end
local cmd = table.remove(args, 1)
for i, arg in ipairs(args) do
if arg:find("%s", 1, true) then
args[i] = arg:format(word)
end
end
return cmd, args
end
local function pipes()
local stdin = luv.new_pipe(false)
local stdout = luv.new_pipe(false)
local stderr = luv.new_pipe(false)
return { stdin, stdout, stderr }
end
local function get_document(completion_item, callback)
local word = completion_item.label
local cmd, args = get_command(word)
if not cmd then
callback(completion_item)
return
end
local stdio = pipes()
local spawn_options = {
args = args,
stdio = stdio,
}
local handle
handle = luv.spawn(cmd, spawn_options, function()
stdio[1]:close()
stdio[2]:close()
stdio[3]:close()
handle:close()
end)
if not handle then
callback(completion_item)
return
end
luv.read_start(stdio[2], function(err, result)
assert(not err, err)
result = result or ""
document_cache:set(word, result)
completion_item.documentation = {
kind = cmp.lsp.MarkupKind.PlainText,
value = result,
}
callback(completion_item)
end)
end
function source:resolve(completion_item, callback)
if config.get("document") then
local cached = document_cache:get(completion_item.label)
if cached then
completion_item.documentation = {
kind = cmp.lsp.MarkupKind.PlainText,
value = cached,
}
callback(completion_item)
else
get_document(completion_item, callback)
end
else
callback(completion_item)
end
end
function source.setup(opt)
config.setup(opt)
end
function source.update()
caches.update()
end
return source
|
-- vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab:
use "tpope/vim-commentary"
|
-----------------------------------------
-- Spell: Queasyshroom
-- Additional effect: Poison. Duration of effect varies with TP
-- Spell cost: 20 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Piercing)
-- Blue Magic Points: 2
-- Stat Bonus: HP-5, MP+5
-- Level: 8
-- Casting Time: 2 seconds
-- Recast Time: 15 seconds
-- Skillchain Element(s): Dark (can open Transfixion or Detonation can close Compression or Gravitation)
-- Combos: None
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL
params.damageType = tpz.damageType.PIERCING
params.scattr = SC_DARK
params.numhits = 1
params.multiplier = 1.25
params.tp150 = 1.25
params.tp300 = 1.25
params.azuretp = 1.25
params.duppercap = 15
params.str_wsc = 0.0
params.dex_wsc = 0.0
params.vit_wsc = 0.0
params.agi_wsc = 0.0
params.int_wsc = 0.20
params.mnd_wsc = 0.0
params.chr_wsc = 0.0
local damage = BluePhysicalSpell(caster, target, spell, params)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
local chance = math.random()
if (damage > 0 and chance > 10) then
target:delStatusEffect(tpz.effect.POISON)
target:addStatusEffect(tpz.effect.POISON, 3, 0, getBlueEffectDuration(caster, resist, tpz.effect.POISON))
end
return damage
end
|
SKIN = {}
SKIN.PrintName = "PERP3"
SKIN.Author = ""
SKIN.DermaVersion = 1
SKIN.colOutline = Color(0, 0, 0, 250)
SKIN.control_color = Color( 100, 100, 100, 200 )
SKIN.control_color_highlight = Color( 130, 130, 130, 200 )
SKIN.control_color_active = Color( 90, 130, 230, 200 )
SKIN.control_color_bright = Color( 255, 200, 100, 200 )
SKIN.control_color_dark = Color( 80, 80, 80, 200 )
SKIN.colButtonBorderHighlight = Color( 255, 255, 255, 0 )
SKIN.colButtonBorderShadow = Color( 0, 0, 0, 0 )
SKIN.colTabBG = Color(0, 0, 0, 255)
SKIN.colPropertySheet = Color(100, 100, 100, 255)
SKIN.colTab = Color(150, 150, 150, 255)
SKIN.colTabInactive = SKIN.colPropertySheet
SKIN.colTabText = Color(255, 255, 255, 150)
SKIN.colTabTextInactive = Color(205, 205, 205, 100)
SKIN.fontButton = "DefaultSmall"
SKIN.fontTab = "DefaultSmall"
SKIN.fontFrame = "DebugFixed"
SKIN.fontForm = "DefaultSmall"
SKIN.fontLabel = "DefaultSmall"
SKIN.fontLargeLabel = "DefaultLarge"
function cutLength ( str, pW, font )
surface.SetFont(font);
local sW = pW - 40;
for i = 1, string.len(str) do
local sStr = string.sub(str, 1, i);
local w, h = surface.GetTextSize(sStr);
if (w > pW || (w > sW && string.sub(str, i, i) == " ")) then
local cutRet = cutLength(string.sub(str, i + 1), pW, font);
local returnTable = {sStr};
for k, v in pairs(cutRet) do
table.insert(returnTable, v);
end
return returnTable;
end
end
return {str};
end
function SKIN:PaintTab( panel )
surface.SetDrawColor(SKIN.colTabBG.r, SKIN.colTabBG.g, SKIN.colTabBG.b, SKIN.colTabBG.a);
surface.DrawRect(0, 0, panel:GetWide(), panel:GetTall() + 8);
if (panel:GetPropertySheet():GetActiveTab() == panel) then
surface.SetDrawColor(SKIN.colTab.r, SKIN.colTab.g, SKIN.colTab.b, SKIN.colTab.a);
surface.DrawRect(1, 1, panel:GetWide() - 2, panel:GetTall() + 8)
else
surface.SetDrawColor(SKIN.colTabInactive.r, SKIN.colTabInactive.g, SKIN.colTabInactive.b, SKIN.colTabInactive.a);
surface.DrawRect(1, 1, panel:GetWide() - 2, panel:GetTall() + 8)
end
end
function SKIN:PaintPropertySheet( panel )
local ActiveTab = panel:GetActiveTab()
local Offset = 0
if ( ActiveTab ) then Offset = ActiveTab:GetTall() end
// This adds a little shadow to the right which helps define the tab shape..
surface.SetDrawColor(SKIN.colTabBG.r, SKIN.colTabBG.g, SKIN.colTabBG.b, SKIN.colTabBG.a);
surface.DrawRect(0, Offset, panel:GetWide(), panel:GetTall() - Offset);
surface.SetDrawColor(SKIN.colPropertySheet.r, SKIN.colPropertySheet.g, SKIN.colPropertySheet.b, SKIN.colPropertySheet.a);
surface.DrawRect(1, 1 + Offset, panel:GetWide() - 2, panel:GetTall() - 2 - Offset);
end
function SKIN:SchemeForm ( panel )
panel.Label:SetFont(SKIN.fontForm)
panel.Label:SetTextColor(Color( 255, 255, 255, 255 ));
end
function SKIN:SchemeLabel( panel )
local col = nil
if ( panel.Hovered && panel:GetTextColorHovered() ) then
col = panel:GetTextColorHovered()
else
col = panel:GetTextColor()
end
if (col) then
panel:SetFGColor( col.r, col.g, col.b, col.a )
else
panel:SetFGColor( 200, 200, 200, 255 )
end
if (panel.BrokeAlready && panel.BrokeAlready == panel:GetValue()) then return; end
local ourFont = SKIN.fontLabel;
local isLarge = string.sub(panel:GetValue(), 1, 1) == ":";
if (isLarge) then
ourFont = SKIN.fontLargeLabel;
panel:SetText(string.sub(panel:GetValue(), 2));
end
panel.BrokeAlready = panel:GetValue();
panel:SetFont(ourFont);
end
function SKIN:DrawSquaredBox ( x, y, w, h, color )
surface.SetDrawColor(color);
surface.DrawRect(x, y, w, h);
surface.SetDrawColor(self.colOutline);
surface.DrawOutlinedRect(x, y, w, h);
end
function SKIN:PaintFrame ( panel, skipTop )
local color = self.bg_color;
self:DrawSquaredBox(0, 0, panel:GetWide(), panel:GetTall(), color)
if (!skipTop) then
surface.SetDrawColor(0, 0, 0, 75);
surface.DrawRect(0, 0, panel:GetWide(), 21);
surface.SetDrawColor(self.colOutline);
surface.DrawRect(0, 21, panel:GetWide(), 1);
end
end
function SKIN:PaintPanelList ( panel )
if (panel.m_bBackground) then
draw.RoundedBox(0, 0, 0, panel:GetWide(), panel:GetTall(), self.bg_color_dark);
end
end
derma.DefineSkin("ugperp", "ugperp", SKIN);
PERP2_SKIN = SKIN; |
scenes.title = Level.create()
titlefont = love.graphics.newFont("fonts/pixelfont.ttf", 6)
titlefont:setFilter( "nearest", "nearest")
love.graphics.setFont(titlefont)
function scenes.title:load()
--create world boundaries
drawWalls()
--Load backround Sprites
titleimg = GameObject.create()
titleimg.name = "titleimg"
titleimg.sprite = love.graphics.newImage("sprites/titleimg.png")
titleimg.sprite:setFilter( "nearest", "nearest")
titleimg.position.x = 0
titleimg.position.y = 32
table.insert(gs.entities, titleimg)
buttonx = GameObject.create()
buttonx.name = "buttonx"
buttonx.sprite = love.graphics.newImage("sprites/button_x.png")
buttonx.sprite:setFilter( "nearest", "nearest")
buttonx.position.x = 88
buttonx.position.y = 90
table.insert(gs.entities, buttonx)
buttonz = GameObject.create()
buttonz.name = "buttonz"
buttonz.sprite = love.graphics.newImage("sprites/button_z.png")
buttonz.sprite:setFilter( "nearest", "nearest")
buttonz.position.x = 38
buttonz.position.y = 90
table.insert(gs.entities, buttonz)
end
function scenes.title:update()
if love.keyboard.isDown('z','x') then
unloadScene()
loadScene("intro")
end
end
function scenes.title:draw()
love.graphics.setColor(15, 56, 15)
love.graphics.setFont(scorefont)
love.graphics.print("or", 70, 94)
love.graphics.setColor(255,255,255)
end |
-- Requirement summary:
-- [PTU] Trigger: kilometers
--
-- Description:
-- Describe correctly the CASE of requirement that is covered, conditions that will be used.
-- 1. Used preconditions: The odometer value was "1234" when previous PTU was successfully applied.
-- Policies DataBase contains "exchange_after_x_kilometers" = 1000
-- 2. Performed steps:
-- SDL->HMI: Vehicleinfo.SubscribeVehicleData ("odometer")
-- HMI->SDL: Vehicleinfo.SubscribeVehicleData (SUCCESS)
-- user sets odometer to 2200
-- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2200")
-- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers"
-- user sets odometer to 2250
-- HMI->SDL: Vehicleinfo.OnVehicleData ("odometer:2500")
-- SDL: checks wether amount of kilometers sinse previous update is equal or greater "exchange_after_x_kilometers"
-- SDL->HMI: OnStatusUpdate (UPDATE_NEEDED)
--
-- Expected result:
-- PTU flow started
---------------------------------------------------------------------------------------------
--[[ General configuration parameters ]]
--ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed
config.defaultProtocolVersion = 2
--[[ Required Shared libraries ]]
local commonFunctions = require ('user_modules/shared_testcases/commonFunctions')
local commonSteps = require ('user_modules/shared_testcases/commonSteps')
local testCasesForPolicyTable = require ('user_modules/shared_testcases/testCasesForPolicyTable')
local utils = require ('user_modules/utils')
--[[ General Precondition before ATF start ]]
commonSteps:DeleteLogsFiles()
commonSteps:DeletePolicyTable()
--[[ Local Functions ]]
local function UpdatePolicy()
local PermissionForSubscribeVehicleData =
[[
"SubscribeVehicleData": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED"
],
"parameters" : ["odometer"]
}
]].. ", \n"
local PermissionForOnVehicleData =
[[
"OnVehicleData": {
"hmi_levels": [
"BACKGROUND",
"FULL",
"LIMITED"
],
"parameters" : ["odometer"]
}
]].. ", \n"
local PermissionLinesForBase4 = PermissionForSubscribeVehicleData..PermissionForOnVehicleData
local PTName = testCasesForPolicyTable:createPolicyTableFile_temp(PermissionLinesForBase4, nil, nil, {"SubscribeVehicleData","OnVehicleData"})
testCasesForPolicyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt(PTName)
end
UpdatePolicy()
--[[ General Settings for configuration ]]
Test = require('connecttest')
require('cardinalities')
require('user_modules/AppTypes')
require('mobile_session')
--[[ Preconditions ]]
commonFunctions:newTestCasesGroup("Preconditions")
function Test:Precondition_Activate_App_Start_PTU()
local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications["Test Application"], level = "FULL"})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,data)
if data.result.isSDLAllowed ~= true then
RequestId = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage",
{language = "EN-US", messageCodes = {"DataConsent"}})
EXPECT_HMIRESPONSE(RequestId)
:Do(function(_,_)
self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality",
{allowed = true, source = "GUI", device = {id = utils.getDeviceMAC(), name = utils.getDeviceName()}})
EXPECT_HMICALL("BasicCommunication.ActivateApp")
:Do(function(_,data2)
self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", {})
end)
:Times(2)
end)
EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN" })
end
end)
end
function Test:Preconditions_Set_Odometer_Value1()
local cid_vehicle = self.mobileSession:SendRPC("SubscribeVehicleData", {odometer = true})
EXPECT_HMICALL("VehicleInfo.SubscribeVehicleData")
:Do(function(_,data)
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {
odometer = { resultCode = "SUCCESS", dataType = "VEHICLEDATA_ODOMETER" }
})
end)
EXPECT_RESPONSE(cid_vehicle, { success = true, resultCode = "SUCCESS" })
end
function Test:Precondition_Update_Policy_With_New_Exchange_After_X_Kilometers_Value()
local requestId = self.hmiConnection:SendRequest("SDL.GetPolicyConfigurationData",
{ policyType = "module_config", property = "endpoints" })
EXPECT_HMIRESPONSE(requestId)
:Do(function()
self.hmiConnection:SendNotification("BasicCommunication.OnSystemRequest",
{
requestType = "PROPRIETARY",
fileName = "filename"
}
)
EXPECT_NOTIFICATION("OnSystemRequest", { requestType = "PROPRIETARY" })
:Do(function()
local CorIdSystemRequest = self.mobileSession:SendRPC("SystemRequest",
{ fileName = "PolicyTableUpdate", requestType = "PROPRIETARY" },
"files/jsons/Policies/Policy_Table_Update/exchange_after_1000_kilometers_ptu.json")
local systemRequestId
EXPECT_HMICALL("BasicCommunication.SystemRequest")
:Do(function(_,data)
systemRequestId = data.id
self.hmiConnection:SendNotification("SDL.OnReceivedPolicyUpdate",
{
policyfile = "/tmp/fs/mp/images/ivsu_cache/PolicyTableUpdate"
})
local function to_run()
self.hmiConnection:SendResponse(systemRequestId,"BasicCommunication.SystemRequest", "SUCCESS", {})
end
RUN_AFTER(to_run, 800)
self.mobileSession:ExpectResponse(CorIdSystemRequest, {success = true, resultCode = "SUCCESS"})
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UP_TO_DATE"})
end)
end)
end)
EXPECT_HMICALL("VehicleInfo.GetVehicleData", { odometer = true })
:Do(function(_, d)
self.hmiConnection:SendResponse(d.id, d.method, "SUCCESS", { odometer = 1234 })
end)
end
--[[ Test ]]
commonFunctions:newTestCasesGroup("Test")
function Test:TestStep_Set_Odometer_Value_NO_PTU_Is_Triggered()
self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 2200})
EXPECT_NOTIFICATION("OnVehicleData", {odometer = 2200})
EXPECT_HMICALL("BasicCommunication.PolicyUpdate"):Times(0)
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}):Times(0)
end
function Test:TestStep_Set_Odometer_Value_And_Check_That_PTU_Is_Triggered()
self.hmiConnection:SendNotification("VehicleInfo.OnVehicleData", {odometer = 2250})
EXPECT_NOTIFICATION("OnVehicleData", {odometer = 2250})
EXPECT_HMICALL("BasicCommunication.PolicyUpdate")
EXPECT_HMINOTIFICATION("SDL.OnStatusUpdate", {status = "UPDATE_NEEDED"}, {status = "UPDATING"}):Times(AtLeast(1))
end
--[[ Postconditions ]]
commonFunctions:newTestCasesGroup("Postconditions")
testCasesForPolicyTable:Restore_preloaded_pt()
function Test.Postcondition_Stop()
StopSDL()
end
return Test
|
local mod = DBM:NewMod(1997, "DBM-AntorusBurningThrone", nil, 946)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17522 $"):sub(12, -3))
mod:SetCreatureID(122369, 122333, 122367)--Chief Engineer Ishkar, General Erodus, Admiral Svirax
mod:SetEncounterID(2070)
mod:SetZone()
mod:SetBossHPInfoToHighest()
mod:SetUsedIcons(7, 8)
mod:SetHotfixNoticeRev(16939)
mod.respawnTime = 29
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 244625 246505 253040 245227",
"SPELL_CAST_SUCCESS 244722 244892 245227 253037 245174",
"SPELL_AURA_APPLIED 244737 244892 253015 244172",
"SPELL_AURA_APPLIED_DOSE 244892 244172",
"SPELL_AURA_REMOVED 244737 253015",
-- "SPELL_PERIODIC_DAMAGE",
-- "SPELL_PERIODIC_MISSED",
"UNIT_SPELLCAST_SUCCEEDED boss1 boss2 boss3"
)
local Svirax = DBM:EJ_GetSectionInfo(16126)
local Ishkar = DBM:EJ_GetSectionInfo(16128)
local Erodus = DBM:EJ_GetSectionInfo(16130)
--TODO, boss health was reporting unknown in streams, verify/fix boss CIDs
--[[
(ability.id = 244625 or ability.id = 253040 or ability.id = 245227 or ability.id = 125012 or ability.id = 125014 or ability.id = 126258) and type = "begincast"
or (ability.id = 244722 or ability.id = 244892) and type = "cast" or (ability.id = 245174 or ability.id = 244947) and type = "summon"
or ability.id = 253015
--]]
--General
local warnOutofPod = mod:NewTargetNoFilterAnnounce("ej16098", 2, 244141)
local warnExploitWeakness = mod:NewStackAnnounce(244892, 2, nil, "Tank")
local warnPsychicAssault = mod:NewStackAnnounce(244172, 3, nil, "-Tank", 2)
--In Pod
----Chief Engineer Ishkar
local warnEntropicMine = mod:NewSpellAnnounce(245161, 2)
----General Erodus
--local warnSummonReinforcements = mod:NewSpellAnnounce(245546, 2, nil, false, 2)
local warnDemonicCharge = mod:NewTargetAnnounce(253040, 2, nil, false, 2)
--Out of Pod
----Admiral Svirax
local warnShockGrenade = mod:NewTargetAnnounce(244737, 3, nil, false, 2)
----Chief Engineer Ishkar
--General
--local specWarnGTFO = mod:NewSpecialWarningGTFO(238028, nil, nil, nil, 1, 2)
local specWarnExploitWeakness = mod:NewSpecialWarningTaunt(244892, nil, nil, nil, 1, 2)
local specWarnPsychicAssaultStack = mod:NewSpecialWarningStack(244172, nil, 10, nil, nil, 1, 6)
local specWarnPsychicAssault = mod:NewSpecialWarningMove(244172, nil, nil, nil, 3, 2)--Two diff warnings cause we want to upgrade to high priority at 19+ stacks
local specWarnAssumeCommand = mod:NewSpecialWarningSwitch(253040, "Tank", nil, nil, 1, 2)
--In Pod
----Admiral Svirax
local specWarnFusillade = mod:NewSpecialWarningMoveTo(244625, nil, nil, nil, 1, 5)
----Chief Engineer Ishkar
--local specWarnEntropicMine = mod:NewSpecialWarningDodge(245161, nil, nil, nil, 1, 2)
----General Erodus
local specWarnSummonReinforcements = mod:NewSpecialWarningSwitch(245546, nil, nil, nil, 1, 2)
-------Adds
local specWarnPyroblast = mod:NewSpecialWarningInterrupt(246505, "HasInterrupt", nil, nil, 1, 2)
local specWarnDemonicChargeYou = mod:NewSpecialWarningYou(253040, nil, nil, nil, 1, 2)
local specWarnDemonicCharge = mod:NewSpecialWarningClose(253040, nil, nil, nil, 1, 2)
local yellDemonicCharge = mod:NewYell(253040)
--Out of Pod
----Admiral Svirax
local specWarnShockGrenade = mod:NewSpecialWarningMoveAway(244737, nil, nil, nil, 1, 2)
local yellShockGrenade = mod:NewShortYell(244737)
local yellShockGrenadeFades = mod:NewShortFadesYell(244737)
--General
mod:AddTimerLine(GENERAL)
local timerExploitWeaknessCD = mod:NewCDTimer(8.5, 244892, nil, "Tank", nil, 5, nil, DBM_CORE_TANK_ICON)
local timerShockGrenadeCD = mod:NewCDTimer(14.7, 244722, nil, nil, nil, 3, nil, DBM_CORE_HEROIC_ICON)
local timerAssumeCommandCD = mod:NewNextTimer(90, 245227, nil, nil, nil, 6)
--In Pod
----Admiral Svirax
mod:AddTimerLine(Svirax)
local timerFusilladeCD = mod:NewNextCountTimer(29.3, 244625, nil, nil, nil, 2, nil, DBM_CORE_DEADLY_ICON)
----Chief Engineer Ishkar
mod:AddTimerLine(Ishkar)
local timerEntropicMineCD = mod:NewCDTimer(10, 245161, nil, nil, nil, 3)
----General Erodus
mod:AddTimerLine(Erodus)
local timerSummonReinforcementsCD = mod:NewNextTimer(8.4, 245546, nil, nil, nil, 1, nil, DBM_CORE_DAMAGE_ICON)
--local berserkTimer = mod:NewBerserkTimer(600)
--General
local countdownAssumeCommand = mod:NewCountdown("Alt50", 245227)
local countdownExploitWeakness = mod:NewCountdown("Alt8", 244892, "Tank", nil, 3)
--In Pod
----Admiral Svirax
local countdownFusillade = mod:NewCountdown("AltTwo30", 244625)
----General Erodus
local countdownReinforcements = mod:NewCountdown(25, 245546)
mod:AddSetIconOption("SetIconOnAdds", 245546, true, true)
mod:AddRangeFrameOption("8")
local felShield = DBM:GetSpellInfo(244910)
mod.vb.FusilladeCount = 0
mod.vb.lastIcon = 8
function mod:DemonicChargeTarget(targetname, uId)
if not targetname then return end
if targetname == UnitName("player") then
if self:AntiSpam(3, 5) then
specWarnDemonicChargeYou:Show()
specWarnDemonicChargeYou:Play("runaway")
yellDemonicCharge:Yell()
end
elseif self:AntiSpam(3.5, 2) and self:CheckNearby(10, targetname) then
specWarnDemonicCharge:Show(targetname)
specWarnDemonicCharge:Play("watchstep")
else
warnDemonicCharge:Show(targetname)
end
end
function mod:OnCombatStart(delay)
self.vb.FusilladeCount = 0
self.vb.lastIcon = 8
--In pod
timerEntropicMineCD:Start(5.1-delay)
--Out of Pod
timerSummonReinforcementsCD:Start(8-delay)
countdownReinforcements:Start(8-delay)
timerAssumeCommandCD:Start(90-delay)
countdownAssumeCommand:Start(90-delay)
if self:IsMythic() then
timerShockGrenadeCD:Start(15)
end
end
function mod:OnCombatEnd()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 244625 then
self.vb.FusilladeCount = self.vb.FusilladeCount + 1
specWarnFusillade:Show(felShield)
specWarnFusillade:Play("findshield")
timerFusilladeCD:Start(nil, self.vb.FusilladeCount+1)
if not self:IsLFR() then
countdownFusillade:Start(29.3)
end
elseif spellId == 246505 then
if self:CheckInterruptFilter(args.sourceGUID, false, true) then
specWarnPyroblast:Show(args.sourceName)
specWarnPyroblast:Play("kickcast")
end
elseif spellId == 253040 then
self:BossTargetScanner(args.sourceGUID, "DemonicChargeTarget", 0.2, 9)
elseif spellId == 245227 then--Assume Command (entering pod)
specWarnAssumeCommand:Show()
specWarnAssumeCommand:Play("targetchange")
timerShockGrenadeCD:Stop()
timerExploitWeaknessCD:Stop()
countdownExploitWeakness:Cancel()
timerExploitWeaknessCD:Start(8)--8-14 (basically depends how fast you get there) If you heroic leap and are super fast. it's cast pretty much instantly on mob activation
countdownExploitWeakness:Start(8)
local cid = self:GetCIDFromGUID(args.sourceGUID)
if cid == 122369 then--Chief Engineer Ishkar
timerEntropicMineCD:Start(8)
timerFusilladeCD:Stop()--Seems this timer resets too
countdownFusillade:Cancel()
timerFusilladeCD:Start(15.9, 1)--Start Updated Fusillade
countdownFusillade:Start(15.9)
--TODO, reinforcements fix
elseif cid == 122333 then--General Erodus
timerSummonReinforcementsCD:Start(11)--Starts elite ones
countdownReinforcements:Start(11)
elseif cid == 122367 then--Admiral Svirax
self.vb.FusilladeCount = 0
timerFusilladeCD:Start(15, 1)
countdownFusillade:Start(15)
timerSummonReinforcementsCD:Stop()--Seems this timer resets too
countdownReinforcements:Cancel()
timerSummonReinforcementsCD:Start(16)--Start updated reinforcements timer
countdownReinforcements:Start(16)
end
if self:IsMythic() then
timerShockGrenadeCD:Start(9.7)
end
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 244722 then
timerShockGrenadeCD:Start()--21
elseif spellId == 244892 then
timerExploitWeaknessCD:Start()
countdownExploitWeakness:Start(8.5)
elseif spellId == 245227 then--Assume Command
timerAssumeCommandCD:Start(90)
countdownAssumeCommand:Start(90)
elseif spellId == 253037 then
if args:IsPlayer() then
specWarnDemonicChargeYou:Show()
specWarnDemonicChargeYou:Play("runaway")
yellDemonicCharge:Yell()
elseif self:CheckNearby(10, args.destName) then
specWarnDemonicCharge:Show(args.destName)
specWarnDemonicCharge:Play("watchstep")
else
warnDemonicCharge:Show(args.destName)
end
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 244737 then
warnShockGrenade:CombinedShow(1, args.destName)
if args:IsPlayer() then
specWarnShockGrenade:Show()
specWarnShockGrenade:Play("runout")
yellShockGrenade:Yell()
yellShockGrenadeFades:Countdown(5, 3)
if self.Options.RangeFrame then
DBM.RangeCheck:Show(8)
end
end
elseif spellId == 244892 then
local uId = DBM:GetRaidUnitId(args.destName)
if self:IsTanking(uId) then
local amount = args.amount or 1
if amount >= 2 then
local _, _, _, _, _, _, expireTime = DBM:UnitDebuff("player", spellId)
local remaining
if expireTime then
remaining = expireTime-GetTime()
end
if not UnitIsDeadOrGhost("player") and (not remaining or remaining and remaining < 8) then
specWarnExploitWeakness:Show(args.destName)
specWarnExploitWeakness:Play("tauntboss")
else
warnExploitWeakness:Show(args.destName, amount)
end
else
warnExploitWeakness:Show(args.destName, amount)
end
end
elseif spellId == 244172 then
local amount = args.amount or 1
if args:IsPlayer() then
if amount == 10 or amount == 15 then
if amount >= 19 then--High priority
specWarnPsychicAssault:Show()
specWarnPsychicAssault:Play("otherout")
else--Just a basic stack warning
specWarnPsychicAssaultStack:Show(amount)
specWarnPsychicAssaultStack:Play("stackhigh")
end
end
else
if amount >= 10 and amount % 5 == 0 then
warnPsychicAssault:Show(args.destName, amount)
end
end
end
end
mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 244737 then
if args:IsPlayer() then
yellShockGrenadeFades:Cancel()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
end
end
end
--[[
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 228007 and destGUID == UnitGUID("player") and self:AntiSpam(2, 4) then
specWarnGTFO:Show()
specWarnGTFO:Play("runaway")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
--]]
--"<14.68 23:07:26> [UNIT_SPELLCAST_SUCCEEDED] General Erodus(??) [[boss3:Summon Reinforcements::3-2083-1712-2166-245546-00015E79FE:245546]]", -- [121]
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, _, spellId)
if (spellId == 245161 or spellId == 245304) and self:AntiSpam(5, 1) then
warnEntropicMine:Show()
--warnEntropicMine:Play("watchstep")
timerEntropicMineCD:Start()
elseif spellId == 245785 then--Pod Spawn Transition Cosmetic Missile
local name = UnitName(uId)
local GUID = UnitGUID(uId)
warnOutofPod:Show(name)
local cid = self:GetCIDFromGUID(GUID)
if cid == 122369 then--Chief Engineer Ishkar
timerEntropicMineCD:Stop()
elseif cid == 122333 then--General Erodus
timerSummonReinforcementsCD:Stop()--Elite ones
countdownReinforcements:Cancel()
elseif cid == 122367 then--Admiral Svirax
timerFusilladeCD:Stop()
countdownFusillade:Cancel()
end
elseif spellId == 245546 then--Summon Reinforcements (major adds)
specWarnSummonReinforcements:Show()
specWarnSummonReinforcements:Play("killmob")
timerSummonReinforcementsCD:Start(35)
countdownReinforcements:Start(35)
if self.Options.SetIconOnAdds then
self:ScanForMobs(122890, 0, self.vb.lastIcon, 1, 0.1, 12, "SetIconOnAdds")
end
if self.vb.lastIcon == 8 then
self.vb.lastIcon = 7
else
self.vb.lastIcon = 8
end
end
end
|
require 'gnuplot'
if arg[1] == nil then
print('-draw\tdraw epoc - error rate graph')
print('-print\tprint error rate for each fold, and total error rate')
os.exit(1)
end
errSum = 0.0
M = {}
table.insert(M, 'log152_1')
table.insert(M, 'log200_1')
--for i = 1,5 do
for i, f in pairs(M) do
errRates = {}
err = 0.0
-- for line in io.lines('log' .. i) do
for line in io.lines(f) do
if (string.find(line, 'Finished epoch') ~= nil) then
b, e = string.find(line, 'top1:')
errRate = string.sub(line, e+1, e+8)
table.insert(errRates, tonumber(errRate))
err = tonumber(errRate)
end
end
errSum = errSum + err
if (arg[1] == '-draw') then
gnuplot.figure(i)
y = torch.DoubleTensor(errRates)
gnuplot.plot(y)
end
if (arg[1] == '-print') then
print(err)
end
end
if (arg[1] == '-print') then
print(errSum / 5)
end
|
--[[
__ __ _______ __ __ __ __ ________
/ \ / / / _____/ \ \ / / \ \ \ \ \ _____\
/ /\ \ / / / /____ \ \/ / \ \ \ \ \ \_____
/ / \ \ / / / _____/ / /\ \ \ \ \ \ \_____ \
/ / \ \/ / / /____ / / \ \ \ \__\ \ ____\ \
/_/ \__/ /______/ /_/ \_\ \______\ \______\
Nexus VR Character Model, by TheNexusAvenger
File: NexusVRCharacterModel/NexusVRCharacter/Character/TorsoCreator.module.lua
Author: TheNexusAvenger
Date: March 11th 2018
TorsoCreator:CreateTorso(CharacterModel)
Converts R15 Torso of given CharacterModel to TorsoClass
RETURNS: TorsoClass
CLASS TorsoClass
TorsoClass:UpdatePosition(NeckCF)
Moves Torso based on Neck CFrame
TorsoClass:SetLocalTransparencyModifier(TransparencyModifier)
Sets LocalTransparencyModifier of the torso
TorsoClass:GetLocalTransparencyModifier()
Gets LocalTransparencyModifier of torso
RETURNS: double
TorsoClass:GetLeftShoulderCFrame()
Gets CFrame of left shoulder
RETURNS: CFrame
TorsoClass:GetRightShoulderCFrame()
Gets CFrame of right shoulder
RETURNS: CFrame
TorsoClass:GetLeftHipCFrame()
Gets CFrame of left hip
RETURNS: CFrame
TorsoClass:GetRightHipCFrame()
Gets CFrame of right hip
RETURNS: CFrame
TorsoClass:Disconnect()
Disconnects all events
--]]
local TorsoCreator = {}
local Configuration = require(script.Parent.Parent:WaitForChild("Configuration"))
local MAX_TORSO_BEND = Configuration.TorsoCreator.MAX_TORSO_BEND
local Util = require(script.Parent:WaitForChild("Util"))
local CFnew,CFAngles = CFrame.new,CFrame.Angles
local atan2 = math.atan2
local function GetAngleX(CF)
local LookVector = CF.lookVector
local X,Y,Z = LookVector.X,LookVector.Y,LookVector.Z
local XZ = ((X ^ 2) + (Z ^ 2)) ^ 0.5
return atan2(Y,XZ)
end
local function CreateHead(Head,UpperTorso,LowerTorso)
local TorsoClass = {}
local NeckRigAttachment = UpperTorso:WaitForChild("NeckRigAttachment")
local LeftShoulderRigAttachment = UpperTorso:WaitForChild("LeftShoulderRigAttachment")
local RightShoulderRigAttachment = UpperTorso:WaitForChild("RightShoulderRigAttachment")
local UpperWaistRigAttachment = UpperTorso:WaitForChild("WaistRigAttachment")
local LowerWaistRigAttachment = LowerTorso:WaitForChild("WaistRigAttachment")
local LeftHipRigAttachment = LowerTorso:WaitForChild("LeftHipRigAttachment")
local RightHipRigAttachment = LowerTorso:WaitForChild("RightHipRigAttachment")
local NeckMotor,WaistMotor = Head:WaitForChild("Neck"),UpperTorso:WaitForChild("Waist")
local CurrentScale = 1
local NeckToTorsoOffset,UpperTorsoToCenterOffset,CenterToLowerTorsoOffset
local LeftShoulderOffset,RightShoulderOffset
local LeftHipOffset,RightHipOffset
local function UpdateSizes(NewScale)
local Scale = NewScale/CurrentScale
CurrentScale = NewScale
Util:ScaleDescendants(UpperTorso,Scale)
Util:ScaleDescendants(LowerTorso,Scale)
--UpperTorso.Size = UpperTorso.Size * NewScale
--LowerTorso.Size = LowerTorso.Size * NewScale
NeckToTorsoOffset = CFnew(-NeckRigAttachment.Position)
UpperTorsoToCenterOffset = CFnew(UpperWaistRigAttachment.Position)
CenterToLowerTorsoOffset = CFnew(-LowerWaistRigAttachment.Position)
LeftShoulderOffset = CFnew(LeftShoulderRigAttachment.Position)
RightShoulderOffset = CFnew(RightShoulderRigAttachment.Position)
LeftHipOffset = CFnew(LeftHipRigAttachment.Position)
RightHipOffset = CFnew(RightHipRigAttachment.Position)
end
UpdateSizes(1)
local UpperTorsoCF,LowerTorsoCF = CFnew(),CFnew()
function TorsoClass:UpdatePosition(NeckCF)
local AngleUp = GetAngleX(NeckCF)
local LowerTorsoTilt = 0
if AngleUp > MAX_TORSO_BEND then
LowerTorsoTilt = AngleUp - MAX_TORSO_BEND
elseif AngleUp < -MAX_TORSO_BEND then
LowerTorsoTilt = AngleUp + MAX_TORSO_BEND
end
UpperTorsoCF = NeckCF * NeckToTorsoOffset
local CenterTorsoCF = UpperTorsoCF * UpperTorsoToCenterOffset * CFAngles(-LowerTorsoTilt,0,0)
LowerTorsoCF = CenterTorsoCF * CenterToLowerTorsoOffset
Util:MoveMotorC1ToPosition(NeckMotor,UpperTorsoCF)
Util:MoveMotorC1ToPosition(WaistMotor,LowerTorsoCF)
end
function TorsoClass:SetLocalTransparencyModifier(TransparencyModifier)
UpperTorso.LocalTransparencyModifier = TransparencyModifier
LowerTorso.LocalTransparencyModifier = TransparencyModifier
end
function TorsoClass:GetLocalTransparencyModifier()
return UpperTorso.LocalTransparencyModifier
end
--function TorsoClass:SetScale(Scale)
-- UpdateSizes(Scale)
--end
function TorsoClass:GetLeftShoulderCFrame()
return UpperTorsoCF * LeftShoulderOffset
end
function TorsoClass:GetRightShoulderCFrame()
return UpperTorsoCF * RightShoulderOffset
end
function TorsoClass:GetLeftHipCFrame()
return LowerTorsoCF * LeftHipOffset
end
function TorsoClass:GetRightHipCFrame()
return LowerTorsoCF * RightHipOffset
end
function TorsoClass:Disconnect()
end
return TorsoClass
end
function TorsoCreator:CreateTorso(CharacterModel)
local Head = CharacterModel:WaitForChild("Head")
local UpperTorso = CharacterModel:WaitForChild("UpperTorso")
local LowerTorso = CharacterModel:WaitForChild("LowerTorso")
return CreateHead(Head,UpperTorso,LowerTorso)
end
return TorsoCreator
|
--[[
==README==
Layer Increment
Basic utility that will make selected lines have increasing or decreasing layer numbers.
]]
script_name = "Layer increment"
script_description = "Makes increasing or decreasing layer numbers."
script_version = "1.1.0"
script_author = "lyger"
script_namespace = "lyger.LayerIncrement"
local DependencyControl = require("l0.DependencyControl")
local rec = DependencyControl{
feed = "https://raw.githubusercontent.com/TypesettingTools/lyger-Aegisub-Scripts/master/DependencyControl.json"
}
local config = {
{
class="dropdown", name="updown",
items={"Count up","Count down"},
x=0,y=0,width=2,height=1,
value="Count up"
},
{
class="label",label="Interval",
x=0,y=1,width=1,height=1
},
{
class="intedit",name="int",
x=1,y=1,width=1,height=1,
min=1,value=1
}
}
function layer_inc(sub,sel)
local pressed, results = aegisub.dialog.display(config,{"Go","Cancel"})
local min_layer = 0
for _,li in ipairs(sel) do
local line = sub[li]
if line.layer>min_layer then
min_layer = line.layer
end
end
local start_layer = min_layer
local factor=1
local interval = results["int"]
if results["updown"]=="Count down" then
start_layer = min_layer + (#sel-1)*interval
factor = -1
end
for j,li in ipairs(sel) do
local line = sub[li]
line.layer = start_layer + (j-1)*factor*interval
sub[li] = line
end
return sel
end
rec:registerMacro(layer_inc)
|
Class = require("lib/class")
Json = require("lib/json")
require("src/Constants")
require("src/Utils")
require("src/StateMachine")
require("src/States/BaseState")
require("src/States/MenuState")
require("src/States/PlayState")
require("src/States/GameOverState")
require("src/LevelEditor/LevelEditor")
require("src/LevelEditor/LevelMaker")
require("src/Bullet")
require("src/Ship")
require("src/Player")
require("src/Crate")
require("src/Enemy") |
local c2e = require("c2etrigger")("Control+t", require("c2e"))
c2e_translator = c2e.translator
c2e_processor = c2e.processor
local e2c = require("e2ctrigger")("Control+e", require("e2c"))
e2c_translator = e2c.translator
e2c_processor = e2c.processor
|
local Class = require 'lib.hump.class'
local Event = getClass 'wyx.event.Event'
-- Game Start - fires when the game starts, before drawing or updating
local GameStartEvent = Class{name='GameStartEvent',
inherits=Event,
function(self)
Event.construct(self, 'Game Start Event')
end
}
-- the class
return GameStartEvent
|
--- === bit.hyper ===
---
--- (only works with https://github.com/lodestone/hyper-hacks)
--- Sets up that pressing the caps-lock key is the same as pressing
--- SHFT-CTRL-ALT-CMD so that it can be used as a 'hyper' key
local hyper = {}
local hotkey = require 'hs.hotkey'
local eventtap = require 'hs.eventtap'
local hyperModal = hotkey.modal.new({}, "f17")
local pressedHyper = function()
hyperModal.triggered = false
hyperModal:enter()
end
local releasedHyper = function()
hyperModal:exit()
if not hyperModal.triggered then
eventtap.keyStroke({}, 'ESCAPE')
end
end
local hyper = hotkey.bind({}, "f18", pressedHyper, releasedHyper)
hyper.bind = function(key, fn)
hyperModal:bind({}, key, nil, function()
fn()
hyperModal.triggered = true
end)
end
return hyper
|
return function(self, keyword)
local ret = {}
for _, v in pairs(self) do
if type(v) == "table" and v.name and v.name:match(keyword) then
table.insert(ret, v)
end
end
return ret
end
|
DUNGEONEER_VERSION = "3.0"
DEBUG = false
if IsInToolsMode() then
DEBUG = true
end
if GameMode == nil then
_G.GameMode = class({})
end
require('libraries/timers')
require('libraries/physics')
require('libraries/projectiles')
require('libraries/notifications')
require('libraries/animations')
require('libraries/playertables')
require('libraries/pathgraph')
require('libraries/selection')
require("statcollection/init")
require('mechanics/ApplyDamage')
require('mechanics/Arena')
require('mechanics/Encounter')
require('mechanics/Encounter_Warnings')
require('mechanics/GameCycle')
require('mechanics/GameModeVote')
require('mechanics/Hero_GetsChecks')
require('mechanics/Info')
require('mechanics/Math')
require('mechanics/Perks')
require('mechanics/Dungeoneer_Lore')
require('mechanics/HttpSend')
require('mechanics/ChallengerMode')
require('mechanics/Currencies')
require('mechanics/Checklist')
require('mechanics/Tutorial')
require('events')
require('gamemode_init')
require('settings')
LinkLuaModifier( 'power_buff', 'modifier/power_buff', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_player_disconnected', 'modifier/modifier_player_disconnected', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'casting_modifier', 'modifier/casting_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'casting_rooted_modifier', 'modifier/casting_rooted_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'casting_no_turning_modifier', 'modifier/casting_no_turning_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'casting_frozen_modifier', 'modifier/casting_frozen_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_attack_immune', 'modifier/modifier_attack_immune', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_unselectable', 'modifier/modifier_unselectable', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_flying_for_pathing', 'modifier/modifier_flying_for_pathing', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_out_of_world', 'modifier/modifier_out_of_world', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_move_speed_no_limit', 'modifier/modifier_move_speed_no_limit', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'turn_rate_modifier', 'modifier/turn_rate_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'strength_resilience_modifier', 'modifier/strength_resilience_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'percentage_based_auto_attack_damage', 'modifier/percentage_based_auto_attack_damage', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_encounter_health', 'modifier/modifier_encounter_health', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_encounter_damage', 'modifier/modifier_encounter_damage', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_muted', 'modifier/modifier_muted', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'damage_meter', 'modifier/damage_meter', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_flying', 'modifier/modifier_flying', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_true_sight', 'modifier/modifier_true_sight', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_fake_ally', 'modifier/modifier_fake_ally', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_untargetable', 'modifier/modifier_untargetable', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_dummy', 'modifier/modifier_dummy', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'arcane_knowledge_modifier', 'modifier/arcane_knowledge_modifier', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_special_invis', 'modifier/modifier_special_invis', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_slowed', 'modifier/modifier_slowed', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'modifier_disable_damage_block', 'modifier/modifier_disable_damage_block', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'castrange_modifier_ability', 'modifier/castrange_modifier_ability', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'cooldown_modifier_ability', 'modifier/cooldown_modifier_ability', LUA_MODIFIER_MOTION_NONE )
-- ### Perk Modifiers Start ### --
LinkLuaModifier( 'glyph_blazing_gold', 'perks/glyph_blazing_gold', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_blazing_knowledge', 'perks/glyph_blazing_knowledge', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_blazing_mind', 'perks/glyph_blazing_mind', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_blazing_power', 'perks/glyph_blazing_power', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_mystic_book', 'perks/glyph_mystic_book', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_mystic_flask', 'perks/glyph_mystic_flask', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_mystic_rune', 'perks/glyph_mystic_rune', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_mystic_stream', 'perks/glyph_mystic_stream', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_petrified_cloak', 'perks/glyph_petrified_cloak', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_petrified_jewel', 'perks/glyph_petrified_jewel', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_petrified_particles', 'perks/glyph_petrified_particles', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_petrified_soil', 'perks/glyph_petrified_soil', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sacred_bracing', 'perks/glyph_sacred_bracing', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sacred_glory', 'perks/glyph_sacred_glory', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sacred_vigor', 'perks/glyph_sacred_vigor', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sacred_vitality', 'perks/glyph_sacred_vitality', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sparking_agility', 'perks/glyph_sparking_agility', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sparking_alacrity', 'perks/glyph_sparking_alacrity', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sparking_swiftness', 'perks/glyph_sparking_swiftness', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_sparking_thunder', 'perks/glyph_sparking_thunder', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_umbral_energy', 'perks/glyph_umbral_energy', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_umbral_force', 'perks/glyph_umbral_force', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_umbral_fragments', 'perks/glyph_umbral_fragments', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'glyph_umbral_potency', 'perks/glyph_umbral_potency', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_bound_souls', 'perks/artifact_bound_souls', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_celestial_barrage', 'perks/artifact_celestial_barrage', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_crackling_lightning', 'perks/artifact_crackling_lightning', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_crunching_ground', 'perks/artifact_crunching_ground', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_fiery_eruption', 'perks/artifact_fiery_eruption', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_holy_gush', 'perks/artifact_holy_gush', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_purifiying_mana_burst', 'perks/artifact_purifiying_mana_burst', LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( 'artifact_time_anomaly', 'perks/artifact_time_anomaly', LUA_MODIFIER_MOTION_NONE )
-- ### Perk Modifiers End ### --
GameRules.DAMAGE_METER = {}
GameRules.DAMAGE_METER_TIMER = {}
GameRules.DAMAGE_METER_BOSS_TIMER = {}
GameRules.DAMAGE_METER_BOSS_TIMER_TIME = 0
GameRules.DAMAGE_METER_TIMER_COUNT = {}
GameRules.DAMAGE_METER_TOTAL_DAMAGE = 0
GameRules.DAMAGE_METER_TOTAL_DAMAGE_HERO = {}
GameRules.DAMAGE_METER_DPS_HERO = {}
GameRules.DAMAGE_METER_DAMAGE_PERCENTAGE_HERO = {}
GameRules.HTTP_PAYLOAD = {}
PlayerCount_Start = 0
HeroEntities = {}
ItemsBuyTime = {}
if not Dungeoneer then
Dungeoneer = {}
end
function GameMode:PostLoadPrecache()
end
function GameMode:OnFirstPlayerLoaded()
SetActiveArena( GetRandomArena() )
Physics:GenerateAngleGrid()
end
function GameMode:OnHeroInGame(unit)
local player = unit:GetPlayerOwner()
local playerID = unit:GetPlayerOwnerID()
local isIllusion = false
--Remove Outpost Capture Ability
unit:RemoveAbility("ability_capture")
if unit:GetTeamNumber() == DOTA_TEAM_GOODGUYS then
local delayAdded = 0.2
local delay = 0
Timers:CreateTimer(0.1, function()
if unit:FindModifierByName("modifier_illusion") ~= nil then
isIllusion = true
end
end)
if isIllusion then return end
-- Add Artifact Ability --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
local abilityArtifact = unit:AddAbility("artifact_ability")
abilityArtifact:SetLevel(1)
abilityArtifact:SetActivated(false)
if unit:GetAbilityByIndex(3):GetAbilityName() ~= "generic_hidden" and
unit:GetAbilityByIndex(4):GetAbilityName() ~= "generic_hidden" then
local abilityReplace = unit:GetAbilityByIndex(4)
unit:SwapAbilities(abilityReplace:GetAbilityName(), "artifact_ability", false, true)
else
unit:SwapAbilities("generic_hidden", "artifact_ability", false, true)
end
end
if not unit:HasModifier("castrange_modifier_ability") then
unit:AddNewModifier(unit, self, "castrange_modifier_ability", {} )
end
if not unit:HasModifier("cooldown_modifier_ability") then
unit:AddNewModifier(unit, self, "cooldown_modifier_ability", {} )
end
end)
-- Teleport to Arena
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
PlayerResource:SetCameraTarget(playerID, unit)
FindClearSpaceForUnit(unit, GetSpecificBorderPoint("point_center"), false)
unit:Stop()
end
end)
-- Add Level --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
unit:AddExperience(400, DOTA_ModifyXP_Unspecified, false, true)
end
end)
-- Add Items --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
local itemDrop = unit:AddItemByName("item_boots_of_rejunivation")
itemDrop:SetPurchaser(unit)
itemDrop:SetPurchaseTime(GameRules:GetGameTime()-10.01)
end
end)
-- Add to HeroEntities --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
--table.insert(HeroEntities, unit)
CustomGameEventManager:Send_ServerToAllClients("debug_msg", { msg="xxxxxxx HeroEntities === "..tonumber(playerID+1).." -- "..unit:GetUnitName() } )
HeroEntities[tonumber(playerID+1)] = unit
end
end)
-- Add Physics --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not IsPhysicsUnit(unit) then
Physics:Unit(unit)
end
end)
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if IsPhysicsUnit(unit) then
unit:AdaptiveNavGridLookahead(true)
end
end)
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if IsPhysicsUnit(unit) then
unit:SetNavCollisionType(PHYSICS_NAV_BOUNCE)
end
end)
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if IsPhysicsUnit(unit) then
unit:SetGroundBehavior(PHYSICS_GROUND_LOCK)
end
end)
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if IsPhysicsUnit(unit) then
unit:SetBounceMultiplier(1.0)
end
end)
-- Add Hero Special Mechanic Modifiers --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
unit:AddNewModifier(unit, nil, "strength_resilience_modifier", {})
unit:AddNewModifier(unit, nil, "arcane_knowledge_modifier", {})
end)
-- Add No Invis Debuff --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
unit:AddNewModifier(unit, nil, "modifier_true_sight", {})
end)
-- Tutorial --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
Tutorial(playerID)
end
end)
-- Free Camera --
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
PlayerResource:SetCameraTarget(playerID, nil)
end
end)
-- This project has been abandoned - thanks for playing! --
--[[
delay = delay + RandomFloat(0.0, delayAdded)
Timers:CreateTimer(delay, function()
if not unit:IsTempestDouble() then
Notifications:TopToAll({text="This project has been abandoned - thanks for playing!", duration=10.0, style={color="rgb(200, 32, 32)", ["font-size"]="40px", ["text-shadow"]="1px 1px 4px 5.0 #333333b0"}, continue=false})
end
end)
]]
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
--unit:AddExperience(900, 0, false, true)
-- Perk Debug --
--unit:AddNewModifier(unit, nil, "greater_crusader_shield", {})
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
-- #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### DEBUG #### --
end
end
function GameMode:OnAllPlayersLoaded()
Timers:CreateTimer(1.0, function()
GeneratePerksAllPlayers()
PerkReplaceInit()
ChecklistsInitialize()
CustomGameEventManager:Send_ServerToAllClients("toggle_boss_info_visibility", { visible=false } )
CustomGameEventManager:Send_ServerToAllClients("info_round", { round=1 } )
end)
end
function GameMode:OnGameInProgress()
Timers:CreateTimer(1.0, function()
for i=0,GetPlayerCount()-1 do
--[[
local player = PlayerResource:GetPlayer(i)
if player ~= nil then
local hero = player:GetAssignedHero()
if hero ~= nil then
table.insert(HeroEntities, hero)
end
end]]
GameModeVote_Initilize(i)
end
GameModeVote_InitilizeAll()
PlayerCount_Start = GetPlayerCount()
if DEBUG then
CustomGameEventManager:Send_ServerToAllClients("perkspicker_debug", {} )
end
end)
--[[
if IsInToolsMode() then
local player = PlayerResource:GetPlayer(0)
local hero = player:GetAssignedHero()
Timers:CreateTimer(5.0, function()
for i=0,14 do
local item = hero:GetItemInSlot(i)
if item ~= nil then
print(" - DEBUG - 1", (item:GetPurchaseTime() * 100) / 100)
end
end
return 2.0
end)
end
]]
Timers:CreateTimer(10.0, function()
ArenaOutOfBoundsDetector()
end)
end
function GameMode:InitGameMode()
GameMode = self
-- Commands
--Convars:RegisterCommand( "win", Dynamic_Wrap(GameMode, 'Win'), "A console command example", FCVAR_CHEAT )
-- Listeners
--CustomGameEventManager:RegisterListener( "readycheck_vote", Dynamic_Wrap(GameMode, 'ReadyCheck_Vote'))
CustomGameEventManager:RegisterListener( "gamemode_lock", Dynamic_Wrap(GameMode, 'GameModeVote_Lock'))
CustomGameEventManager:RegisterListener( "gamemode_upvote", Dynamic_Wrap(GameMode, 'GameModeVote_Upvote'))
CustomGameEventManager:RegisterListener( "gamemode_classicsubmode_lock", Dynamic_Wrap(GameMode, 'GameModeVote_ClassicSubMode_Lock'))
CustomGameEventManager:RegisterListener( "gamemode_classicsubmode_difficulty", Dynamic_Wrap(GameMode, 'GameModeVote_ClassicSubMode_Difficulty'))
CustomGameEventManager:RegisterListener( "gamemode_classicsubmode_casualmode", Dynamic_Wrap(GameMode, 'GameModeVote_ClassicSubMode_CasualMode'))
CustomGameEventManager:RegisterListener( "gamemode_classicsubmode_endlessmode", Dynamic_Wrap(GameMode, 'GameModeVote_ClassicSubMode_EndlessMode'))
CustomGameEventManager:RegisterListener( "loot_empower", Dynamic_Wrap(GameMode, 'Loot_Empower'))
CustomGameEventManager:RegisterListener( "loot_overview_lock", Dynamic_Wrap(GameMode, 'Loot_Lock'))
CustomGameEventManager:RegisterListener( "perks_lock", Dynamic_Wrap(GameMode, 'Perks_Lock'))
CustomGameEventManager:RegisterListener( "perks_upvote", Dynamic_Wrap(GameMode, 'Perks_Upvote'))
CustomGameEventManager:RegisterListener( "perks_sell", Dynamic_Wrap(GameMode, 'Perks_Sell'))
CustomGameEventManager:RegisterListener( "perks_reroll", Dynamic_Wrap(GameMode, 'Perks_Reroll'))
CustomGameEventManager:RegisterListener( "perks_skip", Dynamic_Wrap(GameMode, 'Perks_Skip'))
CustomGameEventManager:RegisterListener( "activeperks_replace", Dynamic_Wrap(GameMode, 'Perks_Replace'))
CustomGameEventManager:RegisterListener( "activeperks_use_ability", Dynamic_Wrap(GameMode, 'Perks_UseAbility'))
CustomGameEventManager:RegisterListener( "boss_info_reroll_boss", Dynamic_Wrap(GameMode, 'Encounter_Reroll'))
CustomGameEventManager:RegisterListener( "retryfight", Dynamic_Wrap(GameMode, 'Encounter_Retry'))
CustomGameEventManager:RegisterListener( "ready", Dynamic_Wrap(GameMode, 'Encounter_Ready'))
CustomGameEventManager:RegisterListener( "continue_vote", Dynamic_Wrap(GameMode, 'Continue_Vote'))
-- Filters --
GameRules:GetGameModeEntity():SetDamageFilter(Dynamic_Wrap(GameMode, "DamageFilter"), self)
GameRules:GetGameModeEntity():SetModifyGoldFilter(Dynamic_Wrap(GameMode, "GoldGainedFilter"), self)
GameRules:GetGameModeEntity():SetItemAddedToInventoryFilter(Dynamic_Wrap(GameMode, "ItemAddedToInventoryFilter"), self)
--GameRules:GetGameModeEntity():SetModifierGainedFilter(Dynamic_Wrap(GameMode, "ModifierGainedFilter"), self)
end
function GameMode:DamageFilter(event)
local damage = event.damage
local damageType = event.damagetype_const
if event.entindex_attacker_const ~= nil and event.entindex_victim_const ~= nil then
local attacker = EntIndexToHScript(event.entindex_attacker_const)
local victim = EntIndexToHScript(event.entindex_victim_const)
--
local Modifier = victim:FindModifierByName("glyph_petrified_cloak")
if Modifier ~= nil then
local staggered_damage_percentage = ( Modifier.staggered_damage / 100 ) * ( Modifier:GetStackCount() / 10000 )
if staggered_damage_percentage > 1.0 then staggered_damage_percentage = 1.0 end
local staggered_damage = damage * staggered_damage_percentage
event.damage = event.damage - staggered_damage
end
--
local Modifier = victim:FindModifierByName("glyph_sacred_bracing")
if Modifier ~= nil then
if Modifier.shield_hp > 0 then
local result = Modifier.shield_hp - damage
if result < 0 then
Modifier.shield_hp = 0
event.damage = math.abs(result)
-- Particle --
if victim.shield_particle ~= nil then
ParticleManager:DestroyParticle( victim.shield_particle, false )
ParticleManager:ReleaseParticleIndex( victim.shield_particle )
victim.shield_particle = nil
end
else
Modifier.shield_hp = result
return false
end
end
end
--
if victim:GetUnitName() == "npc_dota_hero_treasure_on_a_tree" and victim.golden_shield_hero_angle ~= nil then
local angle = 90
--local hero_angle = victim:GetAnglesAsVector().y
local hero_angle = victim.golden_shield_hero_angle
local origin_difference = attacker:GetAbsOrigin() - victim:GetAbsOrigin()
local origin_difference_radian = math.atan2(origin_difference.y, origin_difference.x)
origin_difference_radian = origin_difference_radian * 180
local caster_angle = origin_difference_radian / math.pi
caster_angle = caster_angle + 0.0 -- +180 for opposite side
local result_angle = caster_angle - hero_angle
result_angle = math.abs(result_angle)
if result_angle > 360.00 then
result_angle = result_angle - 360.00
end
if ( result_angle >= 0 and result_angle <= (angle / 2) ) or
( result_angle >= (360 - (angle / 2)) and result_angle <= 360 ) then
-- Sound --
StartSoundEventReliable("Hero_Bristleback.Bristleback", victim)
return false
end
end
--
end
return true
end
function GameMode:GoldGainedFilter(event)
local reason = event.reason_const
local reliable = event.reliable
local playerID = event.player_id_const
local gold = event.gold
if reason ~= DOTA_ModifyGold_Unspecified then
return false
end
return true
end
function GameMode:ItemAddedToInventoryFilter(event, context)
local unit = EntIndexToHScript( event.item_parent_entindex_const ) --event.inventory_parent_entindex_const
local item = EntIndexToHScript( event.item_entindex_const )
local suggested_slot = event.suggested_slot
--print("DEBUG - ItemAddedToInventoryFilter !!! unit:GetUnitName", unit:GetUnitName() )
--print("DEBUG - ItemAddedToInventoryFilter !!! item:GetAbilityName", item:GetAbilityName() )
--print("DEBUG - ItemAddedToInventoryFilter !!! suggested_slot", suggested_slot)
--print("DEBUG - ItemAddedToInventoryFilter END !!!")
if item:GetAbilityName() == "item_book_of_agility" then
Item_ConsumeBook(unit, item, "item_book_of_agility", "item_book_of_agility_modifier", "bonus_agility")
return false
end
if item:GetAbilityName() == "item_book_of_strength" then
Item_ConsumeBook(unit, item, "item_book_of_strength", "item_book_of_strength_modifier", "bonus_strength")
return false
end
if item:GetAbilityName() == "item_book_of_intelligence" then
Item_ConsumeBook(unit, item, "item_book_of_intelligence", "item_book_of_intelligence_modifier", "bonus_intelligence")
return false
end
if item:GetAbilityName() == "item_ancient_book_of_proficiency" then
local bonus = item:GetSpecialValueFor("bonus_all_stats")
unit:AddNewModifier(unit, nil, "item_ancient_book_of_proficiency_modifier", {bonus=bonus} )
unit:EmitSound("Item.TomeOfKnowledge")
UTIL_Remove(item)
return false
end
if item:GetAbilityName() == "item_artifact_of_lesser_knowledge" then
local limit_per_hero = item:GetSpecialValueFor("limit_per_hero")
if unit.item_consumed_books == nil then
unit.item_consumed_books = {}
end
if unit.item_consumed_books["item_artifact_of_lesser_knowledge"] == nil then
unit.item_consumed_books["item_artifact_of_lesser_knowledge"] = 0
end
if unit.item_consumed_books["item_artifact_of_lesser_knowledge"] < limit_per_hero then
--unit:AddNewModifier(unit, nil, "item_artifact_of_lesser_knowledge_modifier", {})
unit:EmitSound("Item.MoonShard.Consume")
LootPerks( unit:GetPlayerOwnerID(), true, "lesser" )
unit.item_consumed_books["item_artifact_of_lesser_knowledge"] = unit.item_consumed_books["item_artifact_of_lesser_knowledge"] + 1
else
unit:ModifyGold(item:GetCost(), true, DOTA_ModifyGold_Unspecified)
Notifications:Bottom(unit:GetPlayerOwnerID(), {text="You cannot exceed the hero limit of "..limit_per_hero, duration=2.0, style={color="rgb(200, 48, 48)", ["font-size"]="20", ["text-shadow"]="1px 1px 4px 5.0 #333333b0"}, continue=false})
end
UTIL_Remove(item)
return false
end
if item:GetAbilityName() == "item_artifact_of_greater_knowledge" then
local limit_per_hero = item:GetSpecialValueFor("limit_per_hero")
if unit.item_consumed_books == nil then
unit.item_consumed_books = {}
end
if unit.item_consumed_books["item_artifact_of_greater_knowledge"] == nil then
unit.item_consumed_books["item_artifact_of_greater_knowledge"] = 0
end
if unit.item_consumed_books["item_artifact_of_greater_knowledge"] < limit_per_hero then
--unit:AddNewModifier(unit, nil, "item_artifact_of_lesser_knowledge_modifier", {})
unit:EmitSound("Item.MoonShard.Consume")
LootPerks( unit:GetPlayerOwnerID(), true, "greater" )
unit.item_consumed_books["item_artifact_of_greater_knowledge"] = unit.item_consumed_books["item_artifact_of_greater_knowledge"] + 1
else
unit:ModifyGold(item:GetCost(), true, DOTA_ModifyGold_Unspecified)
Notifications:Bottom(unit:GetPlayerOwnerID(), {text="You cannot exceed the hero limit of "..limit_per_hero, duration=2.0, style={color="rgb(200, 48, 48)", ["font-size"]="20", ["text-shadow"]="1px 1px 4px 5.0 #333333b0"}, continue=false})
end
UTIL_Remove(item)
return false
end
return true
end
function Item_ConsumeBook(unit, item, item_name, item_modifier_name, item_bonus)
local bonus = item:GetSpecialValueFor(item_bonus)
local limit_per_hero = item:GetSpecialValueFor("limit_per_hero")
if unit.item_consumed_books == nil then
unit.item_consumed_books = {}
end
if unit.item_consumed_books[item_name] == nil then
unit.item_consumed_books[item_name] = 0
end
if unit.item_consumed_books[item_name] < limit_per_hero then
unit:AddNewModifier(unit, nil, item_modifier_name, {bonus=bonus} )
unit:EmitSound("Item.TomeOfKnowledge")
unit.item_consumed_books[item_name] = unit.item_consumed_books[item_name] + 1
else
unit:ModifyGold(item:GetCost(), true, DOTA_ModifyGold_Unspecified)
Notifications:Bottom(unit:GetPlayerOwnerID(), {text="You cannot exceed the hero limit of "..limit_per_hero, duration=2.0, style={color="rgb(200, 48, 48)", ["font-size"]="20", ["text-shadow"]="1px 1px 4px 5.0 #333333b0"}, continue=false})
end
UTIL_Remove(item)
end
function stringSplit(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function round(number, decimals)
local power = 10^decimals
return math.floor(number * power) / power
end
function titleCase( first, rest )
return first:upper()..rest:lower()
end
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local require = require(ReplicatedStorage:WaitForChild("Nevermore", 5))
local rq = require("rquery")
local TimeManager = {}
-- Local Variables
local StartTime = 0
local Duration = 0
-- Initialization
local MapPurgeProof = rq.GetOrAddItem("MapPurgeProof", "Folder", game:GetService("Workspace"))
local Time = Instance.new('IntValue', MapPurgeProof)
Time.Name = 'Time'
-- Functions
function TimeManager:StartTimer(duration)
StartTime = tick()
Duration = duration
spawn(function()
repeat
Time.Value = Duration - (tick() - StartTime)
wait()
until Time.Value <= 0
Time.Value = 0
end)
end
function TimeManager:TimerDone()
return tick() - StartTime >= Duration
end
return TimeManager
|
package.path = (package.path or "") .. ";/home/irocha/.luarocks/share/lua/5.1/?.lua;"
package.cpath = (package.cpath or "") .. ";/home/irocha/.luarocks/lib/lua/5.1/?.so;"
function d(o)
if type(o) == "table" then
for k, v in pairs(o) do
print(k,v)
end
else
print(o)
end
end
d(_G)
redis = require 'redis'
client = redis.connect({ host = '127.0.0.1', port = 6379, timeout = 0 })
for k,v in pairs(client:info()) do
print(k .. ' => ' .. tostring(v))
if type(v) == 'table' then
for ki,vi in pairs(v) do
print("\t"..ki .. ' => ' .. tostring(vi))
end
end
end
|
--[[
eofnewline.lua
makes sure file ends with newline
version: 20200703_112529
originally by bokunodev
https://github.com/bokunodev/lite_modules/blob/master/plugins/eofnewline.lua?raw=1
--]]
local core = require "core"
local command = require "core.command"
local Doc = require "core.doc"
local function eof_newline(doc)
local leof, neof = #doc.lines, #doc.lines
for i = leof, 1, -1 do
if not string.match(doc.lines[i], "^%s*$") then break end
neof = i
end
if neof ~= leof then
doc:remove(neof, 1, leof, math.huge)
return
end
if "\n" ~= doc.lines[leof] then doc:insert(leof, math.huge, "\n") end
end
local save = Doc.save
Doc.save = function(self, ...)
eof_newline(self)
save(self, ...)
end
command.add("core.docview", {
["eof-newline:eof-newline"] = function() eof_newline(core.active_view.doc) end,
})
|
EditorSpawnEnemyGroup = EditorSpawnEnemyGroup or class(MissionScriptEditor)
EditorSpawnEnemyGroup.RANDOMS = {"amount"}
function EditorSpawnEnemyGroup:create_element()
self.super.create_element(self)
self._element.class = "ElementSpawnEnemyGroup"
self._element.values.spawn_type = "ordered"
self._element.values.ignore_disabled = true
self._element.values.amount = 0
self._element.values.elements = {}
self._element.values.interval = 0
self._element.values.team = "default"
end
function EditorSpawnEnemyGroup:post_init(...)
EditorSpawnEnemyGroup.super.post_init(self, ...)
if self._element.values.preferred_spawn_groups then
local i = 1
while i <= #self._element.values.preferred_spawn_groups do
if not tweak_data.group_ai.enemy_spawn_groups[self._element.values.preferred_spawn_groups[i]] then
table.remove(self._element.values.preferred_spawn_groups, i)
else
i = i + 1
end
end
if not next(self._element.values.preferred_spawn_groups) then
self._element.values.preferred_spawn_groups = nil
end
end
if self._element.values.random ~= nil then
self._element.values.spawn_type = self._element.values.random and "random" or "ordered"
self._element.values.random = nil
end
end
function EditorSpawnEnemyGroup:_build_panel()
self:_create_panel()
self:BuildElementsManage("elements", nil, {"ElementSpawnEnemyDummy"})
self:ComboCtrl("spawn_type", table.list_add({"ordered"}, {"random", "group", "group_guaranteed"}), {help = "Specify how the enemy will be spawned."})
self:BooleanCtrl("ignore_disabled", {help = "Select if disabled spawn points should be ignored or not"})
self:NumberCtrl("amount", {floats = 0, min = 0, help = "Specify amount of enemies to spawn from group"})
self:NumberCtrl("interval", {floats = 0, min = 0, help = "Used to specify how often this spawn can be used. 0 means no interval"})
self:ComboCtrl("team", table.list_add({"default"}, tweak_data.levels:get_team_names_indexed()), {help = "Select the group's team (overrides character team)."})
local opt = {}
for cat_name, team in pairs(tweak_data.group_ai.enemy_spawn_groups) do
table.insert(opt, cat_name)
end
for i, o in ipairs(opt) do
self._menu:Toggle({
name = o,
text = o,
value = self._element.values.preferred_spawn_groups and table.contains(self._element.values.preferred_spawn_groups, o) or false,
on_callback = ClassClbk(self, "on_preferred_spawn_groups_checkbox_changed"),
})
end
end
function EditorSpawnEnemyGroup:on_preferred_spawn_groups_checkbox_changed(item)
if item.value then
self._element.values.preferred_spawn_groups = self._element.values.preferred_spawn_groups or {}
if table.contains(self._element.values.preferred_spawn_groups, item.name) then
return
end
table.insert(self._element.values.preferred_spawn_groups, item.name)
elseif self._element.values.preferred_spawn_groups then
table.delete(self._element.values.preferred_spawn_groups, item.name)
if not next(self._element.values.preferred_spawn_groups) then
self._element.values.preferred_spawn_groups = nil
end
end
end
|
local m = {}
local meshFormat = {{'lovrPosition', 'float', 3},
{'lovrNormal', 'float', 3}}
-- note that texcoord (UV mapping) is missing, currently not implemented
local function listappend(t1, t2) -- mutates t1 in place
for i,v in ipairs(t2) do table.insert(t1, v) end
return t1
end
-- usage example for laying upright meshes down:
-- solids.transform(mesh, mat4():rotate(pi/2, 1,0,0))
function m.transform(mesh, m, side)
local tvec3 = vec3()
if side then
for _, vi in ipairs(side) do
local v = {mesh:getVertex(vi)}
v[1], v[2], v[3] = m:mul(tvec3:set(unpack(v))):unpack()
mesh:setVertex(vi, v)
end
else
for vi = 1, mesh:getVertexCount() do
local v = {mesh:getVertex(vi)}
v[1], v[2], v[3] = m:mul(tvec3:set(unpack(v))):unpack()
mesh:setVertex(vi, v)
end
end
return mesh
end
-- solids.map(mesh, function(x,y,z)
-- -- manipulate x,y,z as needed
-- return x, y, z
-- end)
function m.map(mesh, cb)
for vi = 1, mesh:getVertexCount() do
local v = {mesh:getVertex(vi)}
local modified = { cb(unpack(v)) }
mesh:setVertex(vi, modified)
end
end
-- vertices, indices = solids.extract(mesh)
function m.extract(mesh)
local vertices = {}
local indices = mesh:getVertexMap() or {}
for i = 1, mesh:getVertexCount() do
table.insert(vertices, {mesh:getVertex(i)})
end
return vertices, indices
end
function m.copy(mesh)
local vertices, indices = m.extract(mesh)
local meshFormat = mesh:getVertexFormat()
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh
end
function m.subdivide(mesh)
--[[ each ABC triangle generates 4 smaller triangles
B---AB---A
\ /\ /
\/__\/
BC\ /CA
\/
C --]]
local function halfway(p1, p2)
return {(p1[1] + p2[1]) / 2, (p1[2] + p2[2]) / 2, (p1[3] + p2[3]) / 2}
end
local oldvertices, oldindices = m.extract(mesh)
local vertices = {}
local indices = {}
for i = 1, #oldindices, 3 do
local i1, i2, i3 = oldindices[i + 0], oldindices[i + 1], oldindices[i + 2]
local va, vb, vc = oldvertices[i1], oldvertices[i2], oldvertices[i3]
local vab = halfway(va, vb)
local vbc = halfway(vb, vc)
local vca = halfway(vc, va)
listappend(vertices, {va, vab, vca})
listappend(indices, {#vertices - 2, #vertices - 1, #vertices})
listappend(vertices, {vab, vb, vbc})
listappend(indices, {#vertices - 2, #vertices - 1, #vertices})
listappend(vertices, {vbc, vc, vca})
listappend(indices, {#vertices - 2, #vertices - 1, #vertices})
listappend(vertices, {vab, vbc, vca})
listappend(indices, {#vertices - 2, #vertices - 1, #vertices})
end
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh
end
-- merging together two or more meshes
-- solids.merge(meshA, meshB, meshC)
-- merging many meshes
-- solids.merge(solids.empty(), unpack(meshList))
function m.merge(firstMesh, ...)
local vertices, indices = m.extract(firstMesh)
for _, otherMesh in ipairs({...}) do
local moreVertices, moreIndices = m.extract(otherMesh)
local offset = #vertices
listappend(vertices, moreVertices)
for i, index in ipairs(moreIndices) do
table.insert(indices, index + offset)
end
end
local meshFormat = firstMesh:getVertexFormat()
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh
end
function m.toStatic(mesh)
local vertices, indices = m.extract(mesh)
local meshFormat = mesh:getVertexFormat()
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'static', false)
mesh:setVertexMap(indices)
return mesh
end
function m.draw(mesh, ...)
lovr.math.drain()
local pose = mat4(...)
local shader = lovr.graphics.getShader()
lovr.graphics.setLineWidth(2)
lovr.graphics.setShader()
-- wireframe model
lovr.graphics.setColor(0xd35c5c)
lovr.graphics.setWireframe(true)
mesh:draw(pose)
lovr.graphics.setWireframe(false)
-- vertex normals - direct representation
lovr.graphics.setColor(0x606060)
local tvec3 = vec3()
local tmat4 = mat4()
for i = 1, mesh:getVertexCount() do
local v = {mesh:getVertex(i)}
local position = pose:mul(tvec3:set(v[1], v[2], v[3]))
local normal = tvec3:set(v[4], v[5], v[6])
lovr.graphics.line(position, normal:mul(0.1):add(position))
end
-- face normals - calculated average
lovr.graphics.setColor(0x8D1C1C)
local indices = mesh:getVertexMap()
local position, normal = vec3(), vec3()
for i = 1, #indices, 3 do
local vi1, vi2, vi3 = indices[i], indices[i + 1], indices[i + 2]
local v1 = {mesh:getVertex(vi1)}
local v2 = {mesh:getVertex(vi2)}
local v3 = {mesh:getVertex(vi3)}
position:set( v1[1], v1[2], v1[3])
position:add(tvec3:set(v2[1], v2[2], v2[3]))
position:add(tvec3:set(v3[1], v3[2], v3[3]))
position:mul(1/3)
position = pose:mul(position)
normal:set( v1[4], v1[5], v1[6])
normal:add(tvec3:set(v2[4], v2[5], v2[6]))
normal:add(tvec3:set(v3[4], v3[5], v3[6]))
normal:mul(1/3 * 0.1)
normal = quat(pose):mul(normal):add(position)
lovr.graphics.line(position, normal)
lovr.graphics.plane('fill', tmat4:set(position, tvec3:set(0.05), quat(normal:sub(position):normalize())))
end
lovr.graphics.setShader(shader)
end
function m.updateNormals(mesh)
local indices = mesh:getVertexMap()
if not indices then return end
local normals = {} -- maps vertex index to list of normals of adjacent faces
local v1, v2, v3 = vec3(), vec3(), vec3()
for i = 1, #indices, 3 do
local vi1, vi2, vi3 = indices[i], indices[i + 1], indices[i + 2]
v1:set(mesh:getVertex(vi1))
v2:set(mesh:getVertex(vi2))
v3:set(mesh:getVertex(vi3))
local fnormal = {v2:sub(v1):cross(v3:sub(v1)):normalize():unpack()}
normals[vi1] = normals[vi1] or {}
normals[vi2] = normals[vi2] or {}
normals[vi3] = normals[vi3] or {}
table.insert(normals[vi1], fnormal)
table.insert(normals[vi2], fnormal)
table.insert(normals[vi3], fnormal)
end
local vnormal, tvec3 = vec3(), vec3()
for i = 1, mesh:getVertexCount() do
assert(normals[i], 'no triangle in index list contains vertex ' .. i)
vnormal:set(0,0,0)
local c = 0
for _, fnormal in ipairs(normals[i]) do
vnormal:add(tvec3:set(unpack(fnormal)))
c = c + 1
end
vnormal:mul(1 / c)
local v = {mesh:getVertex(i)}
v[4], v[5], v[6] = vnormal:normalize():unpack()
mesh:setVertex(i, v)
end
return mesh
end
function m.empty()
local mesh = lovr.graphics.newMesh(meshFormat, {}, 'triangles', 'dynamic', true)
mesh:setVertexMap({})
return mesh
end
function m.quad(subdivisions)
local size = 1 / math.floor(subdivisions or 1)
local vertices = {}
local indices = {}
local epsilon = 1e-6
for y = -0.5, 0.5 - epsilon, size do
for x = -0.5, 0.5 - epsilon, size do
table.insert(vertices, {x, y, 0})
table.insert(vertices, {x, y + size, 0})
table.insert(vertices, {x + size, y, 0})
table.insert(vertices, {x + size, y + size, 0})
listappend(indices, {#vertices - 3, #vertices - 2, #vertices - 1})
listappend(indices, {#vertices - 2, #vertices - 0, #vertices - 1})
end
end
local mesh = lovr.graphics.newMesh(meshFormat, vertices, "triangles", "dynamic", true)
mesh:setVertexMap(indices)
return mesh, {}
end
function m.cube()
local s = 0.5
local vertices = {
{-s, -s, -s}, {-s, s, -s}, { s, -s, -s}, { s, s, -s}, -- front
{ s, s, -s}, { s, s, s}, { s, -s, -s}, { s, -s, s}, -- right
{ s, -s, s}, { s, s, s}, {-s, -s, s}, {-s, s, s}, -- back
{-s, s, s}, {-s, s, -s}, {-s, -s, s}, {-s, -s, -s}, -- left
{-s, -s, -s}, { s, -s, -s}, {-s, -s, s}, { s, -s, s}, -- bottom
{-s, s, -s}, {-s, s, s}, { s, s, -s}, { s, s, s}, -- top
}
local indices = {
1, 2, 3, 3, 2, 4, -- front
5, 6, 7, 7, 6, 8, -- top
9, 10, 11, 11, 10, 12, -- back
13, 14, 15, 15, 14, 16, -- bottom
17, 18, 19, 19, 18, 20, -- left
21, 22, 23, 23, 22, 24 -- right
}
local sides = {
right = {3, 4, 5, 6, 7, 8, 9, 10, 18, 20, 23, 24},
bottom = {1, 3, 7, 8, 9, 11, 15, 16, 17, 18, 19, 20},
back = {6, 8, 9, 10, 11, 12, 13, 15, 19, 20, 22, 24},
top = {2, 4, 5, 6, 10, 12, 13, 14, 21, 22, 23, 24},
front = {1, 2, 3, 4, 5, 7, 14, 16, 17, 18, 21, 23},
left = {1, 2, 11, 12, 13, 14, 15, 16, 17, 19, 21, 22},
}
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh, sides
end
function m.cubetrunc(slant) -- truncated cube AKA rhombicuboctahedron
slant = slant or 0.8
slant = math.min(math.max(slant, 0), 1)
local s, l = 0.5, 0.5 + 0.5 * math.sqrt(2)
local s, l = slant * 0.5, 0.5
local vertices = {
{-s, -l, s}, {-s, -s, l}, {-l, -s, s}, {-s, s, l},
{-s, l, s}, {-l, s, s}, {-s, -l, -s}, {-l, -s, -s},
{-s, -s, -l}, {-s, l, -s}, {-s, s, -l}, {-l, s, -s},
{ s, -l, s}, { l, -s, s}, { s, -s, l}, { s, l, s},
{ s, s, l}, { l, s, s}, { s, -l, -s}, { s, -s, -l},
{ l, -s, -s}, { s, l, -s}, { l, s, -s}, { s, s, -l},
}
local indices = {
15, 4, 2, 21, 18, 14, 22, 5, 16, 3, 12, 8,
9, 24, 20, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 7, 3, 8, 2, 6, 3, 5, 12, 6,
11, 8, 12, 19, 9, 20, 10, 24, 11, 23, 20, 24,
13, 21, 14, 22, 18, 23, 17, 14, 18, 1, 15, 2,
16, 4, 17, 7, 13, 1, 15, 17, 4, 21, 23, 18,
22, 10, 5, 3, 6, 12, 9, 11, 24, 7, 1, 3,
2, 4, 6, 5, 10, 12, 11, 9, 8, 19, 7, 9,
10, 22, 24, 23, 21, 20, 13, 19, 21, 22, 16, 18,
17, 15, 14, 1, 13, 15, 16, 5, 4, 7, 19, 13,
}
local sides = {
right = {13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24},
bottom = { 1, 2, 3, 7, 8, 9, 13, 14, 15, 19, 20, 21},
back = { 1, 2, 3, 4, 5, 6, 13, 14, 15, 16, 17, 18},
top = { 4, 5, 6, 10, 11, 12, 16, 17, 18, 22, 23, 24},
front = { 7, 8, 9, 10, 11, 12, 19, 20, 21, 22, 23, 24},
left = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
}
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh, sides
end
function m.bipyramid(segments)
segments = segments or 4
local vertices = {}
local indices = {}
local sides = {top={}, bottom={}, ring={}}
for i = 0, segments - 1 do
-- top half
table.insert(vertices, {0, 0.5, 0})
table.insert(sides.top, #vertices)
local theta = i * (2 * math.pi) / segments
local x = 0.5 * math.cos(theta)
local z = 0.5 * math.sin(theta)
table.insert(vertices, {x, 0, z})
table.insert(sides.ring, #vertices)
local theta = (i + 1) * (2 * math.pi) / segments
local x = 0.5 * math.cos(theta)
local z = 0.5 * math.sin(theta)
table.insert(vertices, {x, 0, z})
table.insert(sides.ring, #vertices)
listappend(indices, {#vertices, #vertices - 1, #vertices - 2})
-- bottom half
table.insert(vertices, {0, -0.5, 0})
table.insert(sides.bottom, #vertices)
local theta = i * (2 * math.pi) / segments
local x = 0.5 * math.cos(theta)
local z = 0.5 * math.sin(theta)
table.insert(vertices, {x, 0, z})
table.insert(sides.ring, #vertices)
local theta = (i + 1) * (2 * math.pi) / segments
local x = 0.5 * math.cos(theta)
local z = 0.5 * math.sin(theta)
table.insert(vertices, {x, 0, z})
table.insert(sides.ring, #vertices)
listappend(indices, {#vertices, #vertices - 2, #vertices - 1})
end
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh, sides
end
function m.pyramid(segments)
local mesh, sides = m.bipyramid(segments)
m.transform(mesh, mat4(0, -0.5, 0), sides.ring)
listappend(sides.bottom, sides.ring)
return mesh, sides
end
function m.cylinder(segments)
segments = segments or 6
local vertices = {}
local indices = {}
local sides = {top={}, bottom={}, ring={}}
local vTop = segments * 8 + 1
local vBottom = segments * 8 + 2
for i = 0, segments - 1 do
-- ring
local theta, v1, v2, v3, v4, vi1, vi2, vi3, vi4
theta = i * (2 * math.pi) / segments;
v1 = {0.5 * math.cos(theta), -0.5, 0.5 * math.sin(theta)}
v2 = {0.5 * math.cos(theta), 0.5, 0.5 * math.sin(theta)}
theta = (i + 1) * (2 * math.pi) / segments;
v3 = {0.5 * math.cos(theta), -0.5, 0.5 * math.sin(theta)}
v4 = {0.5 * math.cos(theta), 0.5, 0.5 * math.sin(theta)}
table.insert(vertices, v1)
table.insert(sides.bottom, #vertices)
table.insert(vertices, v2)
table.insert(sides.top, #vertices)
table.insert(vertices, v3)
table.insert(sides.bottom, #vertices)
table.insert(vertices, v4)
table.insert(sides.top, #vertices)
vi1, vi2, vi3, vi4 = #vertices-3, #vertices-2, #vertices-1, #vertices
listappend(indices, {vi1, vi2, vi4, vi1, vi4, vi3})
-- top and bottom sides
theta = i * (2 * math.pi) / segments;
v1 = {0.5 * math.cos(theta), -0.5, 0.5 * math.sin(theta)}
v2 = {0.5 * math.cos(theta), 0.5, 0.5 * math.sin(theta)}
theta = (i + 1) * (2 * math.pi) / segments;
v3 = {0.5 * math.cos(theta), -0.5, 0.5 * math.sin(theta)}
v4 = {0.5 * math.cos(theta), 0.5, 0.5 * math.sin(theta)}
table.insert(vertices, v1)
table.insert(sides.bottom, #vertices)
table.insert(vertices, v2)
table.insert(sides.top, #vertices)
table.insert(vertices, v3)
table.insert(sides.bottom, #vertices)
table.insert(vertices, v4)
table.insert(sides.top, #vertices)
vi1, vi2, vi3, vi4 = #vertices-3, #vertices-2, #vertices-1, #vertices
listappend(indices, {vTop, vi4, vi2, vBottom, vi1, vi3})
end
table.insert(vertices, {0, 0.5, 0})
table.insert(sides.top, #vertices)
assert(vTop, #vertices)
table.insert(vertices, {0, -0.5, 0})
table.insert(sides.bottom, #vertices)
assert(vBottom, #vertices)
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh, sides
end
-- lovr-icosphere v0.0.1
-- https://github.com/bjornbytes/lovr-icosphere
-- MIT License
function m.sphere(subdivisions)
subdivisions = subdivisions or 2
local phi = (1 + math.sqrt(5)) / 2
local vertices = {
{ -1, phi, 0 },
{ 1, phi, 0 },
{ -1, -phi, 0 },
{ 1, -phi, 0 },
{ 0, -1, phi },
{ 0, 1, phi },
{ 0, -1, -phi },
{ 0, 1, -phi },
{ phi, 0, -1 },
{ phi, 0, 1 },
{ -phi, 0, -1 },
{ -phi, 0, 1 }
}
local indices = {
1, 12, 6, 1, 6, 2, 1, 2, 8, 1, 8, 11, 1, 11, 12,
2, 6, 10, 6, 12, 5, 12, 11, 3, 11, 8, 7, 8, 2, 9,
4, 10, 5, 4, 5, 3, 4, 3, 7, 4, 7, 9, 4, 9, 10,
5, 10, 6, 3, 5, 12, 7, 3, 11, 9, 7, 8, 10, 9, 2
}
-- Cache vertex splits to avoid duplicates
local splits = {}
-- Splits vertices i and j, creating a new vertex and returning the index
local function split(i, j)
local key = i < j and (i .. ',' .. j) or (j .. ',' .. i)
if not splits[key] then
local x = (vertices[i][1] + vertices[j][1]) / 2
local y = (vertices[i][2] + vertices[j][2]) / 2
local z = (vertices[i][3] + vertices[j][3]) / 2
table.insert(vertices, { x, y, z })
splits[key] = #vertices
end
return splits[key]
end
-- Subdivide
for _ = 1, subdivisions do
for i = #indices, 1, -3 do
local v1, v2, v3 = indices[i - 2], indices[i - 1], indices[i - 0]
local a = split(v1, v2)
local b = split(v2, v3)
local c = split(v3, v1)
table.insert(indices, v1)
table.insert(indices, a)
table.insert(indices, c)
table.insert(indices, v2)
table.insert(indices, b)
table.insert(indices, a)
table.insert(indices, v3)
table.insert(indices, c)
table.insert(indices, b)
table.insert(indices, a)
table.insert(indices, b)
table.insert(indices, c)
table.remove(indices, i - 0)
table.remove(indices, i - 1)
table.remove(indices, i - 2)
end
end
-- Normalize
for i, v in ipairs(vertices) do
local x, y, z = unpack(v)
local length = math.sqrt(x * x + y * y + z * z) * 2
v[1], v[2], v[3] = x / length, y / length, z / length
end
local mesh = lovr.graphics.newMesh(meshFormat, vertices, 'triangles', 'dynamic', true)
mesh:setVertexMap(indices)
return mesh, {}
end
return m
|
att.PrintName = "Hunter FLIR (2-5x)"
att.Icon = Material("entities/acwatt_optic_hunterflir.png")
att.Description = "Adjustable medium-long range sniper optic with a FLIR vision device attached."
att.SortOrder = 4
att.Desc_Pros = {
"Precision sight picture",
"Increased zoom",
"Thermal vision",
}
att.Desc_Cons = {
}
att.AutoStats = true
att.Slot = "optic_sniper"
att.Model = "models/weapons/arccw/atts/hunter.mdl"
att.AdditionalSights = {
{
Pos = Vector(0, 20, -1.055),
Ang = Angle(0, 0, 0),
Magnification = 2.25,
ScrollFunc = ArcCW.SCROLL_ZOOM,
ZoomLevels = 6,
ZoomSound = "weapons/arccw/fiveseven/fiveseven_slideback.wav",
Thermal = true,
IgnoreExtra = true
}
}
att.ScopeGlint = true
att.Holosight = true
att.HolosightReticle = Material("hud/scopes/duplex.png")
att.HolosightNoFlare = true
att.HolosightSize = 14
att.HolosightBone = "holosight"
att.HolosightPiece = "models/weapons/arccw/atts/hunter_hsp.mdl"
att.Colorable = true
att.HolosightMagnification = 3
att.HolosightBlackbox = true
att.HolosightMagnificationMin = 2
att.HolosightMagnificationMax = 5
att.Mult_SightTime = 1.30
att.Mult_SightedSpeedMult = 0.9
att.Mult_SpeedMult = 0.96 |
--[[
Collections.lua
This file contains a few collection classes that are
useful for many things. The most basic object is the
simple list.
From the list is implemented a queue
--]]
local setmetatable = setmetatable;
--[[
A bag behaves similar to a dictionary.
You can add values to it using simple array indexing
You can also retrieve values based on array indexing
The one addition is the '#' length operator works
--]]
local Bag = {}
setmetatable(Bag, {
__call = function(self, ...)
return self:_new(...);
end,
})
local Bag_mt = {
__index = function(self, key)
--print("__index: ", key)
return self.tbl[key]
end,
__newindex = function(self, key, value)
--print("__newindex: ", key, value)
if value == nil then
self.__Count = self.__Count - 1;
else
self.__Count = self.__Count + 1;
end
--rawset(self, key, value)
self.tbl[key] = value;
end,
__len = function(self)
-- print("__len: ", self.__Count)
return self.__Count;
end,
__pairs = function(self)
return pairs(self.tbl)
end,
}
function Bag._new(self, obj)
local obj = {
tbl = {},
__Count = 0,
}
setmetatable(obj, Bag_mt);
return obj;
end
-- The basic list type
-- This will be used to implement queues and other things
local List = {}
local List_mt = {
__index = List;
}
function List.new(params)
local obj = params or {first=0, last=-1}
setmetatable(obj, List_mt)
return obj
end
function List:PushLeft (value)
local first = self.first - 1
self.first = first
self[first] = value
end
function List:PushRight(value)
local last = self.last + 1
self.last = last
self[last] = value
end
function List:PopLeft()
local first = self.first
if first > self.last then
return nil, "list is empty"
end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
function List:PopRight()
local last = self.last
if self.first > last then
return nil, "list is empty"
end
local value = self[last]
self[last] = nil -- to allow garbage collection
self.last = last - 1
return value
end
--[[
Stack
--]]
local Stack = {}
setmetatable(Stack,{
__call = function(self, ...)
return self:new(...);
end,
});
local Stack_mt = {
__len = function(self)
return self.Impl.last - self.Impl.first+1
end,
__index = Stack;
}
Stack.new = function(self, ...)
local obj = {
Impl = List.new();
}
setmetatable(obj, Stack_mt);
return obj;
end
Stack.len = function(self)
return self.Impl.last - self.Impl.first+1
end
Stack.push = function(self, item)
return self.Impl:PushRight(item);
end
Stack.pop = function(self)
return self.Impl:PopRight();
end
--[[
Queue
--]]
local Queue = {}
setmetatable(Queue, {
__call = function(self, ...)
return self:create(...);
end,
});
local Queue_mt = {
__index = Queue;
}
Queue.init = function(self, first, last, name)
first = first or 1;
last = last or 0;
local obj = {
first=first,
last=last,
name=name};
setmetatable(obj, Queue_mt);
return obj
end
Queue.create = function(self, first, last, name)
first = first or 1
last = last or 0
return self:init(first, last, name);
end
--[[
function Queue.new(name)
return Queue:init(1, 0, name);
end
--]]
function Queue:enqueue(value)
--self.MyList:PushRight(value)
local last = self.last + 1
self.last = last
self[last] = value
return value
end
function Queue:pushFront(value)
-- PushLeft
local first = self.first - 1;
self.first = first;
self[first] = value;
end
function Queue:dequeue(value)
-- return self.MyList:PopLeft()
local first = self.first
if first > self.last then
return nil, "list is empty"
end
local value = self[first]
self[first] = nil -- to allow garbage collection
self.first = first + 1
return value
end
function Queue:length()
return self.last - self.first+1
end
-- Returns an iterator over all the current
-- values in the queue
function Queue:Entries(func, param)
local starting = self.first-1;
local len = self:length();
local closure = function()
starting = starting + 1;
return self[starting];
end
return closure;
end
Queue.Enqueue = Queue.enqueue;
Queue.Dequeue = Queue.dequeue;
Queue.Len = Queue.length;
return {
Bag = Bag;
List = List;
Queue = Queue;
Stack = Stack;
}
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remotes = ReplicatedStorage.Remotes
local Profile = require(ReplicatedStorage.Profile)
local profile = Profile.Deserialize(remotes.GetProfile:InvokeServer())
return profile |
Game.ImportLibrary("gui/scripts/Menu.lua")
MainMenu = class.New(Menu, function(_ARG_0_, _ARG_1_)
Menu.init(_ARG_0_, _ARG_1_)
end)
function MainMenu.GoToInitScreen(_ARG_0_)
_ARG_0_:PopAllItems()
_ARG_0_:PushItemByClassName("MainMenuFrontScreen", {}, false)
end
|
-- gather ingredients
-- go to distillery
-- have still craft moonshine
-- pick it up when its done
-- moonshine gives +str
-- deliver to various saloons
-- deliver to varior homesteads
-- moonshine cart is robbable by other players |
object_tangible_food_generic_drink_kylessian_fruit_distillate = object_tangible_food_generic_shared_drink_kylessian_fruit_distillate:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_drink_kylessian_fruit_distillate, "object/tangible/food/generic/drink_kylessian_fruit_distillate.iff")
|
function onUpdate()
if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.SEVEN') then
endSong();
end
end
--THANKS AGAIN L'Étranger#9279 YOU FUCKING LEGEND |
---
-- RegionHandler.client.lua - Handling for region changed popup
--
local popup = script.Parent.Parent.MainGui.RegionPopup
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TweenService = game:GetService("TweenService")
local tweenInfo = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
local currentTween
ReplicatedStorage.UIEvents.RegionChanged.Event:Connect(function(rg)
if currentTween then
currentTween:Cancel()
end
popup.AnchorPoint = Vector2.new(0.5, 1)
popup.Text.Text = "Region Changed: " .. rg.Name
popup.Visible = true
currentTween = TweenService:Create(popup, tweenInfo, { AnchorPoint = Vector2.new(0.5, 0) })
currentTween:Play()
currentTween.Completed:Wait()
local tween2 = TweenService:Create(popup, tweenInfo, { AnchorPoint = Vector2.new(0.5, 1) })
currentTween = tween2
wait(2)
if currentTween ~= tween2 then
return
end
tween2:Play()
if tween2.Completed:Wait() == Enum.PlaybackState.Completed then
popup.Visible = false
end
end)
|
object_static_structure_content_meatlump_sewer_pipe_multi_elbow_s01 = object_static_structure_content_meatlump_shared_sewer_pipe_multi_elbow_s01:new {
}
ObjectTemplates:addTemplate(object_static_structure_content_meatlump_sewer_pipe_multi_elbow_s01, "object/static/structure/content/meatlump/sewer_pipe_multi_elbow_s01.iff")
|
local L = BigWigs:NewBossLocale("Freehold Trash", "koKR")
if not L then return end
if L then
-- L.sharkbait = "Sharkbait"
-- L.enforcer = "Irontide Enforcer"
-- L.bonesaw = "Irontide Bonesaw"
-- L.crackshot = "Irontide Crackshot"
-- L.corsair = "Irontide Corsair"
-- L.duelist = "Cutwater Duelist"
-- L.oarsman = "Irontide Oarsman"
-- L.juggler = "Cutwater Knife Juggler"
-- L.scrapper = "Blacktooth Scrapper"
-- L.knuckleduster = "Blacktooth Knuckleduster"
-- L.swabby = "Bilge Rat Swabby"
-- L.trapper = "Vermin Trapper"
-- L.rat_buccaneer = "Bilge Rat Buccaneer"
-- L.padfoot = "Bilge Rat Padfoot"
-- L.rat = "Soggy Shiprat"
-- L.crusher = "Irontide Crusher"
-- L.buccaneer = "Irontide Buccaneer"
-- L.ravager = "Irontide Ravager"
-- L.officer = "Irontide Officer"
-- L.stormcaller = "Irontide Stormcaller"
end
L = BigWigs:NewBossLocale("Council o' Captains", "koKR")
if L then
--L.crit_brew = "Crit Brew"
--L.haste_brew = "Haste Brew"
--L.bad_brew = "Bad Brew"
end
L = BigWigs:NewBossLocale("Ring of Booty", "koKR")
if L then
L.custom_on_autotalk = "자동 대화"
L.custom_on_autotalk_desc = "전투를 시작하는 대화 선택지를 즉시 선택합니다."
-- Gather 'round and place yer bets! We got a new set of vict-- uh... competitors! Take it away, Gurgthok and Wodin!
-- L.lightning_warmup = "new set of vict--"
-- It's a greased up pig? I'm beginning to think this is not a professional setup. Oh well... grab the pig and you win
-- L.lightning_warmup_2 = "not a professional setup"
L.lightning = "번개돼지"
-- L.lightning_caught = "Lightning caught after %.1f seconds!"
L.ludwig = "루드비히 폰 토르톨란"
L.trothak = "트로삭"
end
|
arrowTable = arrowTable or {}
--[[Author: Pizzalol
Date: 04.01.2015.
Initializes the caster location for the arrow stun and damage calculation]]
function LaunchArrow( keys )
local caster = keys.caster
local caster_location = caster:GetAbsOrigin()
arrowTable[caster] = arrowTable[caster] or {}
arrowTable[caster].location = caster_location
end
--[[Author: Pizzalol
Date: 04.01.2015.
Changed: 06.01.2015.
Calculates the distance traveled by the arrow, then applies damage and stun according to calculations
Provides vision of the area upon impact]]
function ArrowHit( keys )
local caster = keys.caster
local target = keys.target
local target_location = target:GetAbsOrigin()
local ability = keys.ability
local ability_damage = ability:GetAbilityDamage()
-- Vision
local vision_radius = ability:GetLevelSpecialValueFor("arrow_vision", (ability:GetLevel() - 1))
local vision_duration = ability:GetLevelSpecialValueFor("vision_duration", (ability:GetLevel() - 1))
ability:CreateVisibilityNode(target_location, vision_radius, vision_duration)
-- Initializing the damage table
local damage_table = {}
damage_table.attacker = caster
damage_table.victim = target
damage_table.damage_type = ability:GetAbilityDamageType()
damage_table.ability = ability
-- Arrow
local arrow_max_stunrange = ability:GetLevelSpecialValueFor("arrow_max_stunrange", (ability:GetLevel() - 1))
local arrow_max_damagerange = ability:GetLevelSpecialValueFor("arrow_max_damagerange", (ability:GetLevel() - 1))
local arrow_min_stun = ability:GetLevelSpecialValueFor("arrow_min_stun", (ability:GetLevel() - 1))
local arrow_max_stun = ability:GetLevelSpecialValueFor("arrow_max_stun", (ability:GetLevel() - 1))
local arrow_bonus_damage = ability:GetLevelSpecialValueFor("arrow_bonus_damage", (ability:GetLevel() - 1))
-- Stun and damage per distance
local stun_per_30 = arrow_max_stun/(arrow_max_stunrange*0.033)
local damage_per_30 = arrow_bonus_damage/(arrow_max_damagerange*0.033)
local arrow_stun_duration
local arrow_damage
local distance = (target_location - arrowTable[caster].location):Length2D()
-- Stun
if distance < arrow_max_stunrange then
arrow_stun_duration = distance*0.033*stun_per_30 + arrow_min_stun
else
arrow_stun_duration = arrow_max_stun
end
-- Damage
if distance < arrow_max_damagerange then
arrow_damage = distance*0.033*damage_per_30 + ability_damage
else
arrow_damage = ability_damage + arrow_bonus_damage
end
target:AddNewModifier(caster, nil, "modifier_stunned", {duration = arrow_stun_duration})
damage_table.damage = arrow_damage
ApplyDamage(damage_table)
end |
--[[---------------------------------------------------------
Super Cooking Panic for Garry's Mod
by Xperidia (2020)
-----------------------------------------------------------]]
--[[---------------------------------------------------------
Name: gamemode:CookingPotHaloListThink()
Desc: Make halo ready tables for GM:CookingPotHalo()
-----------------------------------------------------------]]
function GM:CookingPotHaloListThink()
local ply = LocalPlayer()
if not IsValid(ply) then return end
local plyTeam = ply:Team()
local cooking_pots_halos = {}
local cooking_pots_halos_look = {}
for _, v in pairs( ents.FindByClass("scookp_cooking_pot") ) do
local vteam = v:Team()
if not cooking_pots_halos[vteam] then
cooking_pots_halos[vteam] = {}
end
if v == self:EntityLookedAt() and plyTeam == vteam then
table.insert(cooking_pots_halos_look, v)
else
table.insert(cooking_pots_halos[vteam], v)
end
end
self._cooking_pots_halos = cooking_pots_halos
self._cooking_pots_halos_look = cooking_pots_halos_look
end
--[[---------------------------------------------------------
Name: gamemode:CookingPotHalo()
Desc: Renders an halo around every 'cooking pot' entity
The color matches the entity's team
At range of use the halo is stronger
-----------------------------------------------------------]]
function GM:CookingPotHalo()
if not self._cooking_pots_halos then return end
local ply = LocalPlayer()
local plyTeam = ply:Team()
for k, v in pairs(self._cooking_pots_halos) do
halo.Add(v, team.GetColor(k), 2, 2, 1, true, plyTeam == k or plyTeam == TEAM_SPECTATOR)
end
if not self._cooking_pots_halos_look then return end
halo.Add(self._cooking_pots_halos_look, team.GetColor(k), 2, 2, 1, true, true)
end
--[[---------------------------------------------------------
Name: gamemode:SetCookingPotHalo()
Desc: Renders an halo around the mouse over entity
-----------------------------------------------------------]]
function GM:MouseOverHalo()
local ent = self:EntityLookedAt()
if not IsValid(ent) or not ent:IsIngredient() then
return
end
halo.Add({ent}, self:GetTeamColor(ent), 2, 2, 1, true, true)
end
--[[---------------------------------------------------------
Name: entity:DrawTip(str, offset)
Desc: Draw tip on entity
-----------------------------------------------------------]]
function GM.EntityMeta:DrawTip(str, offset)
-- Get the game's camera angles
local angle = EyeAngles()
-- Only use the Yaw component of the angle
angle = Angle(0, angle.y, 0)
-- Apply some animation to the angle
angle.y = angle.y + math.sin(CurTime()) * 10
-- Correct the angle so it points at the camera
-- This is usually done by trial and error using Up(), Right() and Forward() axes
angle:RotateAroundAxis(angle:Up(), -90)
angle:RotateAroundAxis(angle:Forward(), 90)
local pos = self:GetPos() + (offset or Vector(0, 0, 0))
cam.Start3D2D(pos, angle, 0.1)
local font = "scookp_3D2D"
surface.SetFont(font)
draw.SimpleText(str, font, 0, 0, nil, TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM)
cam.End3D2D()
end
--[[---------------------------------------------------------
Name: gamemode:DrawCookingPotTips()
Desc: Draw the tip for the cooking pot
-----------------------------------------------------------]]
function GM:DrawCookingPotTips(ply)
if not ply:IsHoldingIngredient() then return end
local text = self:FormatLangPhrase( "$scookp_tip_cooking_pot",
self:CheckBind("+attack") )
for _, v in pairs(ents.FindByClass("scookp_cooking_pot")) do
if IsValid(v) and v:Team() == ply:Team() then
v:DrawTip(text, Vector(0, 0, 32))
end
end
end
--[[---------------------------------------------------------
Name: gamemode:DrawGrabTips()
Desc: Grab ingredient tips
-----------------------------------------------------------]]
function GM:DrawGrabTips(ply, ent)
if ply:IsHoldingIngredient() then return end
if not ent:IsIngredient() then return end
local text = self:FormatLangPhrase("$scookp_tip_press_x_to_grab",
self:CheckBind("+attack") )
ent:DrawTip(text, Vector(0, 0, 32))
end
--[[---------------------------------------------------------
Name: gamemode:DrawPowerUPgrabTips()
Desc: Draw the Power-UP grab tips
-----------------------------------------------------------]]
function GM:DrawPowerUPgrabTips(ply, ent)
if ply:HasPowerUP() then return end
if not ent:IsPowerUP() then return end
local text = self:FormatLangPhrase( "$scookp_tip_press_x_to_grab",
self:CheckBind("+use") )
ent:DrawTip(text)
end
--[[---------------------------------------------------------
Name: gamemode:DrawTips()
Desc: Called to draw the tips
-----------------------------------------------------------]]
function GM:DrawTips()
if self:ConVarGetBool("hide_tips") then return end
if not self:IsValidGamerMoment() then return end
local ply = LocalPlayer()
if not ply:IsValidPlayingState() then return end
local ent = self:EntityLookedAt()
self:DrawCookingPotTips(ply)
if not IsValid(ent) then return end
--self:DrawGrabTips(ply, ent)
self:DrawPowerUPgrabTips(ply, ent)
end
--[[---------------------------------------------------------
Name: gamemode:PreDrawHalos()
Desc: Called before rendering the halos.
This is the place to call halo.Add.
-----------------------------------------------------------]]
function GM:PreDrawHalos()
self:CookingPotHalo()
self:MouseOverHalo()
end
--[[---------------------------------------------------------
Name: gamemode:PreDrawOpaqueRenderables()
Desc: Called before drawing opaque entities
-----------------------------------------------------------]]
function GM:PostDrawOpaqueRenderables(bDrawingDepth, bDrawingSkybox)
end
--[[---------------------------------------------------------
Name: gamemode:PostDrawTranslucentRenderables()
Desc: Called after all translucent entities are drawn
-----------------------------------------------------------]]
function GM:PostDrawTranslucentRenderables(bDrawingDepth, bDrawingSkybox)
end
--[[---------------------------------------------------------
Name: gamemode:PreDrawEffects()
Desc: Called just after GM:PreDrawViewModel
-----------------------------------------------------------]]
function GM:PreDrawEffects()
self:DrawTips()
end
|
local K, C = unpack(select(2, ...))
if C["ActionBar"].Enable ~= true then
return
end
local _G = _G
local select = select
local CreateFrame = _G.CreateFrame
local GetActionTexture = _G.GetActionTexture
local HasOverrideActionBar = _G.HasOverrideActionBar
local HasVehicleActionBar = _G.HasVehicleActionBar
local InCombatLockdown = _G.InCombatLockdown
local NUM_ACTIONBAR_BUTTONS = _G.NUM_ACTIONBAR_BUTTONS
local RegisterStateDriver = _G.RegisterStateDriver
local ActionBar1 = CreateFrame("Frame", "Bar1Holder", ActionBarAnchor, "SecureHandlerStateTemplate")
ActionBar1:SetAllPoints(ActionBarAnchor)
for i = 1, NUM_ACTIONBAR_BUTTONS do
local button = _G["ActionButton" .. i]
button:SetSize(C["ActionBar"].ButtonSize, C["ActionBar"].ButtonSize)
button:ClearAllPoints()
button:SetParent(Bar1Holder)
if i == 1 then
button:SetPoint("BOTTOMLEFT", Bar1Holder, 0, 0)
else
local previous = _G["ActionButton" .. i - 1]
button:SetPoint("LEFT", previous, "RIGHT", C["ActionBar"].ButtonSpace, 0)
end
end
local function GetPageDriver()
local driver = "[overridebar]override; [possessbar]possess; [shapeshift]shapeshift; [vehicleui]vehicle; [bar:2]2; [bar:3]3; [bar:4]4; [bar:5]5; [bar:6]6"
if (K.Class == "DRUID") then
if (C["ActionBar"].DisableStancePages) then
driver = driver .. "; [bonusbar:1,nostealth] 7; [bonusbar:1,stealth] 7; [bonusbar:2] 8; [bonusbar:3] 9; [bonusbar:4] 10"
else
driver = driver .. "; [bonusbar:1,nostealth] 7; [bonusbar:1,stealth] 8; [bonusbar:2] 8; [bonusbar:3] 9; [bonusbar:4] 10"
end
elseif (K.Class == "MONK") then
driver = driver .. "; [bonusbar:1] 7; [bonusbar:2] 8; [bonusbar:3] 9"
elseif (K.Class == "PRIEST") then
driver = driver .. "; [bonusbar:1] 7"
elseif (K.Class == "ROGUE") then
driver = driver .. "; [bonusbar:1] 7"
elseif (K.Class == "WARRIOR") then
driver = driver .. "; [bonusbar:1] 7; [bonusbar:2] 8"
end
driver = driver .. "; [form] 1; 1"
return driver
end
ActionBar1:RegisterEvent("PLAYER_LOGIN")
ActionBar1:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR")
ActionBar1:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR")
ActionBar1:SetScript("OnEvent", function(self, event)
if event == "PLAYER_LOGIN" then
for i = 1, NUM_ACTIONBAR_BUTTONS do
local button = _G["ActionButton" .. i]
self:SetFrameRef("ActionButton" .. i, button)
end
self:Execute([[
buttons = table.new()
for i = 1, 12 do
table.insert(buttons, self:GetFrameRef("ActionButton"..i))
end
]])
-- Note that the functions meant to check for the various types of bars
-- sometimes will return 'false' directly after a page change, when they should be 'true'.
-- No idea as to why this randomly happens, but the macro driver at least responds correctly,
-- and the bar index can still be retrieved correctly, so for now we just skip the checks.
--
-- Affected functions, which we choose to avoid/work around here:
-- HasVehicleActionBar()
-- HasOverrideActionBar()
-- HasTempShapeshiftActionBar()
-- HasBonusActionBar()
self:SetAttribute("_onstate-page", [[
local page;
if (newstate == "vehicle")
or (newstate == "override")
or (newstate == "shapeshift")
or (newstate == "possess")
or (newstate == "11") then
if (newstate == "vehicle") then
page = GetVehicleBarIndex();
elseif (newstate == "override") then
page = GetOverrideBarIndex();
elseif (newstate == "shapeshift") then
page = GetTempShapeshiftBarIndex();
elseif HasBonusActionBar() and (GetActionBarPage() == 1) then
page = GetBonusBarIndex();
else
page = 12;
end
end
if page then
newstate = page;
end
for i, button in ipairs(buttons) do
button:SetAttribute("actionpage", tonumber(newstate))
end
]])
RegisterStateDriver(self, "page", GetPageDriver())
elseif (event == "UPDATE_VEHICLE_ACTIONBAR") or (event == "UPDATE_OVERRIDE_ACTIONBAR") then
if not InCombatLockdown() and (HasVehicleActionBar() or HasOverrideActionBar()) then
for i = 1, NUM_ACTIONBAR_BUTTONS do
local button = _G["ActionButton" .. i]
local action = button.action
local icon = button.icon
if action >= 120 then
local texture = GetActionTexture(action)
if (texture) then
icon:SetTexture(texture)
icon:Show()
else
if icon:IsShown() then
icon:Hide()
end
end
end
end
end
end
end) |
--[[
测试函数返回值个数
--]]
function foo2()
return 1,2
end
--[[
x,y,z = foo2(),4
print(x..y..z) -- 此时z为nil
--]]
x,y,z = foo2(),3,4
print(x..y..z) -- 此时输出1,3,4
print("1111111")
local a = 0
while 1 do
print(string.format("%d", a))
a = a + 1
end
|
local function onTextMessageEvent(serverConnectionHandlerID, targetMode, toID, fromID, fromName, fromUniqueIdentifier, message, ffIgnored)
return receiveMessage(serverConnectionHandlerID, fromID, fromName, fromUniqueIdentifier, message)
end
local function onClientPokeEvent(serverConnectionHandlerID, pokerID, pokerName, message, ffIgnored)
return receiveMessage(serverConnectionHandlerID, pokerID, pokerName, "", message)
end
function receiveMessage(serverConnectionHandlerID, fromID, fromName, fromUniqueIdentifier, message)
local retVal = 0
local exploitAlert
for i = 1, #message do
local c = string.byte(message, i)
--print(i .. ":" .. c)
if c == 225 then
retVal = 1
exploitAlert = "sent you an unsupported character may cause a client crash."
break
end
end
if retVal == 1 then
if string.len(fromUniqueIdentifier) == 0 then
fromUniqueIdentifier, error = ts3.getClientVariableAsString(serverConnectionHandlerID, fromID, ts3defs.ClientProperties.CLIENT_UNIQUE_IDENTIFIER)
-- if (error ~= ts3errors.ERROR_ok)
-- fromUniqueIdentifier = ""
-- end
end
local clientUrlOrName
if string.len(fromUniqueIdentifier) ~= 0 then
clientUrlOrName = "[URL=client://" .. fromID .. "/" .. fromUniqueIdentifier .. "~]" .. fromName .. "[/URL]"
else
clientUrlOrName = fromName
end
ts3.printMessageToCurrentTab("[color=purple][i]PreventCrash6966 by Energeek/Boumz[/i] :[/color] [b][color=red]" .. clientUrlOrName .. "[/color] [color=grey]" .. exploitAlert .. "[/color][/b]")
end
return retVal
end
preventcrash6966_events = {
onTextMessageEvent = onTextMessageEvent,
onClientPokeEvent = onClientPokeEvent,
}
|
local listURL = "https://raw.githubusercontent.com/TxN/MC-WarpMaster/master/Installer/FileList.cfg"
local errorFlag = false
local c = require("component")
local term = require("term")
local filesystem = require("filesystem")
local x,y = c.gpu.maxResolution()
c.gpu.setResolution(x,y)
c.gpu.fill(1, 1, x, y, " ")
c.gpu.setForeground(0xFFFFFF)
c.gpu.setBackground(0x000000)
term.setCursor(1,1)
print("---- WarpMaster app installer ----")
print(" ")
if filesystem.exists("/lib/ECSAPI.lua") == false then
print("Error!")
print("Could not find MineOS libraries.")
print("Please install MineOS first.")
print("---")
errorFlag = true
end
if c.isAvailable("internet") == false then
print("Error!")
print("Internet card is not installed.")
print("Internet is required to install WarpMaster.")
print("---")
errorFlag = true
end
local libraries = {
ecs = "ECSAPI",
event = "event",
computer = "computer",
serialization = "serialization"
}
if errorFlag == false then
for library in pairs(libraries) do if not _G[library] then _G[library] = require(libraries[library]) end end; libraries = nil
end
local function Download()
local success, response = ecs.internetRequest(listURL)
print("Getting file list...")
if success == false then
return false
end
local fileData = serialization.unserialize(response)
for i=1,#fileData.url do
ecs.getFileFromUrl(fileData.url[i], fileData.path[i])
print("Downloading file " .. i .. " of " .. #fileData.url)
end
return true
end
if errorFlag == false then
print("Downloading WarpMaster...")
if Download() == true then
print("Done!")
print("Now you can run MineOS again. Type 'OS' command in console.")
else
print("Download error.")
end
end
|
local MinersHavenGui = Instance.new("ScreenGui")
local DecoFrame = Instance.new("Frame")
local CratesFrame = Instance.new("Frame")
local Deco = Instance.new("ImageLabel")
local NumberOfBoxes = Instance.new("TextLabel")
local TPCrates = Instance.new("TextButton")
local LoopTPCrates = Instance.new("TextButton")
local Deco_2 = Instance.new("ImageLabel")
local Deco_3 = Instance.new("ImageLabel")
local Deco_4 = Instance.new("ImageLabel")
local Loop = Instance.new("ImageLabel")
local MinesTPFrame = Instance.new("Frame")
local TextLabel = Instance.new("TextLabel")
local AmountToGive = Instance.new("TextBox")
local MineChanButton = Instance.new("ImageButton")
local Deco_5 = Instance.new("TextLabel")
local CloversTwitchCoinsFrame = Instance.new("Frame")
local PlusCloverButton = Instance.new("TextButton")
local PlusTwitchButton = Instance.new("TextButton")
local Toggleable = Instance.new("Frame")
local AutoInfernoBoxFrame = Instance.new("Frame")
local Deco_6 = Instance.new("TextLabel")
local AutoInfernoButton = Instance.new("TextButton")
local AutoRebirthFrame = Instance.new("Frame")
local Deco_7 = Instance.new("TextLabel")
local AutoRebirthButton = Instance.new("TextButton")
local AutoRegularBoxFrame = Instance.new("Frame")
local Deco_8 = Instance.new("TextLabel")
local AutoRegularButton = Instance.new("TextButton")
local AutoUnrealBoxFrame = Instance.new("Frame")
local Deco_9 = Instance.new("TextLabel")
local AutoUnrealButton = Instance.new("TextButton")
local ButtonClickerFrame = Instance.new("Frame")
local Deco_10 = Instance.new("TextLabel")
local ButtonClickerButton = Instance.new("TextButton")
local RemoteClickerFrame = Instance.new("Frame")
local Deco_11 = Instance.new("TextLabel")
local RemoteClickerButton = Instance.new("TextButton")
local AutoLoadoutFrame = Instance.new("Frame")
local Deco_12 = Instance.new("TextLabel")
local AutoLoadout1Button = Instance.new("TextButton")
local NotificationsFrame = Instance.new("Frame")
local Deco_13 = Instance.new("TextLabel")
local NotificationsButton = Instance.new("TextButton")
MinersHavenGui.Name = "MinersHavenGui"
MinersHavenGui.Parent = game.CoreGui
DecoFrame.Name = "DecoFrame"
DecoFrame.Parent = MinersHavenGui
DecoFrame.Active = true
DecoFrame.BackgroundColor3 = Color3.new(1, 1, 1)
DecoFrame.BorderSizePixel = 0
DecoFrame.Draggable = true
DecoFrame.Position = UDim2.new(0.25, 0, 0.25, 0)
DecoFrame.Size = UDim2.new(0.300000012, 0, 0.5, 0)
CratesFrame.Name = "CratesFrame"
CratesFrame.Parent = DecoFrame
CratesFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
CratesFrame.BorderSizePixel = 0
CratesFrame.Position = UDim2.new(0.449999988, 0, 0.100000001, 0)
CratesFrame.Size = UDim2.new(0.5, 0, 0.150000006, 0)
Deco.Name = "Deco"
Deco.Parent = CratesFrame
Deco.BackgroundColor3 = Color3.new(1, 1, 1)
Deco.BackgroundTransparency = 1
Deco.Size = UDim2.new(0.300000012, 0, 1, 0)
Deco.Image = "rbxassetid://853410753"
NumberOfBoxes.Name = "NumberOfBoxes"
NumberOfBoxes.Parent = Deco
NumberOfBoxes.BackgroundColor3 = Color3.new(1, 1, 1)
NumberOfBoxes.BackgroundTransparency = 1
NumberOfBoxes.Size = UDim2.new(1, 0, 1, 0)
NumberOfBoxes.Font = Enum.Font.SciFi
NumberOfBoxes.FontSize = Enum.FontSize.Size24
NumberOfBoxes.Text = "0"
NumberOfBoxes.TextColor3 = Color3.new(1, 1, 1)
NumberOfBoxes.TextSize = 24
NumberOfBoxes.TextStrokeTransparency = 0
NumberOfBoxes.TextWrapped = true
TPCrates.Name = "TPCrates"
TPCrates.Parent = CratesFrame
TPCrates.BackgroundColor3 = Color3.new(0.196078, 0.196078, 0.196078)
TPCrates.BackgroundTransparency = 1
TPCrates.Position = UDim2.new(0.349999994, 0, 0, 0)
TPCrates.Size = UDim2.new(0.300000012, 0, 1, 0)
TPCrates.ZIndex = 2
TPCrates.Font = Enum.Font.SourceSans
TPCrates.FontSize = Enum.FontSize.Size14
TPCrates.Text = "TP Crates"
TPCrates.TextColor3 = Color3.new(1, 1, 1)
TPCrates.TextSize = 14
TPCrates.TextStrokeColor3 = Color3.new(1, 0.976471, 0.976471)
TPCrates.TextWrapped = true
TPCrates.TextYAlignment = Enum.TextYAlignment.Top
LoopTPCrates.Name = "LoopTPCrates"
LoopTPCrates.Parent = CratesFrame
LoopTPCrates.BackgroundColor3 = Color3.new(0.196078, 0.196078, 0.196078)
LoopTPCrates.BackgroundTransparency = 1
LoopTPCrates.Position = UDim2.new(0.699999988, 0, 0, 0)
LoopTPCrates.Size = UDim2.new(0.300000012, 0, 1, 0)
LoopTPCrates.ZIndex = 2
LoopTPCrates.Font = Enum.Font.SourceSans
LoopTPCrates.FontSize = Enum.FontSize.Size14
LoopTPCrates.Text = "Loop TP Crates: OFF"
LoopTPCrates.TextColor3 = Color3.new(1, 1, 1)
LoopTPCrates.TextSize = 14
LoopTPCrates.TextWrapped = true
LoopTPCrates.TextYAlignment = Enum.TextYAlignment.Top
Deco_2.Name = "Deco"
Deco_2.Parent = CratesFrame
Deco_2.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_2.BackgroundTransparency = 1
Deco_2.Position = UDim2.new(0.349999994, 0, 0, 0)
Deco_2.Size = UDim2.new(0.300000012, 0, 1, 0)
Deco_2.Image = "rbxassetid://853410753"
Deco_3.Name = "Deco"
Deco_3.Parent = Deco_2
Deco_3.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_3.BackgroundTransparency = 1
Deco_3.Size = UDim2.new(1, 0, 1, 0)
Deco_3.Image = "rbxassetid://29563831"
Deco_4.Name = "Deco"
Deco_4.Parent = CratesFrame
Deco_4.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_4.BackgroundTransparency = 1
Deco_4.Position = UDim2.new(0.699999988, 0, 0, 0)
Deco_4.Size = UDim2.new(0.300000012, 0, 1, 0)
Deco_4.Image = "rbxassetid://853410753"
Loop.Name = "Loop"
Loop.Parent = Deco_4
Loop.BackgroundColor3 = Color3.new(1, 1, 1)
Loop.BackgroundTransparency = 1
Loop.Size = UDim2.new(1, 0, 1, 0)
Loop.Image = "rbxassetid://169611736"
Loop.ImageColor3 = Color3.new(1, 0, 0)
Loop.ImageTransparency = 0.5
MinesTPFrame.Name = "MinesTPFrame"
MinesTPFrame.Parent = DecoFrame
MinesTPFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
MinesTPFrame.BorderSizePixel = 0
MinesTPFrame.Position = UDim2.new(0.449999988, 0, 0.550000012, 0)
MinesTPFrame.Size = UDim2.new(0.5, 0, 0.400000006, 0)
TextLabel.Parent = MinesTPFrame
TextLabel.BackgroundColor3 = Color3.new(1, 1, 1)
TextLabel.BackgroundTransparency = 1
TextLabel.Size = UDim2.new(0.699999988, 0, 0.300000012, 0)
TextLabel.Font = Enum.Font.Highway
TextLabel.FontSize = Enum.FontSize.Size14
TextLabel.Text = "Amount to give:"
TextLabel.TextColor3 = Color3.new(1, 1, 1)
TextLabel.TextSize = 14
TextLabel.TextWrapped = true
AmountToGive.Name = "AmountToGive"
AmountToGive.Parent = MinesTPFrame
AmountToGive.BackgroundColor3 = Color3.new(1, 1, 1)
AmountToGive.BackgroundTransparency = 1
AmountToGive.Position = UDim2.new(0.699999988, 0, 0, 0)
AmountToGive.Size = UDim2.new(0.300000012, 0, 0.300000012, 0)
AmountToGive.Font = Enum.Font.SourceSans
AmountToGive.FontSize = Enum.FontSize.Size24
AmountToGive.Text = "10"
AmountToGive.TextColor3 = Color3.new(0, 0.886275, 1)
AmountToGive.TextScaled = true
AmountToGive.TextSize = 24
AmountToGive.TextWrapped = true
MineChanButton.Name = "MineChanButton"
MineChanButton.Parent = MinesTPFrame
MineChanButton.BackgroundColor3 = Color3.new(1, 1, 1)
MineChanButton.BorderSizePixel = 0
MineChanButton.Position = UDim2.new(0.330000013, 0, 0.400000006, 0)
MineChanButton.Size = UDim2.new(0.349999994, 0, 0.400000006, 0)
MineChanButton.Image = "rbxassetid://1407000502"
Deco_5.Name = "Deco"
Deco_5.Parent = MineChanButton
Deco_5.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_5.BackgroundTransparency = 1
Deco_5.Size = UDim2.new(1, 0, 0.200000003, 0)
Deco_5.Font = Enum.Font.SourceSans
Deco_5.FontSize = Enum.FontSize.Size14
Deco_5.Text = "Iron Mine-Chan"
Deco_5.TextColor3 = Color3.new(1, 1, 1)
Deco_5.TextScaled = true
Deco_5.TextSize = 14
Deco_5.TextWrapped = true
CloversTwitchCoinsFrame.Name = "CloversTwitchCoinsFrame"
CloversTwitchCoinsFrame.Parent = DecoFrame
CloversTwitchCoinsFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
CloversTwitchCoinsFrame.BorderSizePixel = 0
CloversTwitchCoinsFrame.Position = UDim2.new(0.449999988, 0, 0.349999994, 0)
CloversTwitchCoinsFrame.Size = UDim2.new(0.5, 0, 0.100000001, 0)
PlusCloverButton.Name = "PlusCloverButton"
PlusCloverButton.Parent = CloversTwitchCoinsFrame
PlusCloverButton.BackgroundColor3 = Color3.new(1, 1, 1)
PlusCloverButton.BorderSizePixel = 0
PlusCloverButton.Position = UDim2.new(0.0500000007, 0, 0.100000001, 0)
PlusCloverButton.Size = UDim2.new(0.899999976, 0, 0.400000006, 0)
PlusCloverButton.Font = Enum.Font.SourceSans
PlusCloverButton.FontSize = Enum.FontSize.Size14
PlusCloverButton.Text = "+1 Clover"
PlusCloverButton.TextColor3 = Color3.new(0, 0.294118, 0.0666667)
PlusCloverButton.TextSize = 14
PlusTwitchButton.Name = "PlusTwitchButton"
PlusTwitchButton.Parent = CloversTwitchCoinsFrame
PlusTwitchButton.BackgroundColor3 = Color3.new(1, 1, 1)
PlusTwitchButton.BorderSizePixel = 0
PlusTwitchButton.Position = UDim2.new(0.0500000007, 0, 0.5, 0)
PlusTwitchButton.Size = UDim2.new(0.899999976, 0, 0.400000006, 0)
PlusTwitchButton.Font = Enum.Font.SourceSans
PlusTwitchButton.FontSize = Enum.FontSize.Size14
PlusTwitchButton.Text = "+1 Twitch Coin"
PlusTwitchButton.TextColor3 = Color3.new(0.411765, 0, 0.427451)
PlusTwitchButton.TextSize = 14
Toggleable.Name = "Toggleable"
Toggleable.Parent = DecoFrame
Toggleable.BackgroundColor3 = Color3.new(1, 1, 1)
Toggleable.BackgroundTransparency = 1
Toggleable.Size = UDim2.new(0.400000006, 0, 1, 0)
AutoInfernoBoxFrame.Name = "AutoInfernoBoxFrame"
AutoInfernoBoxFrame.Parent = Toggleable
AutoInfernoBoxFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
AutoInfernoBoxFrame.BorderSizePixel = 0
AutoInfernoBoxFrame.Position = UDim2.new(0.0500000007, 0, 0.600000024, 0)
AutoInfernoBoxFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_6.Name = "Deco"
Deco_6.Parent = AutoInfernoBoxFrame
Deco_6.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_6.BackgroundTransparency = 1
Deco_6.Size = UDim2.new(1, 0, 0.5, 0)
Deco_6.Font = Enum.Font.Highway
Deco_6.FontSize = Enum.FontSize.Size14
Deco_6.Text = "Auto open inferno boxes."
Deco_6.TextColor3 = Color3.new(1, 1, 1)
Deco_6.TextSize = 14
AutoInfernoButton.Name = "AutoInfernoButton"
AutoInfernoButton.Parent = AutoInfernoBoxFrame
AutoInfernoButton.BackgroundColor3 = Color3.new(1, 1, 1)
AutoInfernoButton.BorderSizePixel = 0
AutoInfernoButton.Position = UDim2.new(0.25, 0, 0.5, 0)
AutoInfernoButton.Size = UDim2.new(0.5, 0, 0.5, 0)
AutoInfernoButton.Font = Enum.Font.SourceSans
AutoInfernoButton.FontSize = Enum.FontSize.Size14
AutoInfernoButton.Text = "OFF"
AutoInfernoButton.TextColor3 = Color3.new(1, 0, 0)
AutoInfernoButton.TextSize = 14
AutoRebirthFrame.Name = "AutoRebirthFrame"
AutoRebirthFrame.Parent = Toggleable
AutoRebirthFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
AutoRebirthFrame.BorderSizePixel = 0
AutoRebirthFrame.Position = UDim2.new(0.0500000007, 0, 0.0500000007, 0)
AutoRebirthFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_7.Name = "Deco"
Deco_7.Parent = AutoRebirthFrame
Deco_7.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_7.BackgroundTransparency = 1
Deco_7.Size = UDim2.new(1, 0, 0.5, 0)
Deco_7.Font = Enum.Font.Highway
Deco_7.FontSize = Enum.FontSize.Size14
Deco_7.Text = "Auto rebirth when possible."
Deco_7.TextColor3 = Color3.new(1, 1, 1)
Deco_7.TextSize = 14
AutoRebirthButton.Name = "AutoRebirthButton"
AutoRebirthButton.Parent = AutoRebirthFrame
AutoRebirthButton.BackgroundColor3 = Color3.new(1, 1, 1)
AutoRebirthButton.BorderSizePixel = 0
AutoRebirthButton.Position = UDim2.new(0.25, 0, 0.5, 0)
AutoRebirthButton.Size = UDim2.new(0.5, 0, 0.5, 0)
AutoRebirthButton.Font = Enum.Font.SourceSans
AutoRebirthButton.FontSize = Enum.FontSize.Size14
AutoRebirthButton.Text = "OFF"
AutoRebirthButton.TextColor3 = Color3.new(1, 0, 0)
AutoRebirthButton.TextSize = 14
AutoRegularBoxFrame.Name = "AutoRegularBoxFrame"
AutoRegularBoxFrame.Parent = Toggleable
AutoRegularBoxFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
AutoRegularBoxFrame.BorderSizePixel = 0
AutoRegularBoxFrame.Position = UDim2.new(0.0500000007, 0, 0.400000006, 0)
AutoRegularBoxFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_8.Name = "Deco"
Deco_8.Parent = AutoRegularBoxFrame
Deco_8.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_8.BackgroundTransparency = 1
Deco_8.Size = UDim2.new(1, 0, 0.5, 0)
Deco_8.Font = Enum.Font.Highway
Deco_8.FontSize = Enum.FontSize.Size14
Deco_8.Text = "Auto open regular boxes."
Deco_8.TextColor3 = Color3.new(1, 1, 1)
Deco_8.TextSize = 14
AutoRegularButton.Name = "AutoRegularButton"
AutoRegularButton.Parent = AutoRegularBoxFrame
AutoRegularButton.BackgroundColor3 = Color3.new(1, 1, 1)
AutoRegularButton.BorderSizePixel = 0
AutoRegularButton.Position = UDim2.new(0.25, 0, 0.5, 0)
AutoRegularButton.Size = UDim2.new(0.5, 0, 0.5, 0)
AutoRegularButton.Font = Enum.Font.SourceSans
AutoRegularButton.FontSize = Enum.FontSize.Size14
AutoRegularButton.Text = "OFF"
AutoRegularButton.TextColor3 = Color3.new(1, 0, 0)
AutoRegularButton.TextSize = 14
AutoUnrealBoxFrame.Name = "AutoUnrealBoxFrame"
AutoUnrealBoxFrame.Parent = Toggleable
AutoUnrealBoxFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
AutoUnrealBoxFrame.BorderSizePixel = 0
AutoUnrealBoxFrame.Position = UDim2.new(0.0500000007, 0, 0.5, 0)
AutoUnrealBoxFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_9.Name = "Deco"
Deco_9.Parent = AutoUnrealBoxFrame
Deco_9.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_9.BackgroundTransparency = 1
Deco_9.Size = UDim2.new(1, 0, 0.5, 0)
Deco_9.Font = Enum.Font.Highway
Deco_9.FontSize = Enum.FontSize.Size14
Deco_9.Text = "Auto open unreal boxes."
Deco_9.TextColor3 = Color3.new(1, 1, 1)
Deco_9.TextSize = 14
AutoUnrealButton.Name = "AutoUnrealButton"
AutoUnrealButton.Parent = AutoUnrealBoxFrame
AutoUnrealButton.BackgroundColor3 = Color3.new(1, 1, 1)
AutoUnrealButton.BorderSizePixel = 0
AutoUnrealButton.Position = UDim2.new(0.25, 0, 0.5, 0)
AutoUnrealButton.Size = UDim2.new(0.5, 0, 0.5, 0)
AutoUnrealButton.Font = Enum.Font.SourceSans
AutoUnrealButton.FontSize = Enum.FontSize.Size14
AutoUnrealButton.Text = "OFF"
AutoUnrealButton.TextColor3 = Color3.new(1, 0, 0)
AutoUnrealButton.TextSize = 14
ButtonClickerFrame.Name = "ButtonClickerFrame"
ButtonClickerFrame.Parent = Toggleable
ButtonClickerFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
ButtonClickerFrame.BorderSizePixel = 0
ButtonClickerFrame.Position = UDim2.new(0.0500000007, 0, 0.25, 0)
ButtonClickerFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_10.Name = "Deco"
Deco_10.Parent = ButtonClickerFrame
Deco_10.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_10.BackgroundTransparency = 1
Deco_10.Size = UDim2.new(1, 0, 0.5, 0)
Deco_10.Font = Enum.Font.Highway
Deco_10.FontSize = Enum.FontSize.Size14
Deco_10.Text = "Autoclick the buttons."
Deco_10.TextColor3 = Color3.new(1, 1, 1)
Deco_10.TextSize = 14
ButtonClickerButton.Name = "ButtonClickerButton"
ButtonClickerButton.Parent = ButtonClickerFrame
ButtonClickerButton.BackgroundColor3 = Color3.new(1, 1, 1)
ButtonClickerButton.BorderSizePixel = 0
ButtonClickerButton.Position = UDim2.new(0.25, 0, 0.5, 0)
ButtonClickerButton.Size = UDim2.new(0.5, 0, 0.5, 0)
ButtonClickerButton.Font = Enum.Font.SourceSans
ButtonClickerButton.FontSize = Enum.FontSize.Size14
ButtonClickerButton.Text = "OFF"
ButtonClickerButton.TextColor3 = Color3.new(1, 0, 0)
ButtonClickerButton.TextSize = 14
RemoteClickerFrame.Name = "RemoteClickerFrame"
RemoteClickerFrame.Parent = Toggleable
RemoteClickerFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
RemoteClickerFrame.BorderSizePixel = 0
RemoteClickerFrame.Position = UDim2.new(0.0500000007, 0, 0.150000006, 0)
RemoteClickerFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_11.Name = "Deco"
Deco_11.Parent = RemoteClickerFrame
Deco_11.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_11.BackgroundTransparency = 1
Deco_11.Size = UDim2.new(1, 0, 0.5, 0)
Deco_11.Font = Enum.Font.Highway
Deco_11.FontSize = Enum.FontSize.Size14
Deco_11.Text = "Autoclick the remote."
Deco_11.TextColor3 = Color3.new(1, 1, 1)
Deco_11.TextSize = 14
RemoteClickerButton.Name = "RemoteClickerButton"
RemoteClickerButton.Parent = RemoteClickerFrame
RemoteClickerButton.BackgroundColor3 = Color3.new(1, 1, 1)
RemoteClickerButton.BorderSizePixel = 0
RemoteClickerButton.Position = UDim2.new(0.25, 0, 0.5, 0)
RemoteClickerButton.Size = UDim2.new(0.5, 0, 0.5, 0)
RemoteClickerButton.Font = Enum.Font.SourceSans
RemoteClickerButton.FontSize = Enum.FontSize.Size14
RemoteClickerButton.Text = "OFF"
RemoteClickerButton.TextColor3 = Color3.new(1, 0, 0)
RemoteClickerButton.TextSize = 14
AutoLoadoutFrame.Name = "AutoLoadoutFrame"
AutoLoadoutFrame.Parent = Toggleable
AutoLoadoutFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
AutoLoadoutFrame.BorderSizePixel = 0
AutoLoadoutFrame.Position = UDim2.new(0.0500000007, 0, 0.75, 0)
AutoLoadoutFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_12.Name = "Deco"
Deco_12.Parent = AutoLoadoutFrame
Deco_12.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_12.BackgroundTransparency = 1
Deco_12.Size = UDim2.new(1, 0, 0.5, 0)
Deco_12.Font = Enum.Font.Highway
Deco_12.FontSize = Enum.FontSize.Size14
Deco_12.Text = "Auto Load Loadout 1"
Deco_12.TextColor3 = Color3.new(1, 1, 1)
Deco_12.TextSize = 14
AutoLoadout1Button.Name = "AutoLoadout1Button"
AutoLoadout1Button.Parent = AutoLoadoutFrame
AutoLoadout1Button.BackgroundColor3 = Color3.new(1, 1, 1)
AutoLoadout1Button.BorderSizePixel = 0
AutoLoadout1Button.Position = UDim2.new(0.25, 0, 0.5, 0)
AutoLoadout1Button.Size = UDim2.new(0.5, 0, 0.5, 0)
AutoLoadout1Button.Font = Enum.Font.SourceSans
AutoLoadout1Button.FontSize = Enum.FontSize.Size14
AutoLoadout1Button.Text = "OFF"
AutoLoadout1Button.TextColor3 = Color3.new(1, 0, 0)
AutoLoadout1Button.TextSize = 14
NotificationsFrame.Name = "NotificationsFrame"
NotificationsFrame.Parent = Toggleable
NotificationsFrame.BackgroundColor3 = Color3.new(0.454902, 0.454902, 0.454902)
NotificationsFrame.BorderSizePixel = 0
NotificationsFrame.Position = UDim2.new(0.0500000007, 0, 0.850000024, 0)
NotificationsFrame.Size = UDim2.new(0.899999976, 0, 0.075000003, 0)
Deco_13.Name = "Deco"
Deco_13.Parent = NotificationsFrame
Deco_13.BackgroundColor3 = Color3.new(1, 1, 1)
Deco_13.BackgroundTransparency = 1
Deco_13.Size = UDim2.new(1, 0, 0.5, 0)
Deco_13.Font = Enum.Font.Highway
Deco_13.FontSize = Enum.FontSize.Size14
Deco_13.Text = "Notifications"
Deco_13.TextColor3 = Color3.new(1, 1, 1)
Deco_13.TextSize = 14
NotificationsButton.Name = "NotificationsButton"
NotificationsButton.Parent = NotificationsFrame
NotificationsButton.BackgroundColor3 = Color3.new(1, 1, 1)
NotificationsButton.BorderSizePixel = 0
NotificationsButton.Position = UDim2.new(0.25, 0, 0.5, 0)
NotificationsButton.Size = UDim2.new(0.5, 0, 0.5, 0)
NotificationsButton.Font = Enum.Font.SourceSans
NotificationsButton.FontSize = Enum.FontSize.Size14
NotificationsButton.Text = "ON"
NotificationsButton.TextColor3 = Color3.new(0, 1, 0)
NotificationsButton.TextSize = 14
function CountBricks()
local c = 0
for i,v in pairs(workspace:GetChildren()) do
for x in string.gmatch(v.Name, "Crate") do
wait(0.2)
c = c + 1
end
end
return c
end
tpcratez = false
spawn (function()
while true do
wait()
NumberOfBoxes.Text = CountBricks()
if tpcratez == true then
local pos = Instance.new("Vector3Value")
pos.Value = game.Players.LocalPlayer.Character.Head.Position
local children = game.Workspace:GetChildren()
for i =1, #children do
wait(0.1)
if children[i] ~= nil then
for x in string.gmatch(children[i].Name, "Crate") do
if children[i].ClassName == "Part" then
game.Players.LocalPlayer.Character:MoveTo(children[i].Position)
wait(0.3)
end
end
end
end
wait(0.1)
game.Players.LocalPlayer.Character:MoveTo(pos.Value)
pos:remove()
end
end
end)
TPCrates.MouseButton1Down:connect(function()
local pos = Instance.new("Vector3Value")
pos.Value = game.Players.LocalPlayer.Character.Head.Position
local children = game.Workspace:GetChildren()
for i =1, #children do
wait(0.1)
if children[i] ~= nil then
for x in string.gmatch(children[i].Name, "Crate") do
if children[i].ClassName == "Part" then
game.Players.LocalPlayer.Character:MoveTo(children[i].Position)
wait(0.3)
end
end
end
end
wait(0.1)
game.Players.LocalPlayer.Character:MoveTo(pos.Value)
pos:remove()
end)
LoopTPCrates.MouseButton1Down:connect(function()
if tpcratez == true then
LoopTPCrates.Text = "Loop TP Crates: OFF"
Loop.ImageColor3 = Color3.fromRGB(255,0,0)
tpcratez = false else
LoopTPCrates.Text = "Loop TP Crates: ON"
Loop.ImageColor3 = Color3.fromRGB(0,255,0)
tpcratez = true
end
end)
local autoremote = false
RemoteClickerButton.MouseButton1Down:connect(function()
if autoremote == false then
autoremote = true
RemoteClickerButton.Text = "ON"
RemoteClickerButton.TextColor3 = Color3.fromRGB(0,255,0)
else
autoremote = false
RemoteClickerButton.Text = "OFF"
RemoteClickerButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
local autobutton = false
ButtonClickerButton.MouseButton1Down:connect(function()
if autobutton == false then
autobutton = true
ButtonClickerButton.Text = "ON"
ButtonClickerButton.TextColor3 = Color3.fromRGB(0,255,0)
else
autobutton = false
ButtonClickerButton.Text = "OFF"
ButtonClickerButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
local notificationstog = true
NotificationsButton.MouseButton1Down:connect(function()
if notificationstog == false then
notificationstog = true
NotificationsButton.Text = "ON"
NotificationsButton.TextColor3 = Color3.fromRGB(0,255,0)
else
notificationstog = false
NotificationsButton.Text = "OFF"
NotificationsButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
local loadloadout1 = false
AutoLoadout1Button.MouseButton1Down:connect(function()
if loadloadout1 == false then
loadloadout1 = true
AutoLoadout1Button.Text = "ON"
AutoLoadout1Button.TextColor3 = Color3.fromRGB(0,255,0)
else
loadloadout1 = false
AutoLoadout1Button.Text = "OFF"
AutoLoadout1Button.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
spawn (function()
while true do
wait()
if autoremote == true then
game.ReplicatedStorage.RemoteDrop:FireServer()
end
end
end)
spawn (function()
while true do
wait()
if notificationstog == true then
game.Players.LocalPlayer.PlayerGui.GUI.Notifications.Visible = true
else
game.Players.LocalPlayer.PlayerGui.GUI.Notifications.Visible = false
end
end
end)
spawn(function()
while true do
wait()
if loadloadout1 == true then
game.ReplicatedStorage.Layouts:InvokeServer("Load","Layout1")
end
end
end)
local factorys = workspace.Tycoons:GetChildren()
for i =1, #factorys do
if factorys[i].Owner.Value == game.Players.LocalPlayer.Name then
myfac = factorys[i]
end
end
spawn (function()
while true do
wait(0.1)
if autobutton == true then
local clickymines = myfac:GetChildren()
for i =1, #clickymines do
if clickymines[i].ClassName == "Model" then
if clickymines[i].Model:findFirstChild("Button") then
local de = clickymines[i].Model:GetChildren()
for i =1, #de do
if de[i].Name == "Button" then
game.ReplicatedStorage.Click:FireServer(de[i])
end
end
end
end
end
end
end
end)
spawn (function()
while true do
wait(0.5)
if workspace.Map:findFirstChild("Iron Mine-Chan") then
MineChanButton.Visible = true
else
MineChanButton.Visible = false
end
end
end)
MineChanButton.MouseButton1Down:connect(function()
for i = 1,AmountToGive.Text do
game:GetService("ReplicatedStorage").Click:FireServer(workspace.Map["Iron Mine-Chan"].Hitbox)
end
end)
PlusTwitchButton.MouseButton1Down:connect(function()
game.Players.LocalPlayer.TwitchPoints.Value = game.Players.LocalPlayer.TwitchPoints.Value+1
end)
PlusCloverButton.MouseButton1Down:connect(function()
game.Players.LocalPlayer.Clovers.Value = game.Players.LocalPlayer.Clovers.Value+1
end)
local reloop = false
AutoRegularButton.MouseButton1Down:connect(function()
if reloop == false then
reloop = true
AutoRegularButton.Text = "ON"
AutoRegularButton.TextColor3 = Color3.fromRGB(0,255,0)
else
reloop = false
AutoRegularButton.Text = "OFF"
AutoRegularButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
local unloop = false
AutoUnrealButton.MouseButton1Down:connect(function()
if unloop == false then
unloop = true
AutoUnrealButton.Text = "ON"
AutoUnrealButton.TextColor3 = Color3.fromRGB(0,255,0)
else
unloop = false
AutoUnrealButton.Text = "OFF"
AutoUnrealButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
local inloop = false
AutoInfernoButton.MouseButton1Down:connect(function()
if inloop == false then
inloop = true
AutoInfernoButton.Text = "ON"
AutoInfernoButton.TextColor3 = Color3.fromRGB(0,255,0)
else
inloop = false
AutoInfernoButton.Text = "OFF"
AutoInfernoButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
spawn (function()
while true do
wait(0.1)
if reloop == true then
if 0 < game.Players.LocalPlayer.Crates.Regular.Value then
else
game.ReplicatedStorage.MysteryBox:InvokeServer("Regular")
end
end
if unloop == true then
if 0 < game.Players.LocalPlayer.Crates.Unreal.Value then
else
game.ReplicatedStorage.MysteryBox:InvokeServer("Unreal")
end
end
if inloop == true then
if 0 < game.Players.LocalPlayer.Crates.Inferno.Value then
else
game.ReplicatedStorage.MysteryBox:InvokeServer("Inferno")
end
end
end
end)
local autorebirth = false
AutoRebirthButton.MouseButton1Down:connect(function()
if autorebirth == false then
autorebirth = true
AutoRebirthButton.Text = "ON"
AutoRebirthButton.TextColor3 = Color3.fromRGB(0,255,0)
else
autorebirth = false
AutoRebirthButton.Text = "OFF"
AutoRebirthButton.TextColor3 = Color3.fromRGB(255,0,0)
end
end)
spawn (function()
while true do
wait(1)
if autorebirth == true then
game.ReplicatedStorage.Rebirth:InvokeServer()
end
end
end) |
dofile('../Resource/scripts/ogreConfig.lua')
rootnode =RE.ogreRootSceneNode()
if rootnode then
lightnode=RE.createChildSceneNode(rootnode, "LightNode")
RE.ogreSceneManager():setAmbientLight(0.4, 0.4, 0.4)
if RE.getOgreVersionMinor()==12 then
local function randomNormal()
return (math.random()-0.5)*2
end
local numMainLights=10
if depthShadow then
numMainLights=1 -- no difference
end
local textureShadow=false
if not stencilShadow and not depthShadow then
textureShadow=true
end
local lightVar=0.02
local sc=math.pow(0.5, 1/numMainLights)
local light1D=0.8
local light1S=0.2
local lightOD=0
local lightOS=0
local highQualityRendering=false -- set this true for high quality render
if not stencilShadow then
lightVar=0.1
if depthShadow then
light1D=0.8/numMainLights
light1S=0.2/numMainLights
lightOD=0.8/numMainLights
lightOS=0.2/numMainLights
end
sc=0.9
if textureShadow then
sc=0.995
highQualityRendering=true
end
else
sc=0.975
end
if highQualityRendering then
-- high-quality
numMainLights=100
lightVar=0.04
if stencilShadow then
sc=math.pow(0.5, 1/numMainLights)
else
if depthShadow then
lightVar=0.2
sc=0.99
else
numMainLights=100
lightVar=0.3
sc=0.998
end
RE.ogreSceneManager():setShadowTextureCount(numMainLights)
end
local function randomNormal()
while true do
local u = 2 * math.random() - 1;
local v = 2 * math.random() - 1;
local w = math.pow(u, 2) + math.pow(v, 2);
if w<1 then
local z = math.sqrt((-2 * math.log(w)) / w);
local x = u * z;
local y = v * z;
return x
end
end
end
end
RE.ogreSceneManager():setShadowColour(sc,sc,sc)
for i=1,numMainLights do
local light
if i==1 then
light=RE.ogreSceneManager():createLight("Mainlight")
else
light=RE.ogreSceneManager():createLight("Mainlight"..i)
end
light:setType("LT_DIRECTIONAL")
light:setDirection(-0.5+lightVar*(randomNormal()),-0.7,0.5+lightVar*(randomNormal()))
if i==1 then
light:setDiffuseColour(light1D,light1D,light1D)
light:setSpecularColour(light1S,light1S,light1S)
else
light:setDiffuseColour(lightOD,lightOD,lightOD)
light:setSpecularColour(lightOS,lightOS,lightOS)
end
light:setCastShadows(true)
lightnode:attachObject(light)
end
else
light=RE.ogreSceneManager():createLight("Mainlight")
light:setType("LT_DIRECTIONAL")
light:setDirection(-0.5,-0.7,0.5)
light:setDiffuseColour(0.8,0.8,0.8)
light:setSpecularColour(0.2,0.2,0.2)
light:setCastShadows(true)
lightnode:attachObject(light)
light=RE.ogreSceneManager():createLight("FillLight")
light:setType("LT_DIRECTIONAL")
light:setDirection(0.6,-0.5,-0.4)
light:setDiffuseColour(0.2,0.2,0.2)
light:setSpecularColour(0,0,0)
light:setCastShadows(false)
lightnode:attachObject(light)
end
-- light=RE.ogreSceneManager():createLight("BackLight")
-- light:setType("LT_DIRECTIONAL")
-- light:setDirection(-0.4,-0.5,0.6)
-- light:setDiffuseColour(0.2,0.2,0.2)
-- light:setSpecularColour(0,0,0)
-- light:setCastShadows(false)
-- lightnode:attachObject(light)
-- light=RE.ogreSceneManager():createLight("BackLight2") -- ???? ???? ???츸 ?????? ??.
-- light:setType("LT_DIRECTIONAL")
-- light:setDirection(0.5,0.7,0.5)
-- light:setDiffuseColour(0.2,0.2,0.2)
-- light:setSpecularColour(0,0,0)
-- light:setCastShadows(false)
-- lightnode:attachObject(light)
end
|
require "busted.runner"()
describe("Assertion", function()
describe("True", function()
it("should have an error message", function()
local function some_test()
local assertion = require "ptable.assertion"
assertion.True("test", "some error message", false)
end
local _, err = pcall(some_test)
assert.is_not.Nil(err)
end)
it("should not have an error", function()
local function some_test()
local assertion = require "ptable.assertion"
assertion.True("test", "Some error message", true)
end
local _, err = pcall(some_test)
assert.Nil(err)
end)
it("should not have an error", function()
local function some_test()
local assertion = require "ptable.assertion"
assertion.True("test", "Some error message", not false)
end
local _, err = pcall(some_test)
assert.Nil(err)
end)
end)
end)
|
-- script that retrieves an authentication token to send in all future requests and adds a body for those requests
-- keep this file and getWithToken.lua in sync with respect to token handling
-- do not use wrk's default request
local req = nil
-- use token for at most maxRequests, default throughout test
local counter = 0
local maxRequests = -1
-- request access necessary for both reading and writing by default
local username = "writer@example.com"
-- marker that we have completed the first request
local token = nil
function init(args)
if args[1] ~= nil then
maxRequests = args[1]
print("Max requests: " .. maxRequests)
end
if args[2] ~= nil then
username = args[2]
end
local path = "/token?username=" .. username
-- initialize first (empty) request
req = wrk.format("GET", path, nil, "")
end
function request()
return req
end
function response(status, headers, body)
if not token and status == 200 then
token = body
wrk.headers["Authorization"] = "Bearer " .. token
wrk.headers["Content-Type"] = "application/json"
wrk.method = "POST"
wrk.body = [[
{
"category": {
"name": "Cats"
},
"images": [
{
"url": "http://example.com/images/fluffy1.png"
},
{
"url": "http://example.com/images/fluffy2.png"
},
],
"tags": [
{
"name": "orange"
},
{
"name": "kitty"
}
],
"age": 2,
"hasVaccinations": "true",
"name": "fluffy",
"status": "available"
}]]
req = wrk.format()
return
end
if not token then
print("Failed initial request! status: " .. status)
wrk.thread:stop()
end
if counter == maxRequests then
wrk.thread:stop()
end
counter = counter + 1
end
|
--[[
desc: UpperSlash, a state of Swordman.
author: SkyFvcker
since: 2018-7-30
alter: 2019-5-16
]]--
local _SOUND = require("lib.sound")
local _TABLE = require("lib.table")
local _FACTORY = require("actor.factory")
local _RESMGR = require("actor.resmgr")
local _ASPECT = require("actor.service.aspect")
local _STATE = require("actor.service.state")
local _INPUT = require("actor.service.input")
local _EQUIPMENT = require("actor.service.equipment")
local _BUFF = require("actor.service.buff")
local _EFFECT = require("actor.service.effect")
local _MOTION = require("actor.service.motion")
local _Easemove = require("actor.gear.easemove")
local _Attack = require("actor.gear.attack")
local _Base = require("actor.state.base")
---@class Actor.State.Duelist.Swordman.UpperSlash:Actor.State
---@field protected _attack Actor.Gear.Attack
---@field protected _skill Actor.Skill
---@field protected _effect Actor.Entity
---@field protected _easemoveTick int
---@field protected _easemoveParams table
---@field protected _easemove Actor.Gear.Easemove
---@field protected _hitstopMap table
---@field protected _effectTick int
---@field protected _cutTime int
---@field protected _line int
---@field protected _buff Actor.Buff
---@field protected _ascend boolean
---@field protected _breaking boolean
---@field protected _process int
---@field protected _figureData Lib.RESOURCE.SpriteData
local _UpperSlash = require("core.class")(_Base)
---@param attack Actor.Gear.Attack
---@param entity Actor.Entity
local function _Collide(attack, entity)
local isdone, x, y, z = _Attack.DefaultCollide(attack, entity)
if (isdone) then
return isdone, x, y, z, _, _, entity.battle.banCountMap.flight > 0
end
return false
end
function _UpperSlash:Ctor(data, ...)
_Base.Ctor(self, data, ...)
self._easemoveTick = data.easemoveTick
self._easemoveParams = data.easemove
self._hitstopMap = data.hitstop
self._effectTick = data.effectTick
self._ascend = data.ascend
self._breaking = data.breaking
if (data.comboBuff) then
self._comboBuffData = _RESMGR.NewBuffData(data.comboBuff.path, data.comboBuff)
end
end
function _UpperSlash:Init(entity)
_Base.Init(self, entity)
self._easemove = _Easemove.New(self._entity.transform, self._entity.aspect)
self._attack = _Attack.New(self._entity)
end
function _UpperSlash:NormalUpdate(dt, rate)
self._easemove:Update(rate)
local main = _ASPECT.GetPart(self._entity.aspect) ---@type Graphics.Drawable.Frameani
local tick = main:GetTick()
if (tick == self._effectTick) then
local t = self._entity.transform
local param = {
x = t.x,
y = t.y,
z = t.z,
direction = t.direction,
entity = self._entity
}
self._effect = _FACTORY.New(self._actorDataSet[self._process], param)
if(self._ascend and self._process == 2) then
_SOUND.Play(self._soundDataSet.voice[self._process])
_SOUND.Play(self._soundDataSet.effect[self._process])
self._attack:Enter(self._attackDataSet[self._process], self._skill.attackValues[1], _, _, true)
self._attack.collision[_ASPECT.GetPart(self._effect.aspect)] = "attack"
end
elseif (tick == self._easemoveTick) then
local direction = self._entity.transform.direction
local arrowDirection = _INPUT.GetArrowDirection(self._entity.input, direction)
if (arrowDirection >= 0) then
local easemoveParam = self._easemoveParams[arrowDirection + 1]
self._easemove:Enter("x", easemoveParam.power, easemoveParam.speed, direction)
end
end
if(self._ascend) then
if (self._process == 1 and tick == self._effectTick + 2) then
_BUFF.AddBuff(self._entity, self._comboBuffData)
self._skill:Reset()
elseif (self._process == 2) then
if (tick == self._effectTick) then
self._figureData = main:GetData()
elseif (tick == self._effectTick + 1) then
_EFFECT.NewFigure(self._entity.transform, self._entity.aspect, self._figureData)
end
end
end
self._attack:Update()
_STATE.AutoPlayEnd(self._entity.states, self._entity.aspect, self._nextState)
end
function _UpperSlash:Enter(laterState, skill)
local buff = self._comboBuffData and _BUFF.GetBuff(self._entity.buffs, self._comboBuffData.path)
if (buff) then
if (laterState ~= self) then
_Base.Enter(self)
else
_MOTION.TurnDirection(self._entity.transform, self._entity.input)
end
self._process = 2
_ASPECT.Play(self._entity.aspect, self._frameaniDataSets[2])
buff:Exit()
elseif (laterState ~= self) then
_Base.Enter(self)
self._process = 1
self._easemove:Exit()
self._skill = skill
if (self._breaking) then
self._attack:Enter(self._attackDataSet[self._process], self._skill.attackValues[1], _, _Collide)
else
self._attack:Enter(self._attackDataSet[self._process], self._skill.attackValues[1])
end
local kind = _EQUIPMENT.GetSubKind(self._entity.equipments, "weapon")
table.insert(self._attack.soundDataSet, self._soundDataSet.hitting[kind])
local hitstop = self._hitstopMap[kind]
self._attack.hitstop = hitstop[1]
self._attack.selfstop = hitstop[2]
self._attack.shake.time = hitstop[1]
_SOUND.Play(self._soundDataSet.voice[self._process])
_SOUND.Play(self._soundDataSet.effect[self._process])
self._buff = _BUFF.AddBuff(self._entity, self._buffDatas)
if (self._comboBuffData) then
self._comboBuffData.skill = self._skill
end
end
end
function _UpperSlash:Exit(nextState)
if (nextState == self) then
return
end
_Base.Exit(self, nextState)
if (self._effect) then
self._effect.identity.destroyProcess = 1
self._effect = nil
end
if (self._buff) then
self._buff:Exit()
end
end
return _UpperSlash
|
---@class IsoRegions : zombie.iso.areas.isoregion.IsoRegions
---@field public SINGLE_CHUNK_PACKET_SIZE int
---@field public CHUNKS_DATA_PACKET_SIZE int
---@field public PRINT_D boolean
---@field public CELL_DIM int
---@field public CELL_CHUNK_DIM int
---@field public CHUNK_DIM int
---@field public CHUNK_MAX_Z int
---@field public BIT_EMPTY byte
---@field public BIT_WALL_N byte
---@field public BIT_WALL_W byte
---@field public BIT_PATH_WALL_N byte
---@field public BIT_PATH_WALL_W byte
---@field public BIT_HAS_FLOOR byte
---@field public BIT_STAIRCASE byte
---@field public BIT_HAS_ROOF byte
---@field public DIR_NONE byte
---@field public DIR_N byte
---@field public DIR_W byte
---@field public DIR_2D_NW byte
---@field public DIR_S byte
---@field public DIR_E byte
---@field public DIR_2D_MAX byte
---@field public DIR_TOP byte
---@field public DIR_BOT byte
---@field public DIR_MAX byte
---@field protected CHUNK_LOAD_DIMENSIONS int
---@field protected DEBUG_LOAD_ALL_CHUNKS boolean
---@field public FILE_PRE String
---@field public FILE_SEP String
---@field public FILE_EXT String
---@field public FILE_DIR String
---@field private SQUARE_CHANGE_WARN_THRESHOLD int
---@field private SQUARE_CHANGE_PER_TICK int
---@field private cacheDir String
---@field private cacheDirFile File
---@field private headDataFile File
---@field private chunkFileNames Map|Unknown|Unknown
---@field private regionWorker IsoRegionWorker
---@field private dataRoot DataRoot
---@field private logger IsoRegionsLogger
---@field protected lastChunkX int
---@field protected lastChunkY int
---@field private previousFlags byte
IsoRegions = {}
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return byte
function IsoRegions:getSquareFlags(arg0, arg1, arg2) end
---@public
---@return boolean
function IsoRegions:isDebugLoadAllChunks() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return IWorldRegion
function IsoRegions:getIsoWorldRegion(arg0, arg1, arg2) end
---@public
---@return void
function IsoRegions:ResetAllDataDebug() end
---@public
---@return void
function IsoRegions:update() end
---@public
---@param arg0 int
---@param arg1 int
---@return DataChunk
function IsoRegions:getDataChunk(arg0, arg1) end
---@public
---@param arg0 IsoGridSquare
---@return void
function IsoRegions:setPreviousFlags(arg0) end
---@protected
---@return void
function IsoRegions:forceRecalcSurroundingChunks() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return IChunkRegion
function IsoRegions:getChunkRegion(arg0, arg1, arg2) end
---@public
---@return void
function IsoRegions:reset() end
---@protected
---@return DataRoot
function IsoRegions:getDataRoot() end
---@private
---@return void
function IsoRegions:clientResetCachedRegionReferences() end
---@public
---@return File
function IsoRegions:getHeaderFile() end
---@public
---@param arg0 int
---@param arg1 int
---@return File
function IsoRegions:getChunkFile(arg0, arg1) end
---@public
---@return File
function IsoRegions:getDirectory() end
---@public
---@return IsoRegionsLogger
function IsoRegions:getLogger() end
---@protected
---@return IsoRegionWorker
function IsoRegions:getRegionWorker() end
---@public
---@param arg0 String
---@return void
function IsoRegions:warn(arg0) end
---@protected
---@param arg0 IsoGridSquare
---@return byte
function IsoRegions:calculateSquareFlags(arg0) end
---@public
---@param arg0 String
---@return void
---@overload fun(arg0:String, arg1:Color)
function IsoRegions:log(arg0) end
---@public
---@param arg0 String
---@param arg1 Color
---@return void
function IsoRegions:log(arg0, arg1) end
---@public
---@param arg0 byte
---@return byte
function IsoRegions:GetOppositeDir(arg0) end
---@public
---@param arg0 IsoGridSquare
---@return void
---@overload fun(arg0:IsoGridSquare, arg1:boolean)
function IsoRegions:squareChanged(arg0) end
---@public
---@param arg0 IsoGridSquare
---@param arg1 boolean
---@return void
function IsoRegions:squareChanged(arg0, arg1) end
---@public
---@param arg0 boolean
---@return void
function IsoRegions:setDebugLoadAllChunks(arg0) end
---@public
---@param arg0 int
---@param arg1 int
---@return int
function IsoRegions:hash(arg0, arg1) end
---@public
---@param arg0 ByteBuffer
---@param arg1 UdpConnection
---@return void
function IsoRegions:receiveClientRequestFullDataChunks(arg0, arg1) end
---@public
---@param arg0 ByteBuffer
---@return void
function IsoRegions:receiveServerUpdatePacket(arg0) end
---@public
---@return void
function IsoRegions:init() end
|
--[[
Humor API
Awesome Humor API.
The version of the OpenAPI document: 1.0
Contact: mail@humorapi.com
Generated by: https://openapi-generator.tech
]]
--package humorapi
local http_request = require "http.request"
local http_util = require "http.util"
local dkjson = require "dkjson"
local basexx = require "basexx"
-- model import
local humorapi_inline_response_200 = require "humorapi.model.inline_response_200"
local humorapi_inline_response_200_4 = require "humorapi.model.inline_response_200_4"
local humorapi_inline_response_200_8 = require "humorapi.model.inline_response_200_8"
local humorapi_inline_response_200_9 = require "humorapi.model.inline_response_200_9"
local jokes_api = {}
local jokes_api_mt = {
__name = "jokes_api";
__index = jokes_api;
}
local function new_jokes_api(authority, basePath, schemes)
local schemes_map = {}
for _,v in ipairs(schemes) do
schemes_map[v] = v
end
local default_scheme = schemes_map.https or schemes_map.http
local host, port = http_util.split_authority(authority, default_scheme)
return setmetatable({
host = host;
port = port;
basePath = basePath or "https://api.humorapi.com";
schemes = schemes_map;
default_scheme = default_scheme;
http_username = nil;
http_password = nil;
api_key = {};
access_token = nil;
}, jokes_api_mt)
end
function jokes_api:analyze_joke(body)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes/analyze",
self.basePath);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper accept
--local var_content_type = { "text/plain" }
req.headers:upsert("accept", "text/plain")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
req:set_body(dkjson.encode(body))
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200_9.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function jokes_api:downvote_joke(id)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes/%s/downvote",
self.basePath, id);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200_8.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function jokes_api:random_joke(keywords, include_tags, exclude_tags, min_rating, max_length)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes/random?keywords=%s&include-tags=%s&exclude-tags=%s&min-rating=%s&max-length=%s",
self.basePath, http_util.encodeURIComponent(keywords), http_util.encodeURIComponent(include_tags), http_util.encodeURIComponent(exclude_tags), http_util.encodeURIComponent(min_rating), http_util.encodeURIComponent(max_length));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200_4.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function jokes_api:search_jokes(keywords, include_tags, exclude_tags, Number_, min_rating, max_length, offset)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes/search?keywords=%s&include-tags=%s&exclude-tags=%s&number=%s&min-rating=%s&max-length=%s&offset=%s",
self.basePath, http_util.encodeURIComponent(keywords), http_util.encodeURIComponent(include_tags), http_util.encodeURIComponent(exclude_tags), http_util.encodeURIComponent(Number_), http_util.encodeURIComponent(min_rating), http_util.encodeURIComponent(max_length), http_util.encodeURIComponent(offset));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function jokes_api:submit_joke(body)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes",
self.basePath);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper accept
--local var_content_type = { "text/plain" }
req.headers:upsert("accept", "text/plain")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
req:set_body(dkjson.encode(body))
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200_8.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function jokes_api:upvote_joke(id)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jokes/%s/upvote",
self.basePath, id);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- TODO: api key in query 'api-key'
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return humorapi_inline_response_200_8.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
return {
new = new_jokes_api;
}
|
local GEN_OTHERNAME = 0
local GEN_EMAIL = 1
local GEN_DNS = 2
local GEN_X400 = 3
local GEN_DIRNAME = 4
local GEN_EDIPARTY = 5
local GEN_URI = 6
local GEN_IPADD = 7
local GEN_RID = 8
local default_types = {
OtherName = GEN_OTHERNAME, -- otherName
RFC822Name = GEN_EMAIL, -- email
RFC822 = GEN_EMAIL,
Email = GEN_EMAIL,
DNSName = GEN_DNS, -- dns
DNS = GEN_DNS,
X400 = GEN_X400, -- x400
DirName = GEN_DIRNAME, -- dirName
EdiParty = GEN_EDIPARTY, -- EdiParty
UniformResourceIdentifier = GEN_URI, -- uri
URI = GEN_URI,
IPAddress = GEN_IPADD, -- ipaddr
IP = GEN_IPADD,
RID = GEN_RID, -- rid
}
local literals = {
[GEN_OTHERNAME] = "OtherName",
[GEN_EMAIL] = "email",
[GEN_DNS] = "DNS",
[GEN_X400] = "X400",
[GEN_DIRNAME] = "DirName",
[GEN_EDIPARTY] = "EdiParty",
[GEN_URI] = "URI",
[GEN_IPADD] = "IP",
[GEN_RID] = "RID",
}
local types = {}
for t, gid in pairs(default_types) do
types[t:lower()] = gid
types[t] = gid
end
return {
types = types,
literals = literals,
} |
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
require 'TFramedTransport'
require 'TBinaryProtocol'
-- TServer
TServer = __TObject:new{
__type = 'TServer'
}
-- 2 possible constructors
-- 1. {processor, serverTransport}
-- 2. {processor, serverTransport, transportFactory, protocolFactory}
function TServer:new(args)
if ttype(args) ~= 'table' then
error('TServer must be initialized with a table')
end
if args.processor == nil then
terror('You must provide ' .. ttype(self) .. ' with a processor')
end
if args.serverTransport == nil then
terror('You must provide ' .. ttype(self) .. ' with a serverTransport')
end
-- Create the object
local obj = __TObject.new(self, args)
if obj.transportFactory then
obj.inputTransportFactory = obj.transportFactory
obj.outputTransportFactory = obj.transportFactory
obj.transportFactory = nil
else
obj.inputTransportFactory = TFramedTransportFactory:new{}
obj.outputTransportFactory = obj.inputTransportFactory
end
if obj.protocolFactory then
obj.inputProtocolFactory = obj.protocolFactory
obj.outputProtocolFactory = obj.protocolFactory
obj.protocolFactory = nil
else
obj.inputProtocolFactory = TBinaryProtocolFactory:new{}
obj.outputProtocolFactory = obj.inputProtocolFactory
end
-- Set the __server variable in the handler so we can stop the server
obj.processor.handler.__server = self
return obj
end
function TServer:setServerEventHandler(handler)
self.serverEventHandler = handler
end
function TServer:_clientBegin(content, iprot, oprot)
if self.serverEventHandler and
type(self.serverEventHandler.clientBegin) == 'function' then
self.serverEventHandler:clientBegin(iprot, oprot)
end
end
function TServer:_preServe()
if self.serverEventHandler and
type(self.serverEventHandler.preServe) == 'function' then
self.serverEventHandler:preServe(self.serverTransport:getSocketInfo())
end
end
function TServer:_handleException(err)
if string.find(err, 'TTransportException') == nil then
print(err)
end
end
function TServer:serve() end
function TServer:handle(client)
local itrans, otrans, iprot, oprot, ret, err =
self.inputTransportFactory:getTransport(client),
self.outputTransportFactory:getTransport(client),
self.inputProtocolFactory:getProtocol(client),
self.outputProtocolFactory:getProtocol(client)
self:_clientBegin(iprot, oprot)
while true do
ret, err = pcall(self.processor.process, self.processor, iprot, oprot)
if ret == false and err then
if not string.find(err, "TTransportException") then
self:_handleException(err)
end
break
end
end
itrans:close()
otrans:close()
end
function TServer:close()
self.serverTransport:close()
end
-- TSimpleServer
-- Single threaded server that handles one transport (connection)
TSimpleServer = __TObject:new(TServer, {
__type = 'TSimpleServer',
__stop = false
})
function TSimpleServer:serve()
self.serverTransport:listen()
self:_preServe()
while not self.__stop do
client = self.serverTransport:accept()
self:handle(client)
end
self:close()
end
function TSimpleServer:stop()
self.__stop = true
end
|
local Chara = Elona.require("Chara")
local GUI = Elona.require("GUI")
local I18N = Elona.require("I18N")
local Internal = Elona.require("Internal")
local Item = Elona.require("Item")
local Map = Elona.require("Map")
local Rand = Elona.require("Rand")
return {
id = "slan",
root = "core.locale.talk.unique.slan",
nodes = {
__start = function()
local flag = Internal.get_quest_flag("main_quest")
if flag == 20 then
return "dialog"
end
return "__IGNORED__"
end,
dialog = {
text = {
function() Internal.set_quest_flag("main_quest", 30) end,
{"dialog._0"},
{"dialog._1"},
{"dialog._2"},
},
on_finish = function(t)
for i=0,3 do
Item.create(
Chara.player().position,
{
level = Map.data.current_dungeon_level,
quality = "Bad",
flttypemajor = Internal.filter_set_dungeon()
}
)
end
Item.create(Chara.player().position, "core.gold_piece", Rand.between(1000, 1200))
Item.create(Chara.player().position, "core.platinum_coin", 3)
local item = Item.create(Chara.player().position, "core.bejeweled_chest", 0)
item.param2 = 0
GUI.play_sound("core.write1")
GUI.txt(I18N.get("core.locale.talk.unique.slan.you_receive"))
GUI.txt(I18N.get("core.locale.talk.unique.slan.dies", t.speaker))
t.speaker:vanquish()
end
}
}
}
|
local UTILS = require "tests.test_utils"
return function()
describe("World", function()
before(function()
UTILS.set_env(getfenv(1))
end)
after(function() end)
test("create", function()
local w = box2d.NewWorld()
assert_not_nil(w)
assert_not_nil(w.__userdata_box2d)
assert_equal(w.__userdata_type_box2d, "world")
w:Destroy()
end)
test("destroy", function()
local w = box2d.NewWorld()
w:Destroy()
local f = function() return w:GetProfile() end
local status, value = pcall(f)
assert_false(status)
UTILS.test_error(value, "world was destroyed")
end)
test("destroy all refs", function()
local w = box2d.NewWorld()
local body = w:CreateBody({})
local w2 = body:GetWorld()
w:Destroy()
local f = function() return w:GetProfile() end
local f2 = function() return w2:GetProfile() end
local status, value = pcall(f)
assert_false(status)
UTILS.test_error(value, "world was destroyed")
status, value = pcall(f2)
assert_false(status)
UTILS.test_error(value, "world was destroyed")
end)
test("newIndex", function()
local w = box2d.NewWorld()
local f = function() w.data = {} end
local status, value = pcall(f)
assert_false(status)
UTILS.test_error(value, "world can't set new fields")
w:Destroy()
end)
test("tostring", function()
local w = box2d.NewWorld()
local s = tostring(w)
assert_equal(s:sub(1, 8), "b2World[")
w:Destroy()
end)
test("equals", function()
local w = box2d.NewWorld()
local w2 = box2d.NewWorld()
assert_equal(w, w)
assert_not_equal(w, w2)
assert_not_equal(w, 1)
assert_not_equal(w, {})
local b = w:CreateBody({})
assert_equal(w, b:GetWorld())
w:Destroy()
w2:Destroy()
end)
test("GetProfile()", function()
local w = box2d.NewWorld()
local profile = w:GetProfile()
assert_not_nil(profile.step)
assert_not_nil(profile.collide)
assert_not_nil(profile.solve)
assert_not_nil(profile.solveInit)
assert_not_nil(profile.solveVelocity)
assert_not_nil(profile.solvePosition)
assert_not_nil(profile.broadphase)
assert_not_nil(profile.solveTOI)
w:Destroy()
end)
test("SetContactListener()", function()
local w = box2d.NewWorld()
w:Step(1 / 60, 3, 5)
w:SetContactListener(nil)
w:Step(1 / 60, 3, 5)
w:SetContactListener({ })
w:Step(1 / 60, 3, 5)
local contacts = {
BeginContact = {},
EndContact = {},
PreSolve = {},
PostSolve = {},
}
w:SetContactListener({
BeginContact = function(contact)
assert_not_nil(contact)
assert_not_nil(contact.__userdata_box2d)
assert_equal(contact.__userdata_type_box2d, "contact")
table.insert(contacts.BeginContact, true)
end,
EndContact = function(contact)
assert_not_nil(contact)
assert_not_nil(contact.__userdata_box2d)
assert_equal(contact.__userdata_type_box2d, "contact")
table.insert(contacts.EndContact, true)
end,
---@param old_manifold Box2dManifold
PreSolve = function(contact, old_manifold)
assert_not_nil(contact)
assert_not_nil(contact.__userdata_box2d)
assert_equal(contact.__userdata_type_box2d, "contact")
table.insert(contacts.PreSolve, true)
assert_not_nil(old_manifold)
assert_equal(#old_manifold.points, old_manifold.pointCount)
end,
---@param impulse Box2dContactImpulse
PostSolve = function(contact, impulse)
assert_not_nil(contact)
assert_not_nil(contact.__userdata_box2d)
assert_equal(contact.__userdata_type_box2d, "contact")
table.insert(contacts.PostSolve, true)
assert_not_nil(impulse)
assert_equal(impulse.count, #impulse.normalImpulses)
assert_equal(impulse.count, #impulse.tangentImpulses)
end,
})
w:Step(1 / 60, 3, 5)
assert_equal(#contacts.BeginContact, 0)
assert_equal(#contacts.EndContact, 0)
assert_equal(#contacts.PreSolve, 0)
assert_equal(#contacts.PostSolve, 0)
local b1 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 0, 0) })
local b2 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 1, 0) })
b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
w:Step(1 / 60, 3, 5)
assert_equal(#contacts.BeginContact, 1)
assert_equal(#contacts.EndContact, 0)
assert_equal(#contacts.PreSolve, 1)
assert_equal(#contacts.PostSolve, 1)
w:SetContactListener({ PreSolve = function()
error("error")
end })
local status, value = pcall(w.Step, w, 1 / 60, 3, 5)
assert_false(status)
UTILS.test_error(value, "error")
w:SetContactListener({ PreSolve = function()
end })
w:Step(1 / 60, 3, 5)
w:Step(1 / 60, 3, 5)
w:Step(1 / 60, 3, 5)
w:Step(1 / 60, 3, 5)
w:Step(1 / 60, 3, 5)
w:Destroy()
end)
test("SetContactListener() Destroy Contacts", function()
local w = box2d.NewWorld()
---@type Box2dContact
local c
w:SetContactListener({
BeginContact = function(contact)
c = c or contact
assert_not_nil(c.__userdata_box2d)
assert_equal(c.__userdata_type_box2d, "contact")
end,
EndContact = function(contact)
c = c or contact
assert_not_nil(c.__userdata_box2d)
assert_equal(c.__userdata_type_box2d, "contact")
end,
PreSolve = function(contact, old_manifold)
c = c or contact
assert_not_nil(c.__userdata_box2d)
assert_equal(c.__userdata_type_box2d, "contact")
end,
PostSolve = function(contact, impulse)
c = c or contact
assert_not_nil(c.__userdata_box2d)
assert_equal(c.__userdata_type_box2d, "contact")
end,
})
local b1 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 0, 0) })
local b2 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 1, 0) })
local b3 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 0, 0) })
local b4 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 1, 0) })
b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b3:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b4:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
w:Step(1 / 60, 3, 5)
assert_not_nil(c)
assert_not_nil(c.__userdata_box2d)
c:GetRestitution()
w:DestroyBody(b1)
w:DestroyBody(b2)
w:DestroyBody(b3)
w:DestroyBody(b4)
assert_not_nil(c)
assert_nil(c.__userdata_box2d)
assert_not_nil(c.__userdata_type_box2d, "contact")
b1 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 0, 0) })
b2 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 1, 0) })
b3 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 0, 0) })
b4 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 1, 0) })
b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b3:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b4:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
c = nil
w:Step(1 / 60, 3, 5)
assert_not_nil(c)
assert_not_nil(c.__userdata_box2d)
w:Destroy()
assert_not_nil(c)
assert_nil(c.__userdata_box2d)
assert_not_nil(c.__userdata_type_box2d, "contact")
end)
test("SetDestructionListener()", function()
local w = box2d.NewWorld()
--NIL
local b1 = w:CreateBody()
local b2 = w:CreateBody()
local f1 = b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
local joint = w:CreateJoint(box2d.InitializeRevoluteJointDef(b1, b2, vmath.vector3(0, 0, 0)))
w:SetDestructionListener(nil)
w:DestroyBody(b1)
--EMPTY
b1 = w:CreateBody()
b2 = w:CreateBody()
f1 = b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
joint = w:CreateJoint(box2d.InitializeRevoluteJointDef(b1, b2, vmath.vector3(0, 0, 0)))
w:SetDestructionListener({ })
w:DestroyBody(b1)
--BASE
local callbacks = {
SayGoodbyeFixture = {},
SayGoodbyeJoint = {},
}
w:SetDestructionListener({
SayGoodbyeFixture = function(fixture)
assert_not_nil(fixture)
assert_not_nil(fixture.__userdata_box2d)
assert_equal(fixture.__userdata_type_box2d, "fixture")
table.insert(callbacks.SayGoodbyeFixture, fixture)
end,
SayGoodbyeJoint = function(joint)
assert_not_nil(joint)
assert_not_nil(joint.__userdata_box2d)
assert_equal(joint.__userdata_type_box2d, "joint")
table.insert(callbacks.SayGoodbyeJoint, joint)
end,
})
b1 = w:CreateBody()
b2 = w:CreateBody()
f1 = b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
joint = w:CreateJoint(box2d.InitializeRevoluteJointDef(b1, b2, vmath.vector3(0, 0, 0)))
assert_not_nil(f1.__userdata_box2d)
assert_equal(f1.__userdata_type_box2d, "fixture")
w:DestroyBody(b1)
assert_equal(#callbacks.SayGoodbyeFixture, 1)
assert_equal(#callbacks.SayGoodbyeJoint, 1)
assert_equal(callbacks.SayGoodbyeFixture[1], f1)
assert_equal(callbacks.SayGoodbyeJoint[1], joint)
assert_nil(f1.__userdata_box2d)
assert_equal(f1.__userdata_type_box2d, "fixture")
assert_nil(joint.__userdata_box2d)
assert_equal(joint.__userdata_type_box2d, "joint")
--ERROR
--ERROR WILL BE SHOW IN CONSOLE. IT WILL NOT CALL luaL_error
w:SetDestructionListener({
SayGoodbyeFixture = function(fixture)
error("error happened fixture")
end,
SayGoodbyeJoint = function(joint)
error("error happened joint")
end,
})
b1 = w:CreateBody()
b2 = w:CreateBody()
f1 = b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
joint = w:CreateJoint(box2d.InitializeRevoluteJointDef(b1, b2, vmath.vector3(0, 0, 0)))
w:DestroyBody(b1)
assert_nil(f1.__userdata_box2d)
assert_equal(f1.__userdata_type_box2d, "fixture")
assert_nil(joint.__userdata_box2d)
assert_equal(joint.__userdata_type_box2d, "joint")
w:Destroy()
end)
-- test("CreateBody()", function() end) -- body tests
-- test("DestroyBody()", function() end)-- body tests
-- test("CreateJoint()", function() end) -- jointDef tests
-- test("DestroyBJoint()", function() end)-- joint tests
test("Step()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "Step", {
args = { 1 / 60, 2, 4 }
})
w:Destroy()
end)
test("ClearForces()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "ClearForces", {})
w:Destroy()
end)
test("DebugDraw()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "DebugDraw", {})
w:Destroy()
end)
test("RayCast()", function()
local w = box2d.NewWorld()
local body_1 = w:CreateBody({ position = vmath.vector3(5, 0, 0) })
local body_2 = w:CreateBody({ position = vmath.vector3(10, 0, 0) })
local body_3 = w:CreateBody({ position = vmath.vector3(15, 0, 0) })
body_1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
body_2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
body_3:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
local cb_results = {}
local cb_closest = function(fixture, point, normal, fraction)
assert_equal(type(fixture), "table")
assert_equal(type(point), "userdata")
assert_equal(type(normal), "userdata")
assert_equal(type(fraction), "number")
table.insert(cb_results, { fixture = fixture, point = point, normal = normal, fraction = fraction })
return fraction
end
local cb_all = function(fixture, point, normal, fraction)
table.insert(cb_results, { fixture = fixture, point = point, normal = normal, fraction = fraction })
return 1
end
local cb_any = function(fixture, point, normal, fraction)
table.insert(cb_results, { fixture = fixture, point = point, normal = normal, fraction = fraction })
return 0
end
local p1 = vmath.vector3(0, 0, 0)
local point_no = vmath.vector3(0, 10, 0)
local point_one = vmath.vector3(5, 0, 0)
local point_all = vmath.vector3(15, 0, 0)
--*** NO ***
w:RayCast(cb_closest, p1, point_no)
assert_equal(#cb_results, 0)
w:RayCast(cb_all, p1, point_no)
assert_equal(#cb_results, 0)
w:RayCast(cb_any, p1, point_no)
assert_equal(#cb_results, 0)
--*** ONE ***
w:RayCast(cb_closest, p1, point_one)
assert_equal(#cb_results, 1)
assert_equal(cb_results[1].fixture:GetBody(), body_1)
cb_results = {}
w:RayCast(cb_all, p1, point_one)
assert_equal(#cb_results, 1)
cb_results = {}
w:RayCast(cb_any, p1, point_one)
assert_equal(#cb_results, 1)
cb_results = {}
--*** ALL ***
w:RayCast(cb_closest, p1, point_all)
assert_equal(cb_results[#cb_results].fixture:GetBody(), body_1)
cb_results = {}
w:RayCast(cb_all, p1, point_all)
assert_equal(#cb_results, 3)
cb_results = {}
w:RayCast(cb_any, p1, point_all)
assert_equal(#cb_results, 1)
cb_results = {}
local cb_error = function() error("error happened") end
local status, error = pcall(w.RayCast, w, cb_error, p1, point_all)
assert_false(status)
--remove line number
UTILS.test_error(error, "error happened")
cb_error = function() w.aaaa() end
status, error = pcall(w.RayCast, w, cb_error, p1, point_all)
assert_false(status)
UTILS.test_error(error, " attempt to call field 'aaaa' (a nil value)")
w:Destroy()
end)
test("QueryAABB()", function()
local w = box2d.NewWorld()
local body_1 = w:CreateBody({ position = vmath.vector3(5, 0, 0) })
local body_2 = w:CreateBody({ position = vmath.vector3(10, 0, 0) })
local body_3 = w:CreateBody({ position = vmath.vector3(15, 0, 0) })
body_1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
body_2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
body_3:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
local cb_results = {}
local cb_all = function(fixture)
table.insert(cb_results, { fixture = fixture })
return true;
end
local cb_one = function(fixture)
table.insert(cb_results, { fixture = fixture })
return false;
end
local aabb_no = { lowerBound = vmath.vector3(-10, 0, 0), upperBound = vmath.vector3(-0.6, 0.1, 0) }
local aabb_one = { lowerBound = vmath.vector3(0, 0, 0), upperBound = vmath.vector3(5, 0.5, 0) }
local aabb_all = { lowerBound = vmath.vector3(0, 0, 0), upperBound = vmath.vector3(15, 0.5, 0) }
--*** NO ***
w:QueryAABB(cb_all, aabb_no)
assert_equal(#cb_results, 0)
w:QueryAABB(cb_one, aabb_no)
assert_equal(#cb_results, 0)
--*** ONE ***
w:QueryAABB(cb_all, aabb_one)
assert_equal(#cb_results, 1)
assert_equal(cb_results[1].fixture:GetBody(), body_1)
cb_results = {}
w:QueryAABB(cb_one, aabb_one)
assert_equal(#cb_results, 1)
assert_equal(cb_results[1].fixture:GetBody(), body_1)
cb_results = {}
--*** ALL ***
w:QueryAABB(cb_all, aabb_all)
assert_equal(#cb_results, 3)
cb_results = {}
w:QueryAABB(cb_one, aabb_all)
assert_equal(#cb_results, 1)
cb_results = {}
local cb_error = function() error("error happened") end
local status, error = pcall(w.QueryAABB, w, cb_error, aabb_all)
assert_false(status)
--remove line number
UTILS.test_error(error, "error happened")
w:Destroy()
end)
test("GetBodyList()", function()
local w = box2d.NewWorld()
assert_nil(w:GetBodyList())
local body_1 = w:CreateBody()
local body_2 = w:CreateBody()
assert_equal(w:GetBodyList(), body_2)
w:Destroy()
end)
test("GetJointList()", function()
local w = box2d.NewWorld()
assert_nil(w:GetJointList())
local body_1 = w:CreateBody()
local body_2 = w:CreateBody()
local joint1 = w:CreateJoint({ type = box2d.b2JointType.e_revoluteJoint, bodyA = body_1, bodyB = body_2 })
assert_equal(w:GetJointList(), joint1)
w:Destroy()
end)
test("GetContactList()", function()
local w = box2d.NewWorld()
local body = w:CreateBody({})
assert_nil(w:GetContactList())
local contacts = {
BeginContact = {},
EndContact = {},
PreSolve = {},
---@type Box2dContact[]
PostSolve = {},
}
w:SetContactListener({
---@param impulse Box2dContactImpulse
PostSolve = function(contact, impulse)
table.insert(contacts.PostSolve, contact)
end,
})
w:Step(1 / 60, 3, 5)
local b1 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 0, 0) })
local b2 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(1, 1, 0) })
local b3 = w:CreateBody({ type = box2d.b2BodyType.b2_dynamicBody, position = vmath.vector3(0, 1, 0) })
b1:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b2:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
b3:CreateFixture({ shape = box2d.b2Shape.e_polygon, box = true, box_hy = 1, box_hx = 1 }, 1)
w:Step(1 / 60, 3, 5)
local c = w:GetContactList()
local c2 = c:GetNext()
assert_equal(c2,c:GetNext())
local c3 = c2:GetNext()
local c_nil = c3:GetNext()
assert_not_nil(c)
assert_not_nil(c2)
assert_not_nil(c3)
assert_nil(c_nil)
w:Destroy()
end)
test("Set/Get AllowSleeping()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "AllowSleeping", {
values = { true, false }
})
w:Destroy()
end)
test("Set/Get WarmStarting()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "WarmStarting", {
values = { true, false }
})
w:Destroy()
end)
test("Set/Get ContinuousPhysics()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "ContinuousPhysics", {
values = { true, false }
})
w:Destroy()
end)
test("Set/Get SubStepping()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "SubStepping", {
values = { true, false }
})
w:Destroy()
end)
test("GetProxyCount()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetProxyCount", {
result = 0
})
w:Destroy()
end)
test("GetBodyCount()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetBodyCount", {
result = 0
})
w:Destroy()
end)
test("GetJointCount()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetJointCount", {
result = 0
})
w:Destroy()
end)
test("GetContactCount()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetContactCount", {
result = 0
})
w:Destroy()
end)
test("GetTreeHeight()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetTreeHeight", {
result = 0
})
w:Destroy()
end)
test("GetTreeBalance()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetTreeBalance", {
result = 0
})
w:Destroy()
end)
test("GetTreeQuality()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "GetTreeQuality", {
result = 0
})
w:Destroy()
end)
test("Set/Get Gravity()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "Gravity", {
v3 = true, default = vmath.vector3(0, 0, 0),
values = { vmath.vector3(-1, 0, 0), vmath.vector3(10, 0, 0), vmath.vector3(0, 0, 0) }
})
w:Destroy()
end)
test("IsLocked()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "IsLocked", {
result = false
})
w:Destroy()
end)
test("Set/Get AutoClearForces()", function()
local w = box2d.NewWorld()
UTILS.test_method_get_set(w, "AutoClearForces", {
values = { false, true }
})
w:Destroy()
end)
test("ShiftOrigin()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "ShiftOrigin", { args = { vmath.vector3(10, 10, 0) } })
w:Destroy()
end)
test("Dump()", function()
local w = box2d.NewWorld()
UTILS.test_method(w, "Dump", {})
w:Destroy()
end)
end)
end
|
local M = {}
M.url = 'folke/trouble.nvim'
M.description = 'Fancy problem list'
-- ways to activate this
M.activation = {
wanted_by = {
'target.basic'
},
}
function M.config()
require('trouble').setup {
auto_close = true,
auto_fold = true,
use_diagnostic_signs = true,
}
-- key setup
end
return M
|
-----------
-- Snake --
-----------
-- Website creator's forum name: mabako
local active = false
local lost = false
local screenX, screenY = guiGetScreenSize( )
local lastupdate = getTickCount( )
local moving = 0
local backgroundColor = tocolor( 20, 20, 20, 255 )
local lineColor = tocolor( 80, 80, 80, 255 )
local pickupColor = tocolor( 255, 255, 0, 255 )
local px = ( screenX - 30 * 21 ) / 2
local py = ( screenY - 20 * 21 ) / 2
local pickupPos = nil
repeat
pickupPos = { x = math.random( 1, 30 ), y = math.random( 1, 20 ) }
until pickupPos.x ~= 15 or pickupPos.y ~= 10
local snake = { { x = 15, y = 10 } }
local function isOnSnake( x, y )
for k, v in ipairs( snake ) do
if v.x == x and v.y == y then
return k
end
end
return false
end
local function processPoint( x, y )
if ( isOnSnake( x, y ) and ( #snake == 2 or isOnSnake( x, y ) ~= #snake ) ) or x < 1 or y < 1 or x > 30 or y > 20 then
lost = getTickCount( )
elseif pickupPos.x == x and pickupPos.y == y then
local snake2 = { { x = x, y = y } }
for k, v in ipairs( snake ) do
snake2[ k + 1 ] = v
end
snake = snake2
repeat
pickupPos = { x = math.random( 1, 30 ), y = math.random( 1, 20 ) }
until not isOnSnake( pickupPos.x, pickupPos.y )
else
local snake2 = { { x = x, y = y } }
for i = 1, #snake - 1 do
snake2[ i + 1 ] = snake[ i ]
end
snake = snake2
end
end
local function doSnake( )
-- process the game
local tick = getTickCount( )
if lost and tick - lost > 5000 then
toggleSnake( )
return
elseif not lost and tick - lastupdate > 100 then
lastupdate = tick
if moving == 1 then -- moving up
processPoint( snake[1].x, snake[1].y - 1 )
elseif moving == 2 then
processPoint( snake[1].x, snake[1].y + 1 )
elseif moving == 3 then
processPoint( snake[1].x - 1, snake[1].y )
elseif moving == 4 then
processPoint( snake[1].x + 1, snake[1].y )
end
end
-- draw the board, 30x20
for x = 1, 30 do
for y = 1, 20 do
local color = backgroundColor
if pickupPos.x == x and pickupPos.y == y then
color = pickupColor
else
local snakeID = isOnSnake( x, y )
if snakeID then
if lost then
color = tocolor( ( #snake - snakeID + 1 ) / #snake * 127 + 127, 0, 0, 255 )
else
color = tocolor( 0, ( #snake - snakeID + 1 ) / #snake * 127 + 127, ( #snake - snakeID + 1 ) / #snake * 127 + 128, 255 )
end
end
end
dxDrawRectangle( px + ( x - 1 ) * 21, py + ( y - 1 ) * 21, 20, 20, color, true )
end
end
for x = 0, 30 do
dxDrawLine( px - 1 + x * 21, py, px - 1 + x * 21, py + 20 * 21, lineColor, 1, true )
end
for y = 0, 20 do
dxDrawLine( px, py - 1 + y * 21, px + 30 * 21, py - 1 + y * 21, lineColor, 1, true )
end
end
local key1 = function( ) moving = 1 end
local key2 = function( ) moving = 2 end
local key3 = function( ) moving = 3 end
local key4 = function( ) moving = 4 end
function toggleSnake( )
if active then
removeEventHandler( "onClientRender", getRootElement( ), doSnake )
active = false
unbindKey( "arrow_u", "down", key1 )
unbindKey( "arrow_d", "down", key2 )
unbindKey( "arrow_l", "down", key3 )
unbindKey( "arrow_r", "down", key4 )
guiSetVisible( wInternet, true )
guiSetVisible( wComputer, true )
guiSetInputEnabled( true )
showCursor( true )
else
guiSetVisible( wInternet, false )
guiSetVisible( wComputer, false )
guiSetInputEnabled( false )
showCursor( true )
lastupdate = getTickCount( )
moving = 0
repeat
pickupPos = { x = math.random( 1, 30 ), y = math.random( 1, 20 ) }
until pickupPos.x ~= 15 or pickupPos.y ~= 10
snake = { { x = 15, y = 10 } }
bindKey( "arrow_u", "down", key1 )
bindKey( "arrow_d", "down", key2 )
bindKey( "arrow_l", "down", key3 )
bindKey( "arrow_r", "down", key4 )
active = true
lost = false
addEventHandler( "onClientRender", getRootElement( ), doSnake )
end
end
--
local height = 397
local width = 660
function www_snake_sa( )
guiSetText(internet_address_label, "Snake - Waterwolf")
guiSetText(address_bar,"www.snake.sa")
bg = guiCreateStaticImage(0,0,width,height,"websites/colours/0.png",false,internet_pane)
btn = guiCreateButton( ( width - 200 ) / 2, ( height - 50 ) / 2, 200, 50, "Play", false, bg )
addEventHandler( "onClientGUIClick", btn,
function( )
if not active then
toggleSnake( )
end
end,
false
)
end |
Formation = "double";
formationSlot({
0,
0.5,
0,
},{
0,
0,
1,
},{
0,
1,
0,
})
formationSlot({
0,
-0.5,
0,
},{
0,
0,
1,
},{
0,
1,
0,
})
|
-- TODO: **URGENT** Fix #21
-- Remake graphics again
require('prototypes.entity.remnants')
require("prototypes.entity.inserters") -- Inserters
require("prototypes.entity.miners") -- Hardened electric mining drill. Sitting alone in its own file. How sad.
require("prototypes.entity.assemblerpipes") -- Thingie for assembler pipes
local entities = {}
-- Nuclear transport belt
local nuclear_transport_belt = util.table.deepcopy(data.raw["transport-belt"]["express-transport-belt"])
nuclear_transport_belt.name = "nuclear-transport-belt"
nuclear_transport_belt.icon = "__RandomFactorioThings__/graphics/icons/nuclear-transport-belt.png"
nuclear_transport_belt.corpse = 'nuclear-transport-belt-remnants'
nuclear_transport_belt.minable.result = "nuclear-transport-belt"
nuclear_transport_belt.speed = 0.125
nuclear_transport_belt.next_upgrade = nil
nuclear_transport_belt.belt_animation_set.animation_set.filename = "__RandomFactorioThings__/graphics/entity/nuclear-transport-belt/nuclear-transport-belt.png"
nuclear_transport_belt.belt_animation_set.animation_set.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-transport-belt/hr-nuclear-transport-belt.png"
nuclear_transport_belt.related_underground_belt = 'nuclear-underground-belt'
table.insert(entities, nuclear_transport_belt)
local nuclear_underground_belt = util.table.deepcopy(data.raw["underground-belt"]["express-underground-belt"])
nuclear_underground_belt.name = "nuclear-underground-belt"
nuclear_underground_belt.icon = "__RandomFactorioThings__/graphics/icons/nuclear-underground-belt.png"
nuclear_underground_belt.corpse = 'nuclear-underground-belt-remnants'
nuclear_underground_belt.minable.result = "nuclear-underground-belt"
nuclear_underground_belt.max_distance = 11
nuclear_underground_belt.speed = 0.125
nuclear_underground_belt.next_upgrade = nil
nuclear_underground_belt.belt_animation_set = nuclear_transport_belt.belt_animation_set
nuclear_underground_belt.structure.direction_in.sheet.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_in.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/hr-nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_out.sheet.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_out.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/hr-nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_in_side_loading.sheet.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_in_side_loading.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/hr-nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_out_side_loading.sheet.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/nuclear-underground-belt-structure.png"
nuclear_underground_belt.structure.direction_out_side_loading.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-underground-belt/hr-nuclear-underground-belt-structure.png"
table.insert(entities, nuclear_underground_belt)
local nuclear_splitter = util.table.deepcopy(data.raw["splitter"]["express-splitter"])
nuclear_splitter.name = "nuclear-splitter"
nuclear_splitter.icon = "__RandomFactorioThings__/graphics/icons/nuclear-splitter.png"
nuclear_splitter.corpse = 'nuclear-splitter-remnants'
nuclear_splitter.minable.result = "nuclear-splitter"
nuclear_splitter.speed = 0.125
nuclear_splitter.next_upgrade = nil
nuclear_splitter.belt_animation_set = nuclear_transport_belt.belt_animation_set
nuclear_splitter.structure.north.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-north.png"
nuclear_splitter.structure.north.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-north.png"
nuclear_splitter.structure.east.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-east.png"
nuclear_splitter.structure.east.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-east.png"
nuclear_splitter.structure.south.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-south.png"
nuclear_splitter.structure.south.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-south.png"
nuclear_splitter.structure.west.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-west.png"
nuclear_splitter.structure.west.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-west.png"
nuclear_splitter.structure_patch.east.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-east-top_patch.png"
nuclear_splitter.structure_patch.east.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-east-top_patch.png"
nuclear_splitter.structure_patch.west.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/nuclear-splitter-west-top_patch.png"
nuclear_splitter.structure_patch.west.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-splitter/hr-nuclear-splitter-west-top_patch.png"
table.insert(entities, nuclear_splitter)
data.raw["transport-belt"]["express-transport-belt"].next_upgrade = "nuclear-transport-belt"
data.raw["underground-belt"]["express-underground-belt"].next_upgrade = "nuclear-underground-belt"
data.raw["splitter"]["express-splitter"].next_upgrade = "nuclear-splitter"
-- Nuclear robots
local nuclear_logistic_robot = util.table.deepcopy(data.raw["logistic-robot"]["logistic-robot"])
nuclear_logistic_robot.name = "nuclear-logistic-robot"
nuclear_logistic_robot.minable.result = "nuclear-logistic-robot"
nuclear_logistic_robot.max_health = 150
nuclear_logistic_robot.icon = "__RandomFactorioThings__/graphics/icons/nuclear-logistic-robot.png"
nuclear_logistic_robot.max_payload_size = 2
nuclear_logistic_robot.speed = 0.1
nuclear_logistic_robot.max_energy = "3MJ"
nuclear_logistic_robot.energy_per_move = "4kJ"
nuclear_logistic_robot.idle.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/nuclear-logistic-robot.png"
nuclear_logistic_robot.idle.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/hr-nuclear-logistic-robot.png"
nuclear_logistic_robot.idle_with_cargo.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/nuclear-logistic-robot.png"
nuclear_logistic_robot.idle_with_cargo.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/hr-nuclear-logistic-robot.png"
nuclear_logistic_robot.in_motion.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/nuclear-logistic-robot.png"
nuclear_logistic_robot.in_motion.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/hr-nuclear-logistic-robot.png"
nuclear_logistic_robot.in_motion_with_cargo.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/nuclear-logistic-robot.png"
nuclear_logistic_robot.in_motion_with_cargo.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-logistic-robot/hr-nuclear-logistic-robot.png"
table.insert(entities, nuclear_logistic_robot)
local nuclear_construction_robot = util.table.deepcopy(data.raw["construction-robot"]["construction-robot"])
nuclear_construction_robot.name = "nuclear-construction-robot"
nuclear_construction_robot.minable.result = "nuclear-construction-robot"
nuclear_construction_robot.max_health = 150
nuclear_construction_robot.icon = "__RandomFactorioThings__/graphics/icons/nuclear-construction-robot.png"
nuclear_construction_robot.max_payload_size = 2
nuclear_construction_robot.speed = 0.12
nuclear_construction_robot.max_energy = "3MJ"
nuclear_construction_robot.energy_per_move = "4kJ"
nuclear_construction_robot.idle.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/nuclear-construction-robot.png"
nuclear_construction_robot.idle.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/hr-nuclear-construction-robot.png"
nuclear_construction_robot.in_motion.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/nuclear-construction-robot.png"
nuclear_construction_robot.in_motion.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/hr-nuclear-construction-robot.png"
nuclear_construction_robot.working.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/nuclear-construction-robot-working.png"
nuclear_construction_robot.working.hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-construction-robot/hr-nuclear-construction-robot-working.png"
table.insert(entities, nuclear_construction_robot)
-- Hardened furnaces
local hardened_stone_furnace = util.table.deepcopy(data.raw["furnace"]["stone-furnace"])
hardened_stone_furnace.name = "hardened-stone-furnace"
hardened_stone_furnace.icon = "__RandomFactorioThings__/graphics/icons/hardened-stone-furnace.png"
hardened_stone_furnace.minable.result = "hardened-stone-furnace"
hardened_stone_furnace.max_health = 300
hardened_stone_furnace.crafting_speed = 1.25
hardened_stone_furnace.energy_usage = "100kW"
hardened_stone_furnace.animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/hardened-stone-furnace/hardened-stone-furnace.png"
hardened_stone_furnace.animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/hardened-stone-furnace/hr-hardened-stone-furnace.png"
table.insert(entities, hardened_stone_furnace)
local hardened_steel_furnace = util.table.deepcopy(data.raw["furnace"]["steel-furnace"])
hardened_steel_furnace.name = "hardened-steel-furnace"
hardened_steel_furnace.icon = "__RandomFactorioThings__/graphics/icons/hardened-steel-furnace.png"
hardened_steel_furnace.minable.result = "hardened-steel-furnace"
hardened_steel_furnace.max_health = 450
hardened_steel_furnace.crafting_speed = 2.5
hardened_steel_furnace.energy_usage = "100kW"
hardened_steel_furnace.animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/hardened-steel-furnace/hardened-steel-furnace.png"
hardened_steel_furnace.animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/hardened-steel-furnace/hr-hardened-steel-furnace.png"
table.insert(entities, hardened_steel_furnace)
local hardened_electric_furnace = util.table.deepcopy(data.raw["furnace"]["electric-furnace"])
hardened_electric_furnace.name = "hardened-electric-furnace"
hardened_electric_furnace.icon = "__RandomFactorioThings__/graphics/icons/hardened-electric-furnace.png"
hardened_electric_furnace.minable.result = "hardened-electric-furnace"
hardened_electric_furnace.max_health = 525
hardened_electric_furnace.crafting_speed = 2.5
hardened_electric_furnace.energy_usage = "200kW"
hardened_electric_furnace.animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/hardened-electric-furnace/hardened-electric-furnace.png"
hardened_electric_furnace.animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/hardened-electric-furnace/hr-hardened-electric-furnace.png"
table.insert(entities, hardened_electric_furnace)
-- Nuclear assembling machine
local nuclear_assembling_machine = util.table.deepcopy(data.raw["assembling-machine"]["assembling-machine-3"])
nuclear_assembling_machine.name = "nuclear-assembling-machine"
nuclear_assembling_machine.icon = "__RandomFactorioThings__/graphics/icons/nuclear-assembling-machine.png"
nuclear_assembling_machine.minable.result = "nuclear-assembling-machine"
nuclear_assembling_machine.max_health = 450
nuclear_assembling_machine.crafting_speed = 2
nuclear_assembling_machine.energy_usage = "1125kW"
nuclear_assembling_machine.module_specification.module_slots = 6
nuclear_assembling_machine.energy_source.emissions_per_minute = 1
nuclear_assembling_machine.animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/nuclear-assembling-machine/nuclear-assembling-machine.png"
nuclear_assembling_machine.animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/nuclear-assembling-machine/hr-nuclear-assembling-machine.png"
nuclear_assembling_machine.fluid_boxes[1].pipe_picture = nuclearassemblerpipepictures()
nuclear_assembling_machine.fluid_boxes[2].pipe_picture = nuclearassemblerpipepictures()
nuclear_assembling_machine.next_upgrade = mods["PlutoniumEnergy"] and "plutonium-assembling-machine"
table.insert(entities, nuclear_assembling_machine)
data.raw["assembling-machine"]["assembling-machine-3"].next_upgrade = "nuclear-assembling-machine"
-- Grinding and compressing
local macerator = util.table.deepcopy(data.raw["assembling-machine"]["centrifuge"])
macerator.name = "macerator"
macerator.icon = "__RandomFactorioThings__/graphics/icons/macerator.png"
macerator.minable.result = "macerator"
macerator.working_visualisations[2].animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/macerator/macerator-C-light.png"
macerator.working_visualisations[2].animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/macerator/hr-macerator-C-light.png"
macerator.working_visualisations[2].animation.layers[2].filename = "__RandomFactorioThings__/graphics/entity/macerator/macerator-B-light.png"
macerator.working_visualisations[2].animation.layers[2].hr_version.filename = "__RandomFactorioThings__/graphics/entity/macerator/hr-macerator-B-light.png"
macerator.working_visualisations[2].animation.layers[3].filename = "__RandomFactorioThings__/graphics/entity/macerator/macerator-A-light.png"
macerator.working_visualisations[2].animation.layers[3].hr_version.filename = "__RandomFactorioThings__/graphics/entity/macerator/hr-macerator-A-light.png"
macerator.crafting_categories = {"grinding"}
macerator.energy_usage = "150kW"
table.insert(entities, macerator)
local compressor = util.table.deepcopy(data.raw["assembling-machine"]["centrifuge"])
compressor.name = "compressor"
compressor.icon = "__RandomFactorioThings__/graphics/icons/compressor.png"
compressor.minable.result = "compressor"
compressor.working_visualisations[2].animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/compressor/compressor-C-light.png"
compressor.working_visualisations[2].animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/compressor/hr-compressor-C-light.png"
compressor.working_visualisations[2].animation.layers[2].filename = "__RandomFactorioThings__/graphics/entity/compressor/compressor-B-light.png"
compressor.working_visualisations[2].animation.layers[2].hr_version.filename = "__RandomFactorioThings__/graphics/entity/compressor/hr-compressor-B-light.png"
compressor.working_visualisations[2].animation.layers[3].filename = "__RandomFactorioThings__/graphics/entity/compressor/compressor-A-light.png"
compressor.working_visualisations[2].animation.layers[3].hr_version.filename = "__RandomFactorioThings__/graphics/entity/compressor/hr-compressor-A-light.png"
compressor.crafting_categories = {"compressing"}
compressor.energy_usage = "150kW"
compressor.module_specification.module_slots = 3
table.insert(entities, compressor)
-- Plutonium Energy integration
if mods["PlutoniumEnergy"] then
-- Plutonium assembling machine
local plutonium_assembling_machine = util.table.deepcopy(nuclear_assembling_machine)
plutonium_assembling_machine.name = "plutonium-assembling-machine"
plutonium_assembling_machine.icon = "__RandomFactorioThings__/graphics/icons/plutonium-assembling-machine.png"
plutonium_assembling_machine.minable.result = "plutonium-assembling-machine"
plutonium_assembling_machine.max_health = 500
plutonium_assembling_machine.crafting_speed = 3
plutonium_assembling_machine.energy_usage = "4.5MW"
plutonium_assembling_machine.module_specification.module_slots = 8
plutonium_assembling_machine.animation.layers[1].filename = "__RandomFactorioThings__/graphics/entity/plutonium-assembling-machine/plutonium-assembling-machine.png"
plutonium_assembling_machine.animation.layers[1].hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-assembling-machine/hr-plutonium-assembling-machine.png"
plutonium_assembling_machine.fluid_boxes[1].pipe_picture = plutoniumassemblerpipepictures()
plutonium_assembling_machine.fluid_boxes[2].pipe_picture = plutoniumassemblerpipepictures()
plutonium_assembling_machine.next_upgrade = nil
table.insert(entities, plutonium_assembling_machine)
-- Plutonium transport belt
local plutonium_transport_belt = util.table.deepcopy(nuclear_transport_belt)
plutonium_transport_belt.name = "plutonium-transport-belt"
plutonium_transport_belt.icon = "__RandomFactorioThings__/graphics/icons/plutonium-transport-belt.png"
plutonium_transport_belt.corpse = 'plutonium-transport-belt-remnants'
plutonium_transport_belt.minable.result = "plutonium-transport-belt"
plutonium_transport_belt.speed = 0.15625
plutonium_transport_belt.belt_animation_set.animation_set.filename = "__RandomFactorioThings__/graphics/entity/plutonium-transport-belt/plutonium-transport-belt.png"
plutonium_transport_belt.belt_animation_set.animation_set.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-transport-belt/hr-plutonium-transport-belt.png"
plutonium_transport_belt.related_underground_belt = 'plutonium-underground-belt'
table.insert(entities, plutonium_transport_belt)
local plutonium_underground_belt = util.table.deepcopy(nuclear_underground_belt)
plutonium_underground_belt.name = "plutonium-underground-belt"
plutonium_underground_belt.icon = "__RandomFactorioThings__/graphics/icons/plutonium-underground-belt.png"
plutonium_underground_belt.corpse = 'plutonium-underground-belt-remnants'
plutonium_underground_belt.minable.result = "plutonium-underground-belt"
plutonium_underground_belt.speed = 0.15625
plutonium_underground_belt.max_distance = 13
plutonium_underground_belt.belt_animation_set = plutonium_transport_belt.belt_animation_set
plutonium_underground_belt.structure.direction_in.sheet.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_in.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/hr-plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_out.sheet.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_out.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/hr-plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_in_side_loading.sheet.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_in_side_loading.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/hr-plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_out_side_loading.sheet.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/plutonium-underground-belt-structure.png"
plutonium_underground_belt.structure.direction_out_side_loading.sheet.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-underground-belt/hr-plutonium-underground-belt-structure.png"
table.insert(entities, plutonium_underground_belt)
local plutonium_splitter = util.table.deepcopy(nuclear_splitter)
plutonium_splitter.name = "plutonium-splitter"
plutonium_splitter.icon = "__RandomFactorioThings__/graphics/icons/plutonium-splitter.png"
plutonium_splitter.corpse = 'plutonium-splitter-remnants'
plutonium_splitter.minable.result = "plutonium-splitter"
plutonium_splitter.speed = 0.15625
plutonium_splitter.belt_animation_set = plutonium_transport_belt.belt_animation_set
plutonium_splitter.structure.north.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-north.png"
plutonium_splitter.structure.north.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-north.png"
plutonium_splitter.structure.east.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-east.png"
plutonium_splitter.structure.east.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-east.png"
plutonium_splitter.structure.south.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-south.png"
plutonium_splitter.structure.south.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-south.png"
plutonium_splitter.structure.west.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-west.png"
plutonium_splitter.structure.west.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-west.png"
plutonium_splitter.structure_patch.east.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-east-top_patch.png"
plutonium_splitter.structure_patch.east.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-east-top_patch.png"
plutonium_splitter.structure_patch.west.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/plutonium-splitter-west-top_patch.png"
plutonium_splitter.structure_patch.west.hr_version.filename = "__RandomFactorioThings__/graphics/entity/plutonium-splitter/hr-plutonium-splitter-west-top_patch.png"
table.insert(entities, plutonium_splitter)
entities[1].next_upgrade = "plutonium-transport-belt"
entities[2].next_upgrade = "plutonium-underground-belt"
entities[3].next_upgrade = "plutonium-splitter"
end
data:extend(entities)
|
return {'ril','rild','rillen','rillerig','rillettes','rillijn','rilling','rillaar','riley','rill','rilde','rilden','rille','rillend','rillerige','rilletje','rilletjes','rillijnen','rillingen','rilst','rilt','rillende','rileys','rillaarse'} |
class "PhysicsScreenEntity"
ENTITY_RECT = 1
ENTITY_CIRCLE = 2
ENTITY_MESH = 3
function PhysicsScreenEntity:__index__(name)
if name == "collisionOnly" then
return Physics2D.PhysicsScreenEntity_get_collisionOnly(self.__ptr)
end
end
function PhysicsScreenEntity:__set_callback(name,value)
if name == "collisionOnly" then
Physics2D.PhysicsScreenEntity_set_collisionOnly(self.__ptr, value)
return true
end
return false
end
function PhysicsScreenEntity:PhysicsScreenEntity(...)
for k,v in pairs(arg) do
if type(v) == "table" then
if v.__ptr ~= nil then
arg[k] = v.__ptr
end
end
end
if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then
self.__ptr = Physics2D.PhysicsScreenEntity(unpack(arg))
Polycore.__ptr_lookup[self.__ptr] = self
end
end
function PhysicsScreenEntity:getScreenEntity()
local retVal = Physics2D.PhysicsScreenEntity_getScreenEntity(self.__ptr)
if retVal == nil then return nil end
if Polycore.__ptr_lookup[retVal] ~= nil then
return Polycore.__ptr_lookup[retVal]
else
Polycore.__ptr_lookup[retVal] = ScreenEntity("__skip_ptr__")
Polycore.__ptr_lookup[retVal].__ptr = retVal
return Polycore.__ptr_lookup[retVal]
end
end
function PhysicsScreenEntity:applyTorque(torque)
local retVal = Physics2D.PhysicsScreenEntity_applyTorque(self.__ptr, torque)
end
function PhysicsScreenEntity:applyForce(force)
local retVal = Physics2D.PhysicsScreenEntity_applyForce(self.__ptr, force.__ptr)
end
function PhysicsScreenEntity:setTransform(pos, angle)
local retVal = Physics2D.PhysicsScreenEntity_setTransform(self.__ptr, pos.__ptr, angle)
end
function PhysicsScreenEntity:Update()
local retVal = Physics2D.PhysicsScreenEntity_Update(self.__ptr)
end
function PhysicsScreenEntity:__delete()
Polycore.__ptr_lookup[self.__ptr] = nil
Physics2D.delete_PhysicsScreenEntity(self.__ptr)
end
|
-- realcompass 1.23
-- This fork written by David_G (kestral246@gmail.com)
--
-- 2020-02-20
local activewidth=8 --until I can find some way to get it from minetest
minetest.register_globalstep(function(dtime)
local players = minetest.get_connected_players()
for i,player in ipairs(players) do
local gotacompass=false
local wielded=false
local activeinv=nil
local stackidx=0
--first check to see if the user has a compass, because if they don't
--there is no reason to waste time calculating bookmarks or spawnpoints.
local wielded_item = player:get_wielded_item():get_name()
if string.sub(wielded_item, 0, 12) == "realcompass:" then
--if the player is wielding a compass, change the wielded image
wielded=true
stackidx=player:get_wield_index()
gotacompass=true
else
--check to see if compass is in active inventory
if player:get_inventory() then
--is there a way to only check the activewidth items instead of entire list?
--problem being that arrays are not sorted in lua
for i,stack in ipairs(player:get_inventory():get_list("main")) do
if i<=activewidth and string.sub(stack:get_name(), 0, 12) == "realcompass:" then
activeinv=stack --store the stack so we can update it later with new image
stackidx=i --store the index so we can add image at correct location
gotacompass=true
break
end --if i<=activewidth
end --for loop
end -- get_inventory
end --if wielded else
--dont mess with the rest of this if they don't have a compass
--update to remove legacy get_look_yaw function
if gotacompass then
local dir = player:get_look_horizontal()
local angle_relative = math.deg(dir)
local compass_image = math.floor((angle_relative/22.5) + 0.5)%16
--update compass image to point at target
if wielded then
player:set_wielded_item("realcompass:"..compass_image)
elseif activeinv then
player:get_inventory():set_stack("main",stackidx,"realcompass:"..compass_image)
end --if wielded elsif activin
end --if gotacompass
end --for i,player in ipairs(players)
end) -- register_globalstep
local images = {
"realcompass_0.png",
"realcompass_1.png",
"realcompass_2.png",
"realcompass_3.png",
"realcompass_4.png",
"realcompass_5.png",
"realcompass_6.png",
"realcompass_7.png",
"realcompass_8.png",
"realcompass_9.png",
"realcompass_10.png",
"realcompass_11.png",
"realcompass_12.png",
"realcompass_13.png",
"realcompass_14.png",
"realcompass_15.png",
}
local i
for i,img in ipairs(images) do
local inv = 1
if i == 1 then
inv = 0
end
minetest.register_tool("realcompass:"..(i-1), {
description = "Real Compass",
inventory_image = img,
wield_image = img,
groups = {not_in_creative_inventory=inv}
})
end
-- crafting recipe only works if default mod present.
if minetest.get_modpath("default") ~= nil then
minetest.register_craft({
output = 'realcompass:0',
recipe = {
{'', 'default:steel_ingot', ''},
{'default:copper_ingot', 'default:glass', 'default:copper_ingot'},
{'', 'default:copper_ingot', ''}
}
})
end
|
mp = Map("pptpd", translate("PPTP VPN Server"))
mp.description = translate("PPTP VPN Server connectivity using the native built-in VPN Client on Windows/Linux or Andriod")
mp:section(SimpleSection).template = "pptp/pptp_status"
s = mp:section(NamedSection, "pptpd", "service")
s.anonymouse = true
enabled = s:option(Flag, "enabled", translate("Enable"))
enabled.default = 0
enabled.rmempty = false
localip = s:option(Value, "localip", translate("Local IP"))
localip.datatype = "ip4addr"
clientip = s:option(Value, "remoteip", translate("Client IP"))
clientip.datatype = "string"
clientip.description = translate("LAN DHCP reserved start-to-end IP addresses with the same subnet mask")
remotedns = s:option(Value, "remotedns", translate("Remote Client DNS"))
remotedns.datatype = "ip4addr"
logging = s:option(Flag, "logwtmp", translate("Debug Logging"))
logging.default = 0
logging.rmempty = false
logins = mp:section(NamedSection, "login", "login", translate("PPTP Logins"))
logins.anonymouse = true
username = logins:option(Value, "username", translate("User name"))
username.datatype = "string"
password = logins:option(Value, "password", translate("Password"))
password.password = true
return mp
|
--[[
This file loads and pre-processes cifar10 data
Kui Jia, Dacheng Tao, Shenghua Gao, and Xiangmin Xu, "Improving training of deep neural networks via Singular Value Bounding", CVPR 2017.
http://www.aperture-lab.net/research/svb
This code is based on the fb.resnet.torch package (https://github.com/facebook/fb.resnet.torch)
Copyright (c) 2016, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
--]]
local URL = 'http://torch7.s3-website-us-east-1.amazonaws.com/data/cifar-10-torch.tar.gz'
-- color statistics from the entire CIFAR-10 training set
local meanstd = { mean = {125.3, 123.0, 113.9}, std = {63.0, 62.1, 66.7} }
local t = require('Utils/' .. 'transforms')
local utils = require('Utils/' .. 'utilFuncs')
local M = {}
local imdb = torch.class('imdb', M)
local function convertToTensor(files)
local data, labels
for _, file in ipairs(files) do
local m = torch.load(file, 'ascii')
if not data then
data = m.data:t()
labels = m.labels:squeeze()
else
data = torch.cat(data, m.data:t(), 1)
labels = torch.cat(labels, m.labels:squeeze())
end
end
-- The downloaded files have labels 0-9, which do not work with CrossEntropyCriterion
labels:add(1)
return {data = data:contiguous():view(-1, 3, 32, 32), labels = labels}
end
local function loadingRawData(fileName)
print('=> Downloading CIFAR-10 dataset from ' .. URL)
local ok = os.execute('curl ' .. URL .. ' | tar xz -C Data/cifar10-raw/')
-- local ok = os.execute('tar xz -C Data/cifar10-raw/')
assert(ok == true or ok == 0, 'error downloading CIFAR-10')
print(" | combining dataset into a single file")
local trnData = convertToTensor( {
'Data/cifar10-raw/cifar-10-batches-t7/data_batch_1.t7',
'Data/cifar10-raw/cifar-10-batches-t7/data_batch_2.t7',
'Data/cifar10-raw/cifar-10-batches-t7/data_batch_3.t7',
'Data/cifar10-raw/cifar-10-batches-t7/data_batch_4.t7',
'Data/cifar10-raw/cifar-10-batches-t7/data_batch_5.t7',
} )
local testData = convertToTensor( {
'Data/cifar10-raw/cifar-10-batches-t7/test_batch.t7',
} )
print(' | saving CIFAR-10 dataset to ' .. fileName)
torch.save(fileName, {train = trnData, val = testData})
end
function imdb.create(opts, trnValSplit) -- will be called when building up multi-threaded dataLoader
local tmpFileName = paths.concat('Data', 'cifar10.t7')
if not paths.filep(tmpFileName) then
loadingRawData(tmpFileName) -- downloading the data and combining and saving as a single file 'cifar10.t7'
end
local images = torch.load(tmpFileName) -- loading the train and val data
local imdbTrnVal = M.imdb(images, opts, trnValSplit) -- returning imdb class instance for either 'train' or 'val' data
return imdbTrnVal
end
function imdb:__init(images, opts, trnValSplit)
assert(images[trnValSplit], trnValSplit)
self.images = images[trnValSplit]
self.trnValSplit = trnValSplit
end
function imdb:get(i)
local img = self.images.data[i]:float()
local label = self.images.labels[i]
return {input = img, target = label}
end
function imdb:size()
return self.images.data:size(1) -- the number of images
end
function imdb:preprocess()
if self.trnValSplit == 'train' then
return t.Compose{
-- t.ColorNormalize(meanstd),
t.HorizontalFlip(0.5),
t.RandomCrop(32, 4),
}
elseif self.trnValSplit == 'val' then
return t.IdentityMap() -- do nothing transformation
-- return t.ColorNormalize(meanstd)
else
error('invalid split: ' .. self.trnValSplit)
end
end
return M.imdb |
local CorePackages = game:GetService("CorePackages")
local AppTempCommon = CorePackages.AppTempCommon
local Modules = game:GetService("CoreGui").RobloxGui.Modules
local ShareGame = Modules.Settings.Pages.ShareGame
local Immutable = require(AppTempCommon.Common.Immutable)
local ReceivedUserInviteStatus = require(ShareGame.Actions.ReceivedUserInviteStatus)
return function(state, action)
state = state or {}
if action.type == ReceivedUserInviteStatus.name then
state = Immutable.Set(state, action.userId, action.inviteStatus)
end
return state
end |
local K = unpack(KkthnxUI)
local Module = K:GetModule("Auras")
if K.Class ~= "HUNTER" then
return
end
local playerGUID = _G.UnitGUID("player")
local CreateFrame = _G.CreateFrame
local GetSpecialization = _G.GetSpecialization
local IsPlayerSpell = _G.IsPlayerSpell
local GetSpellTexture = _G.GetSpellTexture
local IsEquippedItem = _G.IsEquippedItem
local GetSpellCost = {
[53351] = 10, -- 杀戮射击
[19434] = 35, -- 瞄准射击
[185358] = 20, -- 奥术射击
[257620] = 20, -- 多重射击
[271788] = 10, -- 毒蛇钉刺
[212431] = 20, -- 爆炸射击
[186387] = 10, -- 爆裂射击
[157863] = 35, -- 复活宠物
[131894] = 20, -- 夺命黑鸦
[120360] = 30, -- 弹幕射击
[342049] = 20, -- 奇美拉射击
[355589] = 15, -- 哀痛箭
}
function Module:UpdateFocusCost(unit, _, spellID)
if unit ~= "player" then
return
end
local focusCal = Module.MMFocus
local cost = GetSpellCost[spellID]
if cost then
focusCal.cost = focusCal.cost + cost
end
if spellID == 19434 then
--print("带着技巧读条:"..tostring(focusCal.isTrickCast), "消耗技巧层数:"..focusCal.trickActive)
if (focusCal.isTrickCast and focusCal.trickActive == 1) or (not focusCal.isTrickCast and focusCal.trickActive == 0) then
focusCal.cost = 35
--print("此时重置集中值为35")
end
end
focusCal:SetFormattedText("%d/40", focusCal.cost % 40)
end
function Module:ResetFocusCost()
Module.MMFocus.cost = 0
Module.MMFocus:SetFormattedText("%d/40", Module.MMFocus.cost % 40)
end
function Module:ResetOnRaidEncounter(_, _, _, groupSize)
if groupSize and groupSize > 5 then
Module:ResetFocusCost()
end
end
local eventSpentIndex = {
["SPELL_AURA_APPLIED"] = 1,
["SPELL_AURA_REFRESH"] = 2,
["SPELL_AURA_REMOVED"] = 0,
}
function Module:CheckTrickState(...)
local _, eventType, _, sourceGUID, _, _, _, _, _, _, _, spellID = ...
if eventSpentIndex[eventType] and spellID == 257622 and sourceGUID == playerGUID then
Module.MMFocus.trickActive = eventSpentIndex[eventType]
end
end
function Module:StartAimedShot(unit, _, spellID)
if unit ~= "player" then
return
end
if spellID == 19434 then
Module.MMFocus.isTrickCast = Module.MMFocus.trickActive ~= 0
end
end
local hunterSets = { 188856, 188858, 188859, 188860, 188861 }
function Module:CheckSetsCount()
local count = 0
for _, itemID in pairs(hunterSets) do
if IsEquippedItem(itemID) then
count = count + 1
end
end
if count < 4 then
Module.MMFocus:Hide()
K:UnregisterEvent("UNIT_SPELLCAST_START", Module.StartAimedShot)
K:UnregisterEvent("UNIT_SPELLCAST_SUCCEEDED", Module.UpdateFocusCost)
K:UnregisterEvent("PLAYER_DEAD", Module.ResetFocusCost)
K:UnregisterEvent("PLAYER_ENTERING_WORLD", Module.ResetFocusCost)
K:UnregisterEvent("ENCOUNTER_START", Module.ResetOnRaidEncounter)
K:UnregisterEvent("CLEU", Module.CheckTrickState)
else
Module.MMFocus:Show()
K:RegisterEvent("UNIT_SPELLCAST_START", Module.StartAimedShot)
K:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED", Module.UpdateFocusCost)
K:RegisterEvent("PLAYER_DEAD", Module.ResetFocusCost)
K:RegisterEvent("PLAYER_ENTERING_WORLD", Module.ResetFocusCost)
K:RegisterEvent("ENCOUNTER_START", Module.ResetOnRaidEncounter)
K:RegisterEvent("CLEU", Module.CheckTrickState)
end
end
local oldSpec
function Module:ToggleFocusCalculation()
if not Module.MMFocus then
return
end
local spec = GetSpecialization()
-- if C["Auras"].MMT29X4 and spec == 2 then
if spec == 2 then
if self ~= "PLAYER_SPECIALIZATION_CHANGED" or spec ~= oldSpec then -- don't reset when talent changed only
Module:ResetFocusCost() -- reset calculation when switch on
end
Module.MMFocus:Show()
Module:CheckSetsCount()
K:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", Module.CheckSetsCount)
else
K:UnregisterEvent("PLAYER_EQUIPMENT_CHANGED", Module.CheckSetsCount)
end
oldSpec = spec
end
function Module:PostCreateLumos(self)
local iconSize = self.lumos[1]:GetWidth()
local boom = CreateFrame("Frame", nil, self.Health)
boom:SetSize(iconSize, iconSize)
boom:SetPoint("BOTTOM", self.Health, "TOP", 0, 5)
boom.CD = CreateFrame("Cooldown", nil, boom, "CooldownFrameTemplate")
boom.CD:SetAllPoints()
boom.CD:SetReverse(true)
boom.Icon = boom:CreateTexture(nil, "ARTWORK")
boom.Icon:SetAllPoints()
boom.Icon:SetTexCoord(unpack(K.TexCoords))
boom:CreateShadow()
boom:Hide()
self.boom = boom
-- MM hunter T29 4sets
Module.MMFocus = K.CreateFontString(self.Health, 16)
Module.MMFocus:ClearAllPoints()
Module.MMFocus:SetPoint("BOTTOM", self.Health, "TOP", 0, 5)
Module.MMFocus.trickActive = 0
Module:ToggleFocusCalculation()
K:RegisterEvent("PLAYER_SPECIALIZATION_CHANGED", Module.ToggleFocusCalculation)
end
function Module:PostUpdateVisibility(self)
if self.boom then
self.boom:Hide()
end
end
local function GetUnitAura(unit, spell, filter)
return Module:GetUnitAura(unit, spell, filter)
end
local function UpdateCooldown(button, spellID, texture)
return Module:UpdateCooldown(button, spellID, texture)
end
local function UpdateBuff(button, spellID, auraID, cooldown, isPet, glow)
return Module:UpdateAura(button, isPet and "pet" or "player", auraID, "HELPFUL", spellID, cooldown, glow)
end
local function UpdateDebuff(button, spellID, auraID, cooldown, glow)
return Module:UpdateAura(button, "target", auraID, "HARMFUL", spellID, cooldown, glow)
end
local function UpdateSpellStatus(button, spellID)
button.Icon:SetTexture(GetSpellTexture(spellID))
if IsUsableSpell(spellID) then
button.Icon:SetDesaturated(false)
else
button.Icon:SetDesaturated(true)
end
end
local boomGroups = {
[270339] = 186270,
[270332] = 259489,
[271049] = 259491,
}
function Module:ChantLumos(self)
local spec = GetSpecialization()
if spec == 1 then
UpdateCooldown(self.lumos[1], 34026, true)
UpdateCooldown(self.lumos[2], 217200, true)
UpdateBuff(self.lumos[3], 106785, 272790, false, true, "END")
UpdateBuff(self.lumos[4], 19574, 19574, true, false, true)
UpdateBuff(self.lumos[5], 193530, 193530, true, false, true)
elseif spec == 2 then
UpdateCooldown(self.lumos[1], 19434, true)
UpdateCooldown(self.lumos[2], 257044, true)
UpdateBuff(self.lumos[3], 257622, 257622)
do
local button = self.lumos[4]
if IsPlayerSpell(260402) then
UpdateBuff(button, 260402, 260402, true, false, true)
elseif IsPlayerSpell(321460) then
UpdateCooldown(button, 53351)
UpdateSpellStatus(button, 53351)
else
UpdateBuff(button, 260242, 260242)
end
end
UpdateBuff(self.lumos[5], 288613, 288613, true, false, true)
elseif spec == 3 then
UpdateDebuff(self.lumos[1], 259491, 259491, false, "END")
do
local button = self.lumos[2]
if IsPlayerSpell(260248) then
UpdateBuff(button, 260248, 260249)
elseif IsPlayerSpell(162488) then
UpdateDebuff(button, 162488, 162487, true)
else
UpdateDebuff(button, 131894, 131894, true)
end
end
do
local button = self.lumos[3]
local boom = self.boom
if IsPlayerSpell(271014) then
boom:Show()
local name, _, duration, expire, caster, spellID = GetUnitAura("target", 270339, "HARMFUL")
if not name then
name, _, duration, expire, caster, spellID = GetUnitAura("target", 270332, "HARMFUL")
end
if not name then
name, _, duration, expire, caster, spellID = GetUnitAura("target", 271049, "HARMFUL")
end
if name and caster == "player" then
boom.Icon:SetTexture(GetSpellTexture(boomGroups[spellID]))
boom.CD:SetCooldown(expire - duration, duration)
boom.CD:Show()
boom.Icon:SetDesaturated(false)
else
local texture = GetSpellTexture(259495)
if texture == GetSpellTexture(270323) then
boom.Icon:SetTexture(GetSpellTexture(259489))
elseif texture == GetSpellTexture(271045) then
boom.Icon:SetTexture(GetSpellTexture(259491))
else
boom.Icon:SetTexture(GetSpellTexture(186270)) -- 270335
end
boom.Icon:SetDesaturated(true)
end
UpdateCooldown(button, 259495, true)
else
boom:Hide()
UpdateDebuff(button, 259495, 269747, true)
end
end
do
local button = self.lumos[4]
if IsPlayerSpell(260285) then
UpdateBuff(button, 260285, 260286)
elseif IsPlayerSpell(269751) then
UpdateCooldown(button, 269751, true)
else
UpdateBuff(button, 259387, 259388, false, false, "END")
end
end
UpdateBuff(self.lumos[5], 266779, 266779, true, false, true)
end
end
|
for i,v in ipairs(a) do print(v) end |
--[[ Copyright (c) 2017 David-John Miller AKA Anoyomouse
* rewritten by Optera 2019
*
* Part of the Warehousing mod
*
* See License.txt in the project directory for license information.
--]]
local warehouse_slots = 1800
local storehouse_slots = 450
local storage_warehouse_slots = 2000
local storage_storehouse_slots = 500
-- Support legacy mode
if settings.startup["Warehousing-sixteen-mode"].value then
warehouse_slots = 800
storehouse_slots = 150
storage_warehouse_slots = 2000
storage_storehouse_slots = 300
end
-- generate base storehouse and warehouse
data:extend({
{
type = "container",
name = "warehouse-basic",
icon = "__Warehousing__/graphics/icons/warehouse-basic.png",
icon_size = 32,
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {mining_time = 2, result = "warehouse-basic"},
max_health = 450,
corpse = "big-remnants",
dying_explosion = "medium-explosion",
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
resistances =
{
{
type = "fire",
percent = 90
}
},
collision_box = {{-2.7, -2.7}, {2.7, 2.7}},
selection_box = {{-3.0, -3.0}, {3.0, 3.0}},
fast_replaceable_group = "container",
inventory_size = warehouse_slots,
scale_info_icons = settings.startup["Warehousing-icon-scaling"].value,
picture =
{
filename = "__Warehousing__/graphics/entity/warehouse-basic.png",
priority = "high",
width = 260,
height = 240,
shift = {1.0, -0.3},
},
circuit_wire_max_distance = 7.5,
circuit_wire_connection_point =
{
shadow =
{
red = {2.01, 0.6},
green = {2.52, 0.6}
},
wire =
{
red = {1.71, 0.3},
green = {2.22, 0.3}
}
},
},
{
type = "container",
name = "storehouse-basic",
icon = "__Warehousing__/graphics/icons/storehouse-basic.png",
icon_size = 32,
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {mining_time = 2, result = "storehouse-basic"},
max_health = 250,
corpse = "big-remnants",
dying_explosion = "medium-explosion",
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
resistances =
{
{
type = "fire",
percent = 90
}
},
collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
fast_replaceable_group = "container",
inventory_size = storehouse_slots,
scale_info_icons = settings.startup["Warehousing-icon-scaling"].value,
picture =
{
filename = "__Warehousing__/graphics/entity/storehouse-basic.png",
priority = "high",
width = 129,
height = 100,
shift = {0.421875, 0},
},
circuit_wire_max_distance = 7.5,
circuit_wire_connection_point =
{
shadow =
{
red = {0.26, -0.6},
green = {0.36, -0.6}
},
wire =
{
red = {-0.16, -0.9},
green = {0.16, -0.9}
}
},
},
})
-- generate logistic variants
function createLogisticContainer(name, logistic_type)
local p = table.deepcopy(data.raw["container"][name.."-basic"])
p.name = name.."-"..logistic_type
p.minable.result = p.name
p.icon = "__Warehousing__/graphics/icons/"..p.name..".png"
p.picture.filename = "__Warehousing__/graphics/entity/"..p.name..".png"
p.type = "logistic-container"
p.logistic_mode = logistic_type
return p
end
local storehouse_active_provider = createLogisticContainer("storehouse", "active-provider")
local storehouse_passive_provider = createLogisticContainer("storehouse", "passive-provider")
local storehouse_storage = createLogisticContainer("storehouse", "storage")
storehouse_storage.inventory_size = storage_storehouse_slots
storehouse_storage.logistic_slots_count = 1
local storehouse_buffer = createLogisticContainer("storehouse", "buffer")
storehouse_buffer.logistic_slots_count = 12
local storehouse_requester = createLogisticContainer("storehouse", "requester")
storehouse_requester.logistic_slots_count = 12
local warehouse_active_provider = createLogisticContainer("warehouse", "active-provider")
local warehouse_passive_provider = createLogisticContainer("warehouse", "passive-provider")
local warehouse_storage = createLogisticContainer("warehouse", "storage")
warehouse_storage.inventory_size = storage_warehouse_slots
warehouse_storage.logistic_slots_count = 1
local warehouse_buffer = createLogisticContainer("warehouse", "buffer")
warehouse_buffer.logistic_slots_count = 12
local warehouse_requester = createLogisticContainer("warehouse", "requester")
warehouse_requester.logistic_slots_count = 12
data:extend({
storehouse_active_provider,
storehouse_passive_provider,
storehouse_storage,
storehouse_buffer,
storehouse_requester,
warehouse_active_provider,
warehouse_passive_provider,
warehouse_storage,
warehouse_buffer,
warehouse_requester,
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.