content
stringlengths 5
1.05M
|
|---|
return {
{
Index= 12,
PointerLocation= 584724,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 61,
PointerLocation= 585704,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 98,
PointerLocation= 586444,
OldPointer= 235659,
Label= "L1018"
},
{
Index= 105,
PointerLocation= 586584,
OldPointer= 236372,
Label= "L1019"
},
{
Index= 106,
PointerLocation= 586604,
OldPointer= 236624,
Label= "L1020"
},
{
Index= 128,
PointerLocation= 587044,
OldPointer= 240598,
Label= "L1021"
},
{
Index= 147,
PointerLocation= 587424,
OldPointer= 390119,
Label= "L1022"
},
{
Index= 162,
PointerLocation= 587724,
OldPointer= 240598,
Label= "L1021"
},
{
Index= 226,
PointerLocation= 589004,
OldPointer= 258297,
Label= "L1023"
},
{
Index= 248,
PointerLocation= 589444,
OldPointer= 260046,
Label= "L1024"
},
{
Index= 249,
PointerLocation= 589464,
OldPointer= 260495,
Label= "L1025"
},
{
Index= 250,
PointerLocation= 589484,
OldPointer= 260677,
Label= "L1026"
},
{
Index= 251,
PointerLocation= 589504,
OldPointer= 261200,
Label= "L1027"
},
{
Index= 252,
PointerLocation= 589524,
OldPointer= 261027,
Label= "L1028"
},
{
Index= 253,
PointerLocation= 589544,
OldPointer= 261457,
Label= "L1029"
},
{
Index= 259,
PointerLocation= 589664,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 268,
PointerLocation= 589844,
OldPointer= 272341,
Label= "L1030"
},
{
Index= 275,
PointerLocation= 589984,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 286,
PointerLocation= 590204,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 302,
PointerLocation= 590524,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 406,
PointerLocation= 592604,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 419,
PointerLocation= 592864,
OldPointer= 441774,
Label= "L1031"
},
{
Index= 436,
PointerLocation= 593204,
OldPointer= 460231,
Label= "L1032"
},
{
Index= 450,
PointerLocation= 593484,
OldPointer= 458839,
Label= "L1033"
},
{
Index= 479,
PointerLocation= 594064,
OldPointer= 390868,
Label= "L1034"
},
{
Index= 488,
PointerLocation= 594244,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 506,
PointerLocation= 594604,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 595,
PointerLocation= 596384,
OldPointer= 390188,
Label= "L1035"
},
{
Index= 596,
PointerLocation= 596404,
OldPointer= 390296,
Label= "L1036"
},
{
Index= 597,
PointerLocation= 596424,
OldPointer= 390350,
Label= "L1037"
},
{
Index= 598,
PointerLocation= 596444,
OldPointer= 390404,
Label= "L1038"
},
{
Index= 599,
PointerLocation= 596464,
OldPointer= 390242,
Label= "L1039"
},
{
Index= 611,
PointerLocation= 596704,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 645,
PointerLocation= 597384,
OldPointer= 458915,
Label= "L1040"
},
{
Index= 671,
PointerLocation= 597904,
OldPointer= 388441,
Label= "L1041"
},
{
Index= 716,
PointerLocation= 598804,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 728,
PointerLocation= 599044,
OldPointer= 305567,
Label= "L1042"
},
{
Index= 734,
PointerLocation= 599164,
OldPointer= 441819,
Label= "L1043"
},
{
Index= 750,
PointerLocation= 599484,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 827,
PointerLocation= 601024,
OldPointer= 458879,
Label= "L1044"
},
{
Index= 839,
PointerLocation= 601264,
OldPointer= 320938,
Label= "L1045"
},
{
Index= 849,
PointerLocation= 601464,
OldPointer= 323106,
Label= "L1046"
},
{
Index= 855,
PointerLocation= 601584,
OldPointer= 323461,
Label= "L1047"
},
{
Index= 893,
PointerLocation= 602344,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 908,
PointerLocation= 602644,
OldPointer= 332004,
Label= "L1048"
},
{
Index= 937,
PointerLocation= 603224,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 940,
PointerLocation= 603284,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1009,
PointerLocation= 604664,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1014,
PointerLocation= 604764,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1022,
PointerLocation= 604924,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1037,
PointerLocation= 605224,
OldPointer= 342291,
Label= "L1049"
},
{
Index= 1107,
PointerLocation= 606624,
OldPointer= 350557,
Label= "L1050"
},
{
Index= 1108,
PointerLocation= 606644,
OldPointer= 350557,
Label= "L1050"
},
{
Index= 1109,
PointerLocation= 606664,
OldPointer= 350557,
Label= "L1050"
},
{
Index= 1127,
PointerLocation= 607024,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1150,
PointerLocation= 607484,
OldPointer= 353012,
Label= "L1051"
},
{
Index= 1206,
PointerLocation= 608604,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1250,
PointerLocation= 609484,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1251,
PointerLocation= 609504,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1252,
PointerLocation= 609524,
OldPointer= 358136,
Label= "L1053"
},
{
Index= 1253,
PointerLocation= 609544,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1254,
PointerLocation= 609564,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1255,
PointerLocation= 609584,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1256,
PointerLocation= 609604,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1257,
PointerLocation= 609624,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1258,
PointerLocation= 609644,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1259,
PointerLocation= 609664,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1261,
PointerLocation= 609704,
OldPointer= 357492,
Label= "L1052"
},
{
Index= 1299,
PointerLocation= 610464,
OldPointer= 363364,
Label= "L1054"
},
{
Index= 1320,
PointerLocation= 610884,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1358,
PointerLocation= 611644,
OldPointer= 441668,
Label= "L1055"
},
{
Index= 1375,
PointerLocation= 611984,
OldPointer= 437286,
Label= "L1017"
},
{
Index= 1406,
PointerLocation= 612604,
OldPointer= 441668,
Label= "L1055"
}
}
|
if not modules then modules = { } end modules ['t-annotation'] = {
version = 1.000,
comment = "Annotations",
author = "Wolfgang Schuster",
copyright = "Wolfgang Schuster",
license = "GNU General Public License"
}
thirddata = thirddata or {}
thirddata.annotation = thirddata.annotation or {}
local annotation = thirddata.annotation
local variables = interfaces.variables
local format = string.format
local gsub = string.gsub
local rep = string.rep
local validstring = string.valid
local datasets = job.datasets
local v_yes = variables.yes
local v_no = variables.no
local v_auto = variables.auto
local v_paragraph = variables.paragraph
local v_text = variables.text
local v_command = variables.command
local v_vertical = variables.vertical
local v_horizontal = variables.horizontal
local v_annotation = variables.annotation
local v_buffer = variables.buffer
local texsprint = tex.sprint
local ctxcatcodes = tex.ctxcatcodes
local txtcatcodes = tex.txtcatcodes
-- Collect the content of the environment
local data = { }
function annotation.erasedata(name)
data[name] = nil
end
function annotation.getdata(name)
local data = data[name]
return data and data.content or ""
end
function annotation.printdata(environment,name)
local content, catcodes
if tex.conditionals['c_annotation_buffer'] and name ~= "" then
content = datasets.getdata(environment,name,"content") or ""
catcodes = datasets.getdata(environment,name,"catcodes") or ""
else
content = data[name] and data[name]["content"] or ""
catcodes = data[name] and data[name]["catcodes"] or ""
end
if catcodes == txtcatcodes then
context.pushcatcodes(txtcatcodes)
else
context.pushcatcodes(ctxcatcodes)
end
if tex.conditionals['c_annotation_inline'] then
context(content:strip()) -- remove leading/trailing spaces
else
context.viafile(content,format("annotation.%s",validstring(name,"noname")))
end
context.popcatcodes()
end
function annotation.parameters(environment,name)
local data = data[name]
local parameters = data and data.parameters or ""
texsprint(ctxcatcodes,parameters)
end
function annotation.dataset(environment,name,parameters,content,catcodes)
datasets.setdata {
name = environment,
tag = name,
data = {
parameters = parameters,
content = content,
catcodes = catcodes
}
}
end
function annotation.collectdata(environment,name,parameters,content,begintag,endtag,catcodes)
local oldcontent = annotation.getdata(name)
local content = content
local parameters = parameters
local catcodes = catcodes
local nesting = false
if oldcontent == "" then
-- no nested environment
else
content = oldcontent .. endtag .. " " .. content
end
if select(2,gsub(content,begintag,begintag)) > select(2,gsub(content,endtag,endtag)) then
nesting = true
else
nesting = false
end
if not nesting and name ~= "" then
annotation.dataset(environment,name,parameters,content,catcodes)
end
data[name] = { parameters = parameters, content = content, catcodes = catcodes }
commands.doifelse(nesting)
end
function annotation.savedata(environment,name,parameters,content,catcodes)
data[name] = { parameters = parameters, content = content, catcodes = catcodes }
end
-- Write the content of the environment to a file
annotation.empty = true
function annotation.open()
annotation.export = io.open(file.addsuffix(table.concat({tex.jobname,"annotation"},"-"),"txt"),"wb")
end
function annotation.write(title,content)
local title, content = title:strip(), content
if annotation.empty == true then
annotation.open()
annotation.empty = false
else
annotation.export:write("\n\n")
end
if title ~= "" then
annotation.export:write(title)
annotation.export:write("\n",rep("-",#title),"\n\n")
content = content:gsub(" \\par ","\n\n")
annotation.export:write(content)
end
end
--~ function annotation.write(title,content)
--~ local title, content = title:strip(), content
--~ if annotation.empty == true then
--~ annotation.open()
--~ annotation.empty = false
--~ else
--~ annotation.export:write("\n")
--~ end
--~ annotation.export:write(title.." "..content)
--~ end
|
require "globals" -- we now require globals
local love = require "love"
local Lazer = require "objects/Lazer" -- since we'll be using lazers
function Player()
local SHIP_SIZE = 30
local VIEW_ANGLE = math.rad(90)
local LAZER_DISTANCE = 0.6
local MAX_LAZERS = 10
return {
x = love.graphics.getWidth() / 2,
y = love.graphics.getHeight() / 2,
radius = SHIP_SIZE / 2,
angle = VIEW_ANGLE,
rotation = 0,
thrusting = false,
lazers = {},
thrust = {
x = 0,
y = 0,
speed = 5,
big_flame = false,
flame = 2.0
},
draw_flame_thrust = function (self, fillType, color)
love.graphics.setColor(color)
love.graphics.polygon(
fillType,
self.x - self.radius * (2 / 3 * math.cos(self.angle) + 0.5 * math.sin(self.angle)),
self.y + self.radius * (2 / 3 * math.sin(self.angle) - 0.5 * math.cos(self.angle)),
self.x - self.radius * self.thrust.flame * math.cos(self.angle),
self.y + self.radius * self.thrust.flame * math.sin(self.angle),
self.x - self.radius * (2 / 3 * math.cos(self.angle) - 0.5 * math.sin(self.angle)),
self.y + self.radius * (2 / 3 * math.sin(self.angle) + 0.5 * math.cos(self.angle))
)
end,
shootLazer = function (self)
if (#self.lazers <= MAX_LAZERS) then
-- lazer spawn from front of ship
table.insert(self.lazers, Lazer(
self.x + ((4 / 3) * self.radius) * math.cos(self.angle),
self.y - ((4 / 3) * self.radius) * math.sin(self.angle),
self.angle
))
end
end,
destroyLazer = function (self, index)
table.remove(self.lazers, index)
end,
draw = function (self, faded)
local opacity = 1
if faded then
opacity = 0.2
end
if self.thrusting then
if not self.thrust.big_flame then
self.thrust.flame = self.thrust.flame - 1 / love.timer.getFPS()
if self.thrust.flame < 1.5 then
self.thrust.big_flame = true
end
else
self.thrust.flame = self.thrust.flame + 1 / love.timer.getFPS()
if self.thrust.flame > 2.5 then
self.thrust.big_flame = false
end
end
self:draw_flame_thrust("fill", {255/255 ,102/255 ,25/255})
self:draw_flame_thrust("line", {1, 0.16, 0})
end
if show_debugging then -- changed to global show_debugging
love.graphics.setColor(1, 0, 0)
love.graphics.rectangle( "fill", self.x - 1, self.y - 1, 2, 2 )
love.graphics.circle("line", self.x, self.y, self.radius)
end
love.graphics.setColor(1, 1, 1, opacity)
love.graphics.polygon(
"line",
self.x + ((4 / 3) * self.radius) * math.cos(self.angle),
self.y - ((4 / 3) * self.radius) * math.sin(self.angle),
self.x - self.radius * (2 / 3 * math.cos(self.angle) + math.sin(self.angle)),
self.y + self.radius * (2 / 3 * math.sin(self.angle) - math.cos(self.angle)),
self.x - self.radius * (2 / 3 * math.cos(self.angle) - math.sin(self.angle)),
self.y + self.radius * (2 / 3 * math.sin(self.angle) + math.cos(self.angle))
)
-- draw lazers
for _, lazer in pairs(self.lazers) do
lazer:draw(faded)
end
end,
movePlayer = function (self)
local FPS = love.timer.getFPS()
local friction = 0.7
self.rotation = 360 / 180 * math.pi / FPS
if love.keyboard.isDown("a") or love.keyboard.isDown("left") or love.keyboard.isDown("kp4") then
self.angle = self.angle + self.rotation
end
if love.keyboard.isDown("d") or love.keyboard.isDown("right") or love.keyboard.isDown("kp6") then
self.angle = self.angle - self.rotation
end
if self.thrusting then
self.thrust.x = self.thrust.x + self.thrust.speed * math.cos(self.angle) / FPS
self.thrust.y = self.thrust.y - self.thrust.speed * math.sin(self.angle) / FPS
else
if self.thrust.x ~= 0 or self.thrust.y ~= 0 then
self.thrust.x = self.thrust.x - friction * self.thrust.x / FPS
self.thrust.y = self.thrust.y - friction * self.thrust.y / FPS
end
end
self.x = self.x + self.thrust.x
self.y = self.y + self.thrust.y
if self.x + self.radius < 0 then
self.x = love.graphics.getWidth() + self.radius
elseif self.x - self.radius > love.graphics.getWidth() then
self.x = -self.radius
end
if self.y + self.radius < 0 then
self.y = love.graphics.getHeight() + self.radius
elseif self.y - self.radius > love.graphics.getHeight() then
self.y = -self.radius
end
for index, lazer in pairs(self.lazers) do
if (lazer.distance > LAZER_DISTANCE * love.graphics.getWidth()) and (lazer.exploading == 0) then -- we now include if lazer exploading == 0
lazer:expload()-- we now instead expload the lazer
end
if lazer.exploading == 0 then -- 0 -> lazer not exploading
lazer:move()
elseif lazer.exploading == 2 then -- 2 -> lazer is done exploading
self.destroyLazer(self, index)
end
end
end
}
end
return Player
|
local colors = {
none = "NONE",
bg = "#191622",
bg_dark = "#13111B",
bg_darker = "#15121E",
bg_light = "#201B2D",
bg_lighter = "#252131",
fg = "#E1E1E6",
comment = "#483C67",
selection = "#41414D",
cyan = "#78D1E1",
pink = "#FF79C6",
purple = "#988BC7",
orange = "#E89E64",
yellow = "#E7DE79",
green = "#67E480",
red = "#E96379",
git = { add = "#67E480", change = "#78D1E1", delete = "#ED4556", conflict = "#BB7A61" },
}
return colors
|
local loop_plugins = {
entities = {
provides = "entity",
controls = function()
return {
{
type = "drop-down",
ref = { "entity_type" },
items = {
"container", "storage-tank",
"any-machine", "assembling-machine", "furnace",
"constant-combinator", "programmable-speaker",
"lamp", "radar",
"vehicle"
},
selected_index = 1
}
-- TODO: generic component for name search: text input
-- (contains / starts with / exact match / fuzzy search, default to fuzzy here)
-- fuzzy: https://codereview.stackexchange.com/questions/111957/vc-as-in-vancouver-or-valencia
}
end,
func = function(search)
-- TODO: Search in area:
-- local cursor_stack = player.cursor_stack
-- cursor_stack.clear()
-- cursor_stack.set_stack({name="search-engine-area-filter", type="selection-tool", count = 1})
-- TODO: Support ghosts somehow? Especially showing what kind of ghost it is
search.params.force = search.player.force
local drop_down = search.gui_loop_params.entity_type
search.params.type = drop_down.items[drop_down.selected_index]
if search.params.type == "any-machine" then
search.params.type = {"assembling-machine","furnace"}
elseif search.params.type == "vehicle" then
search.params.type = {"car","tank","spidertron"}
end
return search.player.surface.find_entities_filtered(search.params)
end
},
recipes = {
provides = "recipe",
controls = function()
return {
-- enabled, containing ingredient/product/anywhere
}
end,
func = function()
-- TODO: Use LuaGameScript.get_filtered_recipe_prototypes
return game.recipe_prototypes
end
}
}
local function gui_elements()
local r = {}
for k, v in pairs(loop_plugins) do
table.insert(r, {
type = "button",
caption = k,
tags = { loop_id = k, provides = v.provides }
})
end
return r
end
local function create_loop(loop_id, search)
return loop_plugins[loop_id].func(search)
end
local function provides(loop_id)
return loop_plugins[loop_id].provides
end
local function controls(loop_id, search)
return loop_plugins[loop_id].controls(search)
end
return {
controls = controls,
gui_elements = gui_elements,
provides = provides,
create_loop = create_loop
}
|
--
-- User: lishulong
-- Date: 2018/8/21
-- Time: 下午4:45
-- Email: lishulong.never@gmail.com
-- Description:
--
rs = 10
if rs == 10 then print('rs is 10') end
if rs > 10 then print('rs > 10') elseif rs < 10 then print('rs < 10') else print('rs == 10') end
-- 循环
i = 10
while (i > 0) do
i = i - 1
print(i)
end
-- lua 语言没有 continue
--repeat
a = 10
--repeat
-- print(a)
-- a = a - 1
-- if a == 0 then return false end
--until false
repeat
print(a)
a = a - 1
until a == 0
--419801
for var = 1, 10, 2 do print(i) end
local a = {"a", "b", "c", "d"}
for i, v in ipairs(a) do
print("index:", i, " value:", v)
end
|
-- Set leader key
vim.g.mapleader = ' '
-- Refresh config
Map_n { '<F5>', ':luafile %<CR>' }
Map_i { '<F5>', ':luafile %<CR>' }
-- Buffer keys
-- new buffer
Map_n { '<Leader>bN', ':enew<CR>' }
-- close/delete buffer
Map_n { '<Leader>bx', ':bd!<CR>' }
-- Switch buffer
-- previously visited buffer
Map_n { '<Leader>bb', ':b#<CR>' }
-- next buffer
Map_n { '<Leader>bn', ':bn<CR>' }
-- preivous buffer
Map_n { '<Leader>bp', ':bp<CR>' }
-- Window keys
-- Move between window
-- move up
Map_n { '<C-K>', '<C-W><C-K>' }
Map_n { '<Leader>wk', '<C-W><C-K>' }
-- move down
Map_n { '<C-J>', '<C-W><C-J>' }
Map_n { '<Leader>wj', '<C-W><C-J>' }
-- move left
Map_n { '<C-H>', '<C-W><C-H>' }
Map_n { '<Leader>wh', '<C-W><C-H>' }
-- move right
Map_n { '<C-L>', '<C-W><C-L>' }
Map_n { '<Leader>wl', '<C-W><C-L>' }
-- Split window
-- horizontal/below split
Map_n { '<Leader>ws', ':split<CR>' }
Map_n { '<Leader>s', ':split<CR>' }
-- vertical/right split
Map_n { '<Leader>wv', ':vsplit<CR>' }
Map_n { '<Leader>v', ':vsplit<CR>' }
-- close window
Map_n { '<Leader>wx', ':close<CR>' }
-- Move line/s
Map_n { '<A-j>', ':m .+1<CR>==' }
Map_n { '<A-k>', ':m .-2<CR>==' }
Map_v { '<A-j>', ":m '>+1<CR>gv=gv" }
Map_v { '<A-k>', ":m '<-2<CR>gv=gv" }
Map_i { '<A-j>', '<Esc>:m .+1<CR>==gi' }
Map_i { '<A-k>', '<Esc>:m .-2<CR>==gi' }
-- Yank/copy to clipboard
Map_n { '<Leader>y', '"+yy' }
Map_v { '<Leader>y', '"+y' }
-- Paste from clipboard
Map_n { '<Leader>p', '"+p' }
-- Toggle conceal
Map_n { '<Leader>TC', ":set <C-R>=&conceallevel ? 'conceallevel=0' : 'conceallevel=1'<CR><CR>" }
|
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local config = require "core.configmanager";
local encodings = require "util.encodings";
local stringprep = encodings.stringprep;
local storagemanager = require "core.storagemanager";
local usermanager = require "core.usermanager";
local signal = require "util.signal";
local set = require "util.set";
local lfs = require "lfs";
local pcall = pcall;
local type = type;
local nodeprep, nameprep = stringprep.nodeprep, stringprep.nameprep;
local io, os = io, os;
local print = print;
local tonumber = tonumber;
local CFG_SOURCEDIR = _G.CFG_SOURCEDIR;
local _G = _G;
local prosody = prosody;
-- UI helpers
local function show_message(msg, ...)
print(msg:format(...));
end
local function show_usage(usage, desc)
print("Usage: ".._G.arg[0].." "..usage);
if desc then
print(" "..desc);
end
end
local function getchar(n)
local stty_ret = os.execute("stty raw -echo 2>/dev/null");
local ok, char;
if stty_ret == true or stty_ret == 0 then
ok, char = pcall(io.read, n or 1);
os.execute("stty sane");
else
ok, char = pcall(io.read, "*l");
if ok then
char = char:sub(1, n or 1);
end
end
if ok then
return char;
end
end
local function getline()
local ok, line = pcall(io.read, "*l");
if ok then
return line;
end
end
local function getpass()
local stty_ret = os.execute("stty -echo 2>/dev/null");
if stty_ret ~= 0 then
io.write("\027[08m"); -- ANSI 'hidden' text attribute
end
local ok, pass = pcall(io.read, "*l");
if stty_ret == 0 then
os.execute("stty sane");
else
io.write("\027[00m");
end
io.write("\n");
if ok then
return pass;
end
end
local function show_yesno(prompt)
io.write(prompt, " ");
local choice = getchar():lower();
io.write("\n");
if not choice:match("%a") then
choice = prompt:match("%[.-(%U).-%]$");
if not choice then return nil; end
end
return (choice == "y");
end
local function read_password()
local password;
while true do
io.write("Enter new password: ");
password = getpass();
if not password then
show_message("No password - cancelled");
return;
end
io.write("Retype new password: ");
if getpass() ~= password then
if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
return;
end
else
break;
end
end
return password;
end
local function show_prompt(prompt)
io.write(prompt, " ");
local line = getline();
line = line and line:gsub("\n$","");
return (line and #line > 0) and line or nil;
end
-- Server control
local function adduser(params)
local user, host, password = nodeprep(params.user), nameprep(params.host), params.password;
if not user then
return false, "invalid-username";
elseif not host then
return false, "invalid-hostname";
end
local host_session = prosody.hosts[host];
if not host_session then
return false, "no-such-host";
end
storagemanager.initialize_host(host);
local provider = host_session.users;
if not(provider) or provider.name == "null" then
usermanager.initialize_host(host);
end
local ok, errmsg = usermanager.create_user(user, password, host);
if not ok then
return false, errmsg or "creating-user-failed";
end
return true;
end
local function user_exists(params)
local user, host = nodeprep(params.user), nameprep(params.host);
storagemanager.initialize_host(host);
local provider = prosody.hosts[host].users;
if not(provider) or provider.name == "null" then
usermanager.initialize_host(host);
end
return usermanager.user_exists(user, host);
end
local function passwd(params)
if not user_exists(params) then
return false, "no-such-user";
end
return adduser(params);
end
local function deluser(params)
if not user_exists(params) then
return false, "no-such-user";
end
local user, host = nodeprep(params.user), nameprep(params.host);
return usermanager.delete_user(user, host);
end
local function getpid()
local pidfile = config.get("*", "pidfile");
if not pidfile then
return false, "no-pidfile";
end
if type(pidfile) ~= "string" then
return false, "invalid-pidfile";
end
pidfile = config.resolve_relative_path(prosody.paths.data, pidfile);
local modules_enabled = set.new(config.get("*", "modules_disabled"));
if prosody.platform ~= "posix" or modules_enabled:contains("posix") then
return false, "no-posix";
end
local file, err = io.open(pidfile, "r+");
if not file then
return false, "pidfile-read-failed", err;
end
local locked, err = lfs.lock(file, "w");
if locked then
file:close();
return false, "pidfile-not-locked";
end
local pid = tonumber(file:read("*a"));
file:close();
if not pid then
return false, "invalid-pid";
end
return true, pid;
end
local function isrunning()
local ok, pid, err = getpid();
if not ok then
if pid == "pidfile-read-failed" or pid == "pidfile-not-locked" then
-- Report as not running, since we can't open the pidfile
-- (it probably doesn't exist)
return true, false;
end
return ok, pid;
end
return true, signal.kill(pid, 0) == 0;
end
local function start()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if ret then
return false, "already-running";
end
if not CFG_SOURCEDIR then
os.execute("./prosody");
else
os.execute(CFG_SOURCEDIR.."/../../bin/prosody");
end
return true;
end
local function stop()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGTERM);
return true;
end
local function reload()
local ok, ret = isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGHUP);
return true;
end
return {
show_message = show_message;
show_warning = show_message;
show_usage = show_usage;
getchar = getchar;
getline = getline;
getpass = getpass;
show_yesno = show_yesno;
read_password = read_password;
show_prompt = show_prompt;
adduser = adduser;
user_exists = user_exists;
passwd = passwd;
deluser = deluser;
getpid = getpid;
isrunning = isrunning;
start = start;
stop = stop;
reload = reload;
};
|
-- TBASIC includes
if not _G.bit and not _G.bit32 then
error("This lua implementation does not have bit/bit32 library, aborting.")
end
if not _G.unpack and not table.unpack then
error("This lua implementation does not have unpack() function, aborting.")
end
if _G.bit32 then _G.bit = bit32 end -- Lua 5.2 and LuaJIT compatibility (which has 'bit32' but no 'bit')
if _G.unpack and not _G.table.unpack then _G.table.unpack = unpack end -- LuaJIT compatibility
-- simple binary search stole and improved from Kotlin Language
-- @param cmpval: function that returns numerical value of the value used for searching.
-- implementation: function(s) return whateverhashornumber(s) end
-- e.g. function(s) return string.hash(s) end -- for string values
-- you must implement it by yourself!
do -- Avoid heap allocs for performance
local default_cmp_fn = function(s) return string.hash(tostring(s)) end
function table.binsearch(t, value, cmpval)
local low = 1
local high = #t
local cmp = cmpval or default_cmp_fn
local value = cmp(value)
while low <= high do
local mid = bit.rshift((low + high), 1)
local midVal = t[mid]
if value > cmp(midVal) then
low = mid + 1
elseif value < cmp(midVal) then
high = mid - 1
else
return mid -- key found
end
end
return nil -- key not found
end
end
_G._TBASIC = {}
_G._TBASIC._VERNUM = 0x0004 -- 0.4
_G._TBASIC._VERSION = tonumber(string.format("%d.%d", bit.rshift(_TBASIC._VERNUM, 8), bit.band(_TBASIC._VERNUM, 0xFF)))
_G._TBASIC._HEADER = string.format(" **** TERRAN BASIC V%d.%d **** ", bit.rshift(_TBASIC._VERNUM, 8), bit.band(_TBASIC._VERNUM, 0xFF))
_G._TBASIC.PROMPT = function() print("\nREADY.") end
_G._TBASIC._INVOKEERR = function(msg, msg1)
if msg1 then
print("?L".._G._TBASIC._INTPRTR.PROGCNTR..": "..msg.." "..msg1)
else
print("?L".._G._TBASIC._INTPRTR.PROGCNTR..": "..msg, "ERROR")
end
if _TBASIC.SHOWLUAERROR then error("Error thrown") end
--os.exit(1) -- terminate
_G._TBASIC.__appexit = true -- duh, computercraft
end
_G._TBASIC._ERROR = {
SYNTAX = function() _TBASIC._INVOKEERR("SYNTAX") end,
SYNTAXAT = function(word) _TBASIC._INVOKEERR("SYNTAX ERROR AT", "'"..word.."'") end,
TYPE = function() _TBASIC._INVOKEERR("TYPE MISMATCH") end,
ILLEGALNAME = function(name, reason)
if reason then
_TBASIC._INVOKEERR("ILLEGAL NAME: ".."'"..name.."'", "REASON:"..reason)
else
_TBASIC._INVOKEERR("ILLEGAL NAME:", "'"..name.."'")
end
end,
ILLEGALARG = function(expected, got)
if (not expected) and (not got) then
_TBASIC._INVOKEERR("ILLEGAL QUANTITY")
elseif not got then
_TBASIC._INVOKEERR(expected:upper().." EXPECTED")
else
_TBASIC._INVOKEERR(expected:upper().." EXPECTED,", "GOT "..got:upper())
end
end,
NOSUCHLINE = function(line) _TBASIC._INVOKEERR("NO SUCH LINE:", line) end,
NULFN = function(var) _TBASIC._INVOKEERR("UNDEFINED FUNCTION:", "'"..var.."'") end,
NULVAR = function(var) _TBASIC._INVOKEERR("UNDEFINED VARIABLE:", "'"..var.."'") end,
DIV0 = function() _TBASIC._INVOKEERR("DIVISION BY ZERO") end,
NAN = function() _TBASIC._INVOKEERR("NOT A NUMBER") end,
STACKOVFL = function() _TBASIC._INVOKEERR("TOO MANY RECURSION") end,
LINETOOBIG = function() _TBASIC._INVOKEERR("TOO BIG LINE NUMBER") end,
NOLINENUM = function() _TBASIC._INVOKEERR("NO LINE NUMBER") end,
ABORT = function(reason)
if reason then
_TBASIC._INVOKEERR("PROGRAM", "ABORTED: "..reason)
else
_TBASIC._INVOKEERR("PROGRAM", "ABORTED")
end
end,
ARGMISSING = function(fname, remark)
if remark then
_TBASIC._INVOKEERR("MISSING ARGUMENT(S) FOR", "'"..fname.."' ("..remark..")")
else
_TBASIC._INVOKEERR("MISSING ARGUMENT(S) FOR", "'"..fname.."'")
end
end,
NOMATCHING = function(fname, match) _TBASIC._INVOKEERR("'"..fname.."' HAS NO MACTHING", "'"..match.."'") end,
TOOLONGEXEC = function() _TBASIC._INVOKEERR("TOO LONG WITHOUT YIELDING") end,
RETURNWOSUB = function() _TBASIC._INVOKEERR("RETURN WITHOUT GOSUB") end,
NEXTWOFOR = function() _TBASIC._INVOKEERR("NEXT WITHOUT FOR") end,
ASGONIF = function() _TBASIC._INVOKEERR("ASSIGNMENT ON IF CLAUSE") end,
SHELLCMD = function() _TBASIC._INVOKEERR("THIS IS A SHELL COMMAND") end,
IOERR = function() _TBASIC._INVOKEERR("READ/WRITE") end,
NOSYMFORNEXT = function() _TBASIC._INVOKEERR("NO VAR FOR NEXT CLAUSE") end,
DEV_FUCKIT = function() _TBASIC._INVOKEERR("FEELING DIRTY") end,
DEV_UNIMPL = function(fname) _TBASIC._INVOKEERR("UNIMPLEMENTED SYNTAX:", "'"..fname.."'") end
}
_G._TBASIC._FNCTION = { -- aka OPCODES because of some internal-use-only functions
-- variable control
"CLR", -- deletes all user-defined variables and functions
"DIM", -- allocates an array
"DEF", -- defines new function. Synopsis "DEF FN FOOBAR(arg)"
"FN", -- denotes function
-- flow control
"GO", "GOTO", -- considered harmful
"GOSUB", "RETURN",
"FOR", "NEXT", "IN",
"DO", -- reserved only
"IF", "THEN",
"LABEL", -- line number alias
--"ELSE", "ELSEIF", -- reserved only, will not be implemented
"END", -- terminate program cleanly
"ABORT", -- break as if an error occured
"ABORTM", -- ABORT with message
-- stdio
"PRINT",
"INPUT",
"GET", -- read single key
"HTAB", "TAB", -- set cursor's X position
"VTAB", -- set cursor's Y position
"SCROLL",
"CLS", -- clear screen
"TEXTCOL", -- foreground colour
"BACKCOL", -- background colour
-- mathematics
"ABS", "SIN", "COS", "TAN", "FLOOR", "CEIL", "ROUND", "LOG",
"INT", -- integer part of a number (3.78 -> 3, -3.03 -> -3)
"RND", -- random number 0.0 <= x < 1.0
"SGN", -- sign of a number (-1, 0, 1)
"SQRT", -- square root
"CBRT", -- cubic root
"MAX", "MIN",
"INV", -- returns (1.0 / arg)
"RAD", -- converts deg into rad
-- string manipulation
"LEN",
"LEFT", -- just like in Excel
"MID", -- -- just like in Excel (substring)
"RIGHT", -- just like in Excel
-- type conversion
"ASC", -- converts a charactor into its code point
"CHR", -- converts an integer into corresponding character
"STR", -- number to string
"VAL", -- string to number
-- misc
"REM", -- mark this line as comment
"NEW", -- clean up any programs on the buffer (this is a Shell function)
-- pc speaker
"BEEP", -- beeps. Synopsis: "BEEP", "BEEP [pattern]" (not for CC)
"TEMIT", -- emits a tone. Synopsis: "TEMIT [frequency] [seconds]" (not for CC)
-- commands
"RUN", -- run a program or a line. Synopsis: "RUN", "RUN [line]" (this is a Shell function)
"LIST", -- list currently entered program. Synopsis: "LIST", "LIST [line]", "LIST [from "-" to]" (this is a Shell function)
"NEW", -- clear program lines buffer (this is a Shell function)
"RENUM", -- re-number BASIC statements (this is a Shell function)
"DELETE", -- delete line (this is a Shell function)
-- external IO
"LOAD", -- file load. Synopsis: "LOAD [filename]"
"SAVE", -- file save. Synopsis: "SAVE [filename]"
-- internal use only!!
"ASSIGNARRAY",
"READARRAY",
}
_G._TBASIC._OPERATR = {
-- operators
">>>", "<<", ">>", "|", "&", "XOR", "!", -- bitwise operations
";", -- string concatenation
"==", ">", "<", "<=", "=<", ">=", "=>", -- TURN OFF your font ligature for this part if you're seeing two identical symbols!
"!=", "<>", "><", -- not equal
"=", ":=", -- assign
"AND", "OR", "NOT",
"^", -- math.pow, 0^0 should return 1.
"*", "/", "+", "-", -- arithmetic operations
"%", -- math.fmod
"TO", "STEP", -- integer sequence operator
"MINUS", -- unary minus (internal use only!!)
"+=", "-=", "*=", "/=", "%=" -- C-style assign
}
_G._TBASIC.OPILLEGAL = { -- illegal functions and operators (internal-use-only opcodes)
"ASSIGNARRAY",
"READARRAY",
"MINUS",
}
_G._TBASIC._INTPRTR = {}
_G._TBASIC._INTPRTR.TRACE = false -- print program counter while execution
_G._TBASIC.SHOWLUAERROR = true
local function stackpush(t, v)
t[#t + 1] = v
end
local function stackpop(t)
local v = t[#t]
t[#t] = nil
return v
end
local function stackpeek(t)
local v = t[#t]
return v
end
function string.hash(str) -- FNV-1 32-bit
local hash = 2166136261
for i = 1, #str do
hash = hash * 16777619
hash = bit.bxor(hash, str:byte(i))
end
return hash
end
_G._TBASIC._INTPRTR.RESET = function()
_TBASIC.__appexit = false
_TBASIC._INTPRTR.PROGCNTR = 0
_TBASIC._INTPRTR.MAXLINES = 999999
_TBASIC._INTPRTR.VARTABLE = {} -- table of variables. [NAME] = data
_TBASIC._INTPRTR.FNCTABLE = {} -- table of functions. [NAME] = array of strings? (TBA)
_TBASIC._INTPRTR.CALLSTCK = {} -- return points (line number)
_TBASIC._INTPRTR.LINELABL = {} -- LABEL statement table
_TBASIC._INTPRTR.STACKMAX = 2000
_TBASIC._INTPRTR.CNSTANTS = {
M_PI = 3.141592653589793, -- this is a standard implementation
M_2PI = 6.283185307179586, -- this is a standard implementation
M_E = 2.718281828459045, -- this is a standard implementation
M_ROOT2 = 1.414213562373095, -- this is a standard implementation
TRUE = true,
FALSE = false,
NIL = nil,
_VERSION = _TBASIC._VERSION
}
end
-- FUNCTION IMPLEMENTS --------------------------------------------------------
local function __readvar(varname)
-- varname could be either real name, or a data
-- if varname is a string that can be represented as number, returns tonumber(varname) ("4324" -> 4324)
-- if varname is a TBASIC string, return resolved string ("~FOOBAR" -> "FOOBAR")
-- if varname is a TBASIC variable, return resolved variable ("$FOO" -> any value stored in variable 'FOO')
--print("readvar_varname", varname)
if type(varname) == "table" or type(varname) == "nil" or type(varname) == "boolean" then
return varname
end
if tonumber(varname) then
return tonumber(varname)
end
if varname:byte(1) == 126 then
return varname:sub(2, #varname)
end
if varname:byte(1) == 36 then
local data = varname:sub(2, #varname)
if tonumber(data) then
return tonumber(data)
else
-- try for constants
local retval = _TBASIC._INTPRTR.CNSTANTS[data:upper()]
if retval ~= nil then return retval
-- try for variable table
else return _TBASIC._INTPRTR.VARTABLE[data:upper()] end
end
elseif varname:byte(1) == 37 then
local array = _TBASIC._INTPRTR.VARTABLE[varname:sub(2, #varname):upper()]
if not array or type(array) ~= "table" then
return false
elseif array.identifier == "tbasicarray" then
return array
else
error(varname.." is not an TBASIC array")
end
else
return varname -- already resolved
end
end
local function __makenewtbasicarray(dimensional)
local t = {}
t.dimension = dimensional
t.data = {} -- this data WILL BE one-based whilst TBASIC is zero-based. BEWARE!
t.identifier = "tbasicarray"
return t
end
-- ARRNAME(3,2,4), arguments denote max possible index, starting from zero
function gfnarrayget(arrname, ...)
local t = __readvar(arrname)
local function getdimensionalsum(iteration)
local i = 0
for dim = iteration, (#t.dimension) - 1 do
i = i + t.dimension[dim]
end
return i
end
local indices = {...}
local actualIndex = 0
for d = 1, #indices do
if (d < #indices) then
actualIndex = actualIndex + getdimensionalsum(d) * indices[d]
else
actualIndex = actualIndex + indices[d]
end
end
return t.data[actualIndex + 1] -- actualIndex is zero-based, but t.data is one-based
end
function gfnarrayset(arrname, value, ...)
local t = __readvar(arrname)
local function getdimensionalsum(iteration)
local i = 0
for dim = iteration, (#t.dimension) - 1 do
i = i + t.dimension[dim]
end
return i
end
local indices = {...}
local actualIndex = 0
for d = 1, #indices do
if (d < #indices) then
actualIndex = actualIndex + getdimensionalsum(d) * indices[d]
else
actualIndex = actualIndex + indices[d]
end
end
t.data[actualIndex + 1] = value -- actualIndex is zero-based, but t.data is one-based
end
local function __assert(aarg, expected)
local arg = __readvar(aarg)
if type(arg) ~= expected then
_TBASIC._ERROR.ILLEGALARG(expected, type(arg))
return
end
end
local function __assertlhand(llval, expected)
local lval = __readvar(llval)
if type(lval) ~= expected then
_TBASIC._ERROR.ILLEGALARG("LHAND: "..expected, type(lval))
return
end
end
local function __assertrhand(rrval, expected)
local rval = __readvar(rrval)
if type(rval) ~= expected then
_TBASIC._ERROR.ILLEGALARG("RHAND: "..expected, type(rval))
return
end
end
local function __checknumber(aarg)
local arg = __readvar(aarg)
if arg == nil then
_TBASIC._ERROR.ILLEGALARG("number", type(arg))
return
else
if type(arg) == "table" then
repeat
tval = arg[1]
arg = tval
until type(tval) ~= "table"
end
n = tonumber(arg)
if n == nil then
_TBASIC._ERROR.ILLEGALARG("number", type(arg))
return
else
return n
end
end
end
local function __checkstring(aarg)
local arg = __readvar(aarg)
if type(arg) == "function" then
_TBASIC._ERROR.ILLEGALARG("STRING/NUMBER/BOOL", type(arg))
return
end
if type(arg) == "table" then
repeat
tval = arg[1]
arg = tval
until type(tval) ~= "table"
end
local strarg = tostring(arg)
return strarg:byte(1) == 126 and strarg:sub(2, #strarg) or strarg
end
local function __resolvevararg(...)
local ret = {}
for _, varname in ipairs({...}) do
table.insert(ret, __readvar(varname))
end
return ret
end
_G._TBASIC.__assert = __assert
_G._TBASIC.__assertlhand = __assertlhand
_G._TBASIC.__assertrhand = __assertrhand
_G._TBASIC.__checknumber = __checknumber
_G._TBASIC.__checkstring = __checkstring
_G._TBASIC.__readvar = __readvar
_G._TBASIC.__resolvevararg = __resolvevararg
--[[
Function implementations
Cautions:
* Every function that returns STRING must prepend "~"
]]
local function _fnprint(...)
function printarg(arg)
if type(arg) == "function" then
_TBASIC._ERROR.SYNTAX()
return
end
if type(arg) == "boolean" then
if arg then io.write(" TRUE")
else io.write(" FALSE") end
elseif _TBASIC.isstring(arg) then
io.write(__checkstring(arg))
elseif _TBASIC.isnumber(arg) then -- if argument can be turned into a number (e.g. 14321, "541")
io.write(" "..arg)
elseif type(arg) == "table" then
printarg(arg[1]) -- recursion
else
io.write(tostring(arg))
end
end
local args = __resolvevararg(...)
if #args < 1 then
io.write ""
else
for i, arg in ipairs(args) do
if i > 1 then io.write "\t" end
printarg(arg)
end
end
io.write "\n"
end
local function _fngoto(lnum)
local linenum = nil
if _TBASIC.isnumber(lnum) then
linenum = __checknumber(lnum)
else
linenum = _TBASIC._INTPRTR.LINELABL[__checkstring(lnum)]
end
if linenum == nil or linenum < 1 then
_TBASIC._ERROR.NOSUCHLINE(linenum)
return
end
_TBASIC._INTPRTR.PROGCNTR = linenum - 1
end
local function _fnnewvar(varname, value)
_TBASIC._INTPRTR.VARTABLE[varname:upper()] = __readvar(value)
end
local function _fngosub(lnum)
local linenum = nil
if _TBASIC.isnumber(lnum) then
linenum = __checknumber(lnum)
else
linenum = _TBASIC._INTPRTR.LINELABL[__checkstring(lnum)]
end
stackpush(_TBASIC._INTPRTR.CALLSTCK, _TBASIC._INTPRTR.PROGCNTR) -- save current line number
_fngoto(linenum)
end
local function _fnreturn()
if #_TBASIC._INTPRTR.CALLSTCK == 0 then -- nowhere to return
_TBASIC._ERROR.RETURNWOSUB()
return
end
local return_line = stackpop(_TBASIC._INTPRTR.CALLSTCK) + 1 -- the line has GOSUB, so advance one
_fngoto(return_line)
end
local function _fnabort()
_TBASIC._ERROR.ABORT()
end
local function _fnabortmsg(reason)
_TBASIC._ERROR.ABORT(__checkstring(__readvar(reason)))
end
local function _fnif(bbool)
local bool = __readvar(bbool)
__assert(bool, "boolean")
if bool == nil then
_TBASIC._ERROR.ILLEGALARG()
return
end
if not bool then
_TBASIC._INTPRTR.PROGCNTR = _TBASIC._INTPRTR.PROGCNTR + 1
end
end
local function _fnnop()
return
end
local function _fnfor(seq)
stackpush(_TBASIC._INTPRTR.CALLSTCK, _TBASIC._INTPRTR.PROGCNTR)
end
local function _fnnext(...)
if #_TBASIC._INTPRTR.CALLSTCK == 0 then -- nowhere to return
_TBASIC._ERROR.NEXTWOFOR()
return
end
local variables = {...} -- array of strings(varname) e.g. "$X, $Y, $Z"
-- error if no symbol is specified (a common "mistake")
if #variables == 0 then
_TBASIC._ERROR.NOSYMFORNEXT()
end
local branch = false
-- dequeue intsequences
for i, v in ipairs(variables) do
local t = nil
if _TBASIC.isvariable(v) then
t = _TBASIC._INTPRTR.VARTABLE[v:sub(2, #v)]
if type(t) ~= "table" then
_TBASIC._ERROR.ILLEGALARG("ARRAY", type(t))
return
end
table.remove(t, 1)
-- unassign variable
if #t == 0 then
_TBASIC._INTPRTR.VARTABLE[v] = nil
branch = true
end
else
_TBASIC._ERROR.ILLEGALARG("ARRAY", type(t))
return
end
end
-- branch? or go back?
if not branch then
_fngoto(stackpeek(_TBASIC._INTPRTR.CALLSTCK) + 1) -- the line has FOR statement
else
stackpop(_TBASIC._INTPRTR.CALLSTCK) -- dump the stack
end
end
local function _fnabs(n)
return math.abs(__checknumber(n))
end
local function _fnsin(n)
return math.sin(__checknumber(n))
end
local function _fncos(n)
return math.cos(__checknumber(n))
end
local function _fntan(n)
return math.tan(__checknumber(n))
end
local function _fntorad(n)
return math.rad(__checknumber(n))
end
local function _fnascii(char)
return __checkstring(char):byte(1)
end
local function _fncbrt(n)
return __checknumber(n)^3
end
local function _fnceil(n)
return math.ceil(__checknumber(n))
end
local function _fnchar(code)
return "~"..string.char(__checknumber(code)) -- about "~".. ? read the cautions above!
end
local function _fnfloor(n)
return math.floor(__checknumber(n))
end
local function _fngetkeycode(...)
-- TODO get a single character from the keyboard and saves the code of the character to the given variable(s)
end
local function _fnint(n)
num = __checknumber(n)
return num >= 0 and math.floor(n) or math.ceil(n)
end
local function _fnmultinv(n) -- multiplicative invert
return 1.0 / __checknumber(n)
end
local function _fnsubstrleft(str, n)
return "~"..__checkstring(str):sub(1, __checknumber(n))
end
local function _fnsubstr(str, left, right)
return "~"..__checkstring(str):sub(__checknumber(left), __checknumber(right))
end
local function _fnsubstrright(str, n)
return "~"..__checkstring(str):sub(-__checknumber(n))
end
local function _fnlen(var)
local value = __readvar(var)
return #value
end
local function _fnloge(n)
return math.log(__checknumber(n))
end
local function _fnmax(...)
local args = __resolvevararg(...)
if #args < 1 then
_TBASIC._ERROR.ARGMISSING("MAX")
return
end
local max = -math.huge
for _, i in ipairs(args) do
local n = __checknumber(i)
if max < n then max = n end
end
return max
end
local function _fnmin(...)
local args = __resolvevararg(...)
if #args < 1 then
_TBASIC._ERROR.ARGMISSING("MIN")
return
end
local min = math.huge
for _, i in ipairs(args) do
local n = __checknumber(i)
if min > n then min = n end
end
return min
end
local function _fnrand()
return math.random()
end
local function _fnround(n)
return math.floor(__checknumber(n) + 0.5)
end
local function _fnsign(n)
local num = __checknumber(n)
return num > 0 and 1.0 or num < 0 and -1.0 or 0.0
end
local function _fnsqrt(n)
return __checknumber(n)^(0.5)
end
local function _fntostring(n)
local ret = tostring(__checknumber(n))
if not ret then
_TBASIC._ERROR.ILLEGALARG()
return
else
return "~"..ret
end
end
local function _fntonumber(s)
if tonumber(s) then return s end
return tonumber(__checkstring(s))
end
local function _fntan(n)
return math.tan(__checknumber(n))
end
local function _fninput(...) -- INPUT(var1, [var2, var3 ...])
local args = {...}
local prompt = "YOUR INPUT ? "
local prompt_numbered = "YOUR INPUT (%d OF %d) ? "
function prompt_and_get_input()
-- if there's two or more input, a number will be shown
if #args >= 2 then
io.write(string.format(prompt_numbered, argcount, #args))
else
io.write(prompt)
end
io.flush() -- print out the line right away
local value = io.read()
return value
end
if #args < 1 then
_TBASIC._ERROR.ARGMISSING("INPUT")
return
else
for argcount, varname in ipairs(args) do
local inputvalue = nil
while inputvalue == nil or inputvalue == "" do
inputvalue = prompt_and_get_input()
_opassign(varname, inputvalue)
end
end
end
end
local function _fnlabel(lname)
_TBASIC._INTPRTR.LINELABL[__checkstring(lname)] = _TBASIC._INTPRTR.PROGCNTR
end
-- dim(max_index, max_index, ...)
local function _fndim(...)
local args = {...}
local varname = args[1]
local dimensional = {}
for i, v in ipairs(args) do
if i > 1 then
dimensional[i - 1] = v + 1 -- stores size, not max_index
end
end
_opassign(varname, __makenewtbasicarray(dimensional))
end
local function _fnassignarray(arrname, value, ...)
gfnarrayset(arrname, value, ...)
end
local function _fnreadarray(arrname, ...)
return gfnarrayget(arrname, ...)
end
-- OPERATOR IMPLEMENTS --------------------------------------------------------
local function booleanise(bool)
return bool and "$TRUE" or "$FALSE"
end
function _opconcat(llval, rrval)
local lval = __readvar(llval)
local rval = __readvar(rrval)
if type(lval) == "function" then _TBASIC._ERROR.ILLEGALARG("VALUE", "FUNCTION") return end
if type(rval) == "function" then _TBASIC._ERROR.ILLEGALARG("VALUE", "FUNCTION") return end
local l = (type(lval) == "string" and lval:byte(1)) == 126 and lval:sub(2, #lval) or __checkstring(lval)
local r = (type(rval) == "string" and rval:byte(1)) == 126 and rval:sub(2, #rval) or __checkstring(rval)
return "~"..l..r
end
function _opplus(lval, rval)
local l = __checknumber(lval)
local r = __checknumber(rval)
return l + r
end
function _optimes(lval, rval)
local l = __checknumber(lval)
local r = __checknumber(rval)
return l * r
end
function _opminus(lval, rval)
local l = __checknumber(lval)
local r = __checknumber(rval)
return l - r
end
function _opdiv(lval, rval)
local l = __checknumber(lval)
local r = __checknumber(rval)
if r == 0 then
_TBASIC._ERROR.DIV0()
return
else
return _optimes(l, 1.0 / r)
end
end
function _opmodulo(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return math.fmod(l, r)
end
function _oppower(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return math.pow(l, r) -- 0^0 is 1 according to the spec, and so is the Lua's.
end
function _opassign(var, value)
if _TBASIC.isnumber(var) or _TBASIC.isfunction(var) or _TBASIC.isoperator(var) or _TBASIC.isargsep(var) then
_TBASIC._ERROR.ILLEGALNAME(var)
return
end
-- remove uncaught "$"
local varname = var:byte(1) == 36 and var:sub(2, #var) or var
-- if it still has "$", the programmer just broke the law
if varname:byte(1) == 36 then
_TBASIC._ERROR.ILLEGALNAME(varname, "HAS ILLEGAL CHARACTER '$'")
return
end
_TBASIC._INTPRTR.VARTABLE[varname:upper()] = __readvar(value)
end
function _opeq(llval, rrval)
local lval = __readvar(llval)
local rval = __readvar(rrval)
if tonumber(lval) and tonumber(rval) then
return booleanise(tonumber(lval) == tonumber(rval))
else
return booleanise(__checkstring(lval) == __checkstring(rval))
end
end
function _opne(llval, rrval)
local lval = __readvar(llval)
local rval = __readvar(rrval)
if tonumber(lval) and tonumber(rval) then
return booleanise(tonumber(lval) ~= tonumber(rval))
else
return booleanise(__checkstring(lval) ~= __checkstring(rval))
end
end
function _opgt(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return booleanise(l > r)
end
function _oplt(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return booleanise(l < r)
end
function _opge(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return booleanise(l >= r)
end
function _ople(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return booleanise(l <= r)
end
function _opband(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.band(l, r)
end
function _opbor(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.bor(l, r)
end
function _opbxor(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.bxor(l, r)
end
function _opbnot(val)
local expected = "number"
local v = __checknumber(val)
return bit.bnot(v)
end
function _oplshift(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.lshift(l, r)
end
function _oprshift(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.arshift(l, r)
end
function _opurshift(lval, rval)
local expected = "number"
local l = __checknumber(lval)
local r = __checknumber(rval)
return bit.rshift(l, r)
end
function _opland(lhand, rhand)
return booleanise(__readvar(lhand) and __readvar(rhand))
end
function _oplor(lhand, rhand)
return booleanise(__readvar(lhand) or __readvar(rhand))
end
function _oplnot(rhand)
return booleanise(not __readvar(rhand))
end
function _opintrange(x, y) -- x TO y -> {x..y}
local from = __checknumber(x)
local to = __checknumber(y)
local seq = {}
if from < to then
for i = from, to do
table.insert(seq, i)
end
else
for i = from, to, -1 do
table.insert(seq, i)
end
end
return seq
end
function _opintrangestep(sseq, sstp) -- i know you can just use "for i = from, to, step"
local seq = __readvar(sseq)
local stp = __readvar(sstp)
local step = __checknumber(stp) -- but that's just how not this stack machine works...
__assert(seq, "table")
if step == 1 then return seq end
if step < 1 then _TBASIC._ERROR.ILLEGALARG() return end
local newseq = {}
for i, v in ipairs(seq) do
if i % step == 1 then
table.insert(newseq, v)
end
end
return newseq
end
function _opunaryminus(n)
local num = __checknumber(n)
return -num
end
function _opplusassign(var, value)
if type(__readvar(var)) == "number" then
_opassign(var, __readvar(var) + __checknumber(value))
else
_TBASIC._ERROR.ILLEGALARG()
return
end
end
function _opminusassign(var, value)
if type(__readvar(var)) == "number" then
_opassign(var, __readvar(var) - __checknumber(value))
else
_TBASIC._ERROR.ILLEGALARG()
return
end
end
function _optimesassign(var, value)
if type(__readvar(var)) == "number" then
_opassign(var, __readvar(var) * __checknumber(value))
else
_TBASIC._ERROR.ILLEGALARG()
return
end
end
function _opdivassign(var, value)
if type(__readvar(var)) == "number" then
if __checknumber(value) == 0 then
_TBASIC._ERROR.DIV0()
return
else
_opassign(var, __readvar(var) / __checknumber(value))
end
else
_TBASIC._ERROR.ILLEGALARG()
return
end
end
function _opmodassign(var, value)
if type(__readvar(var)) == "number" then
if __checknumber(value) == 0 then
_TBASIC._ERROR.DIV0()
return
else
_opassign(var, math.fmod(__readvar(var), __checknumber(value)))
end
else
_TBASIC._ERROR.ILLEGALARG()
return
end
end
local vararg = -13 -- magic
_G._TBASIC.LUAFN = {
-- variable control
CLR = {function() _TBASIC._INTPRTR.VARTABLE = {} end, 0},
DIM = {_fndim, vararg},
ASSIGNARRAY = {_fnassignarray, vararg},
READARRY = {_fnreadarray, vararg},
-- flow control
IF = {_fnif, 1},
THEN = {_fnnop, 0},
GOTO = {_fngoto, 1},
GOSUB = {_fngosub, 1},
RETURN = {_fnreturn, 0},
END = {function() _G._TBASIC.__appexit = true end, 0},
ABORT = {_fnabort, 0},
ABORTM = {_fnabortmsg, 1},
FOR = {_fnfor, 1},
NEXT = {_fnnext, vararg},
LABEL = {_fnlabel, 1},
-- stdio
PRINT = {_fnprint, vararg},
INPUT = {_fninput, vararg},
-- mathematics
ABS = {_fnabs, 1},
CBRT = {_fncbrt, 1},
CEIL = {_fnceil, 1},
COS = {_fncos, 1},
FLOOR = {_fnfloor, 1},
INT = {_fnint, 1},
INV = {_fnmultinv, 1},
LOG = {_fnloge, 1},
MAX = {_fnmax, vararg},
MIN = {_fnmin, vararg},
RAD = {_fntorad, 1},
RND = {_fnrand, 0},
ROUND = {_fnround, 1},
SGN = {_fnsign, 1},
SIN = {_fnsin, 1},
SQRT = {_fnsqrt, 1},
TAN = {_fntan, 1},
-- string manipulation
LEFT = {_fnsubstrleft, 2},
LEN = {_fnlen, 1},
MID = {_fnsubstr, 3},
RIGHT = {_fnsubstrright, 2},
-- type conversion
ASC = {_fnascii, 1},
CHR = {_fnchar, 1},
STR = {_fntostring, 1},
VAL = {_fntonumber, 1},
---------------
-- operators --
---------------
[";"] = {_opconcat, 2},
["+"] = {_opplus, 2},
["*"] = {_optimes, 2},
["-"] = {_opminus, 2},
["/"] = {_opdiv, 2},
["%"] = {_opmodulo, 2},
["^"] = {_oppower, 2},
["=="] = {_opeq, 2},
["!="] = {_opne, 2}, ["<>"] = {_opne, 2}, ["><"] = {_opne, 2},
[">="] = {_opge, 2}, ["=>"] = {_opge, 2},
["<="] = {_ople, 2}, ["=<"] = {_ople, 2},
[">"] = {_opgt, 2},
["<"] = {_oplt, 2},
["="] = {_opassign, 2}, [":="] = {_opassign, 2},
["+="] = {_opplusassign, 2}, ["-="] = {_opminusassign, 2},
["*="] = {_optimesassign, 2}, ["/="] = {_opdivassign, 2}, ["%="] = {_opmodassign, 2},
MINUS = {_opunaryminus, 1},
-- logical operators
AND = {_opland, 2},
OR = {_oplor, 2},
NOT = {_oplnot, 1},
-- bit operators
["<<"] = {_oplshift, 2},
[">>"] = {_oprshift, 2}, -- bit.arshift
[">>>"] = {_opurshift, 2}, -- bit.rshift
["|"] = {_opbor, 2},
["&"] = {_opband, 2},
["!"] = {_opbnot, 1},
XOR = {_opbxor, 2},
-- int sequence
TO = {_opintrange, 2},
STEP = {_opintrangestep, 2},
-- misc
REM = {_fnnop, 0}
}
_G._TBASIC._GETARGS = function(func)
local f = _TBASIC.LUAFN[func]
if f == nil then return nil end
return f[2]
end
-- PARSER IMPL ----------------------------------------------------------------
local opprecedence = {
{":=", "=", "+=", "-=", "*=", "/=", "%="}, -- least important
{"OR"},
{"AND"},
{"|"},
{"XOR"},
{"&"},
{"==", "!=", "<>", "><"},
{"<=", ">=", "=<", "=>", "<", ">"},
{"TO", "STEP"},
{">>>", "<<", ">>"},
{";"},
{"+", "-"},
{"*", "/", "%"},
{"NOT", "!"},
{"^"}, -- most important
{"MINUS"}
}
local opassoc = {
rtl = {";", "^", "NOT", "!"}
}
local function exprerr(token)
_TBASIC._ERROR.SYNTAXAT(token)
end
function _op_precd(op)
-- take care of prematurely prepended '#'
local t1 = op:byte(1) == 35 and op:sub(2, #op) or op
op = t1:upper()
for i = 1, #opprecedence do
for _, op_in_quo in ipairs(opprecedence[i]) do
if op == op_in_quo then
return i
end
end
end
exprerr("precedence of "..op)
end
function _op_isrtl(op)
for _, v in ipairs(opassoc.rtl) do
if op == v then return true end
end
return false
end
function _op_isltr(op)
return not _op_isrtl(op)
end
function _G._TBASIC.isnumber(token)
return tonumber(token) and true or false
end
function _G._TBASIC.isoperator(token)
if token == nil then return false end
-- take care of prematurely prepended '#'
local t1 = token:byte(1) == 35 and token:sub(2, #token) or token
token = t1
for _, tocheck in ipairs(_TBASIC._OPERATR) do
if tocheck == token:upper() then return true end
end
return false
end
function _G._TBASIC.isvariable(word)
if type(word) == "number" then return false end
if type(word) == "boolean" then return true end
if type(word) == "table" then return true end
if word == nil then return false end
return word:byte(1) == 36
end
function _G._TBASIC.isargsep(token)
return token == ","
end
function _G._TBASIC.isfunction(token)
if token == nil then return false end
-- take care of prematurely prepended '&'
local t1 = token:byte(1) == 38 and token:sub(2, #token) or token
token = t1
-- try for builtin
local cmpval = function(table_elem) return string.hash(table_elem) end
local found = table.binsearch(_TBASIC._FNCTION, token, cmpval)
if found then
return true
end
-- try for user-defined functions
found = table.binsearch(_TBASIC._INTPRTR.FNCTABLE, token, cmpval)
if found then -- found is either Table or Nil. We want boolean value.
return true
else
return false
end
end
function _G._TBASIC.isstring(token)
if type(token) ~= "string" then return false end
return token:byte(1) == 126
end
function _G._TBASIC.isarray(token)
if token:byte(1) == 37 then
return true
else
local var = __readvar("%"..token)
return type(var) == "table" and var.identifier == "tbasicarray"
end
end
local function printdbg(...)
local debug = false
if debug then print("TBASINCL", ...) end
end
-- implementation of the Shunting Yard algo
_G._TBASIC.TORPN = function(exprarray)
local stack = {}
local outqueue = {}
local loophookkeylist = {}
local function infloophook(key)
if not _G[key] then
_G[key] = 0
table.insert(loophookkeylist, key)
end
_G[key] = _G[key] + 1
if _G[key] > 50000 then
error(key..": too long without yielding")
end
end
local isfunction = _TBASIC.isfunction
local isoperator = _TBASIC.isoperator
local isargsep = _TBASIC.isargsep
local isnumber = _TBASIC.isnumber
local isstring = _TBASIC.isstring
local isarray = _TBASIC.isarray
for _, token in ipairs(exprarray) do--expr:gmatch("[^ ]+") do
if token == nil then error("Token is nil!") end
-- hack: remove single prepended whitespace
t1 = token:byte(1) == 32 and token:sub(2, #token) or token
token = t1
printdbg("TOKEN", "'"..token.."'")
if isfunction(token:upper()) then
printdbg("is function")
stackpush(stack, "&"..token:upper())
elseif isarray(token:upper()) then
printdbg("is array")
stackpush(stack, "%"..token:upper())
elseif isargsep(token) then
printdbg("is argument separator")
if not (stackpeek(stack) == "(" or #stack == 0) then
repeat
stackpush(outqueue, stackpop(stack))
infloophook("repeat1")
until stackpeek(stack) == "(" or #stack == 0
end
-- no left paren encountered, ERROR!
if #stack == 0 then exprerr(token) end -- misplaces sep or mismatched parens
elseif isoperator(token) then
printdbg("is operator")
local o1 = token
while isoperator(stackpeek(stack)) and (
(_op_isltr(o1) and _op_precd(o1) <= _op_precd(stackpeek(stack))) or
(_op_isrtl(o1) and _op_precd(o1) < _op_precd(stackpeek(stack)))
) do
local o2 = stackpeek(stack)
printdbg("--> push o2 to stack, o2:", o2)
stackpop(stack) -- drop
stackpush(outqueue, (o2:byte(1) == 35) and o2 or "#"..o2:upper()) -- try to rm excess '#'
infloophook("while")
end
stackpush(stack, "#"..o1:upper())
elseif token == "(" then
stackpush(stack, token)
elseif token == ")" then
while stackpeek(stack) ~= "(" do
if #stack == 0 then
exprerr(token)
end
printdbg("--> stack will pop", stackpeek(stack))
stackpush(outqueue, stackpop(stack))
infloophook("")
end
printdbg("--> will drop", stackpeek(stack), "(should be left paren!)")
--[[found_left_paren = false
if stackpeek(stack) ~= "(" then
exprerr(token)
else
found_left_paren = true
end]]
stackpop(stack) -- drop
printdbg("--> stack peek after drop", stackpeek(stack))
if isfunction(stackpeek(stack)) then
printdbg("--> will enq fn", stackpeek(stack))
stackpush(outqueue, stackpop(stack))
end
printdbg("--> STACKTRACE_ITMD", table.concat(stack, " "))
printdbg("--> OUTPUT_ITMD", table.concat(outqueue, " "))
-- stack empty without finding left paren, ERROR!
--if not found_left_paren and #stack == 0 then exprerr(token) end -- mismatched parens
elseif isstring(token) or isnumber(token) then
printdbg("is data")
stackpush(outqueue, token) -- arbitrary data
else -- a word without '~' or anything; assume it's a variable name
printdbg("is variable")
stackpush(outqueue, "$"..token:upper())
end
printdbg("STACKTRACE", table.concat(stack, " "))
printdbg("OUTPUT", table.concat(outqueue, " "))
printdbg()
end
while #stack > 0 do
if stackpeek(stack) == "(" or stackpeek(stack) == ")" then
exprerr("(paren)") -- mismatched parens
end
stackpush(outqueue, stackpop(stack))
infloophook("while3")
end
printdbg("FINAL RESULT: "..table.concat(outqueue, " "))
for _, key in ipairs(loophookkeylist) do
_G[key] = nil
end
return outqueue
end
-- INIT -----------------------------------------------------------------------
-- load extensions
local status, err = pcall(
function()
if os and os.loadAPI then -- ComputerCraft
os.loadAPI "TBASEXTN.lua"
else
require "TBASEXTN"
end
end
)
if err then
error(err)
end
--sort builtin keywords list
table.sort(_TBASIC._FNCTION, function(a, b) return string.hash(a) < string.hash(b) end)
_G._TBASIC._INTPRTR.RESET()
--[[
Terran BASIC (TBASIC)
Copyright (c) 2016-2017 Torvald (minjaesong) and the contributors.
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.
]]
|
object_tangible_deed_vehicle_deed_vehicle_deed_swamp_speeder = object_tangible_deed_vehicle_deed_shared_vehicle_deed_swamp_speeder:new {
}
ObjectTemplates:addTemplate(object_tangible_deed_vehicle_deed_vehicle_deed_swamp_speeder, "object/tangible/deed/vehicle_deed/vehicle_deed_swamp_speeder.iff")
|
local filter_color= color("0,0,0,1")
local args= {
Def.Quad{
InitCommand= function(self)
self:hibernate(math.huge):diffuse(filter_color)
end,
PlayerStateSetCommand= function(self, param)
local pn= param.PlayerNumber
local style= GAMESTATE:GetCurrentStyle(pn)
local alf= getenv("ScreenFilter"..ToEnumShortString(pn)) or 0
local width= style:GetWidth(pn) + 8
self:setsize(width, _screen.h*4096):diffusealpha(alf):hibernate(0)
end,
}
}
if GAMESTATE:GetCurrentGame():GetName() == "kb7" then
args[#args+1]= Def.Sprite{
Texture= "board.png", InitCommand= function(self)
self:y(_screen.cy):zoomy(_screen.h)
end,
}
end
return Def.ActorFrame(args)
|
local std = stead
local instead = std.ref '@instead'
instead.savepath = instead_savepath
std.savepath = instead_savepath
instead.gamepath = instead_gamepath
instead.exepath = instead_exepath
|
local m_template = nil
function CreateMainBtn()
m_template = createWidget(nil, "Template", "Template")
setTemplateWidget(m_template)
local button=createWidget(mainForm, "ATButton", "Button", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, 30, 25, 350, 120)
setText(button, "AT")
DnD:Init(button, button, true)
end
|
return
{
entities =
{
{"tree-05", {x = -5.5, y = -4.5}, {}},
{"stone-wall", {x = -4.5, y = -5.5}, {dead = 0.2}},
{"stone-wall", {x = -5.5, y = -5.5}, {dead = 0.2}},
{"tree-05", {x = -2.5, y = -5.5}, {}},
{"stone-wall", {x = -3.5, y = -5.5}, {dead = 0.2}},
{"tree-05", {x = -0.5, y = -5.5}, {}},
{"stone-wall", {x = 1.5, y = -5.5}, {dead = 0.2}},
{"tree-05", {x = 2.5, y = -5.5}, {}},
{"tree-05", {x = 5.5, y = -5.5}, {}},
{"stone-wall", {x = 4.5, y = -5.5}, {dead = 0.2}},
{"tree-05", {x = -5.5, y = -2.5}, {}},
{"medium-electric-pole", {x = -3.5, y = -3.5}, {dead = 0.8}},
{"gun-turret", {x = 3, y = -2}, {force = "enemy", items = {["piercing-rounds-magazine"] = 5}, }},
{"tree-05", {x = 5.5, y = -3.5}, {}},
{"stone-wall", {x = -5.5, y = -0.5}, {dead = 0.2}},
{"radar", {x = -0.5, y = -0.5}, {dead = 0.2}},
{"tree-05", {x = 5.5, y = -0.5}, {}},
{"stone-wall", {x = 6.5, y = -1.5}, {dead = 0.2}},
{"stone-wall", {x = -5.5, y = 0.5}, {dead = 0.2}},
{"stone-wall", {x = -5.5, y = 1.5}, {dead = 0.2}},
{"radar", {x = -0.5, y = 2.5}, {dead = 0.2}},
{"stone-wall", {x = 6.5, y = 1.5}, {dead = 0.2}},
{"tree-05", {x = -5.5, y = 3.5}, {}},
{"stone-wall", {x = -5.5, y = 2.5}, {dead = 0.2}},
{"medium-electric-pole", {x = 1.5, y = 2.5}, {dead = 0.8}},
{"land-mine", {x = 4.86, y = 4.17}, {force = "enemy", }},
{"tree-05", {x = 5.5, y = 2.5}, {}},
{"tree-05", {x = -5.5, y = 5.5}, {}},
{"gun-turret", {x = -2, y = 5}, {force = "enemy", items = {["piercing-rounds-magazine"] = 5}, }},
{"gate", {x = 6.5, y = 4.5}, {dead = 0.2}},
{"gate", {x = 6.5, y = 5.5}, {dead = 0.2}},
{"stone-wall", {x = -5.5, y = 7.5}, {dead = 0.2}},
{"stone-wall", {x = -4.5, y = 7.5}, {dead = 0.2}},
{"stone-wall", {x = -3.5, y = 7.5}, {dead = 0.2}},
{"stone-wall", {x = -2.5, y = 7.5}, {dead = 0.2}},
{"tree-05", {x = -1.5, y = 6.5}, {}},
{"tree-05", {x = 1.5, y = 6.5}, {}},
{"stone-wall", {x = 0.5, y = 7.5}, {dead = 0.2}},
{"stone-wall", {x = 3.5, y = 7.5}, {dead = 0.2}},
{"tree-05", {x = 4.5, y = 6.5}, {}},
{"stone-wall", {x = 6.5, y = 7.5}, {dead = 0.2}},
{"stone-wall", {x = 6.5, y = 6.5}, {dead = 0.2}},
},
}
|
----------------------------------<
-- Bluebird GUI
-- elements/dxScrollPane.lua
----------------------------------<
-- Element variables
--[[------------------------------<
dxElement -> dxScrollPane
-------------------
[Includes Basic Indicators]
x : X position
y : Y position
sx : SX position
sy : SY position
render : Drawing target for its children
cOffsets : Current Offsets
mOffsets : Maximal Offsets
autoFocus : Indicates whether the scrollpane has to focus on dxFocusPoints automaticly.
afterMovement : Let the scrollpane move after swiping it.
scrollable : Unable to drag it by move, but still possible with dxFocusPoint focusing.
slideTime : Total time it takes to focus on a dxFocusPoint.
parent : Parent table
children : Children container
--]]------------------------------<
-- Creator
----------------------------------<
function dxCreateScrollPane(x,y,sx,sy,parent,relativeX, relativeY)
if (x == nil) or (y == nil) or (sx == nil) or (sy == nil) then pushError(1, 'dxCreateScrollPane') return false end
if type(x) ~= 'number' then pushError(2, 'dxCreateScrollPane', 'X Position', 'number') return false end
if type(y) ~= 'number' then pushError(2, 'dxCreateScrollPane', 'Y Position', 'number') return false end
if type(sx) ~= 'number' then pushError(2, 'dxCreateScrollPane', 'Width', 'number') return false end
if type(sy) ~= 'number' then pushError(2, 'dxCreateScrollPane', 'Height', 'number') return false end
if (parent == nil) or (parent == false) then
parent = dxContainer
else
if (not isElement(parent)) then
pushError(2, 'dxCreateScrollPane', 'Parent', 'dxElement')
return false
end
local elementType = dxElementsList[parent]["type"]
if (elementType ~= "dxTile") and (elementType ~= "dxScrollPane") and (elementType ~= "dxContainer") then
pushError(4, 'dxCreateScrollPane', 'Parent')
return false
end
parent = dxElementsList[parent]
end
if (relativeX == nil) then
relativeX = false
else
if type(relativeX) ~= "boolean" then
pushError(3, 'dxCreateScrollPane', 'X Relativity', 'boolean')
relativeX = false
end
if (relativeX == true) then
x = parent.sx*x
sx = parent.sx*sx
end
end
if (relativeY == nil) then
relativeY = false
else
if type(relativeY) ~= "boolean" then
pushError(3, 'dxCreateScrollPane', 'Y Relativity', 'boolean')
relativeY = false
end
if (relativeY == true) then
y = parent.sy*y
sy = parent.sy*sy
end
end
local ElementTable = {
["type"] = "dxScrollPane",
["element"] = createElement("dxGUI", "dxScrollPane"),
["creator"] = getResourceName(sourceResource or getThisResource()),
["x"] = x,
["y"] = y,
["sx"] = sx,
["sy"] = sy,
["cOffsets"] = {0,0},
["mOffsets"] = {0,0},
["AutoFocus"] = true,
["AfterMovement"] = true,
["Scrollable"] = true,
["SlideTime"] = 500,
["BlockChildren"] = false,
["parent"] = parent,
["Enabled"] = true,
["render"] = dxCreateRenderTarget(sx,sy,true),
["children"] = {}
}
table.insert(parent["children"], 1,ElementTable)
table.insert(dxTargets, ElementTable.render)
dxElementsList[ElementTable["element"]] = ElementTable
triggerEvent("onDXElementCreation", root)
return ElementTable["element"]
end
fileDelete("elements/dxScrollPane.lua")
|
--类的声明,这里声明了类名还有属性,并且给出了属性的初始值
Class = {x=0,y=0}
--设置元表的索引,想模拟类的话,这步操作很关键
Class.__index = Class
--构造方法,构造方法的名字是随便起的,习惯性命名为new()
function Class:new(x,y)
local t = {} --初始化t,如果没有这句,那么类所建立的对象如果有一个改变,其他对象都会改变
setmetatable(t, Class) --将t的元表设定为Class
t.x = x --属性值初始化
t.y = y
return t --返回自身
end
--这里定义类的其他方法
function Class:test()
print(self.x,self.y)
end
function Class:plus()
self.x = self.x + 1
self.y = self.y + 1
end
|
local configs = require 'lspconfig/configs'
local util = require 'lspconfig/util'
local server_name = 'cssls'
local bin_name = 'vscode-css-language-server'
configs[server_name] = {
default_config = {
cmd = { bin_name, '--stdio' },
filetypes = { 'css', 'scss', 'less' },
root_dir = function(fname)
return util.root_pattern('package.json', '.git')(fname) or util.path.dirname(fname)
end,
settings = {
css = { validate = true },
scss = { validate = true },
less = { validate = true },
},
},
docs = {
description = [[
https://github.com/hrsh7th/vscode-langservers-extracted
`css-languageserver` can be installed via `npm`:
```sh
npm i -g vscode-langservers-extracted
```
Neovim does not currently include built-in snippets. `vscode-css-language-server` only provides completions when snippet support is enabled. To enable completion, install a snippet plugin and add the following override to your language client capabilities during setup.
```lua
--Enable (broadcasting) snippet capability for completion
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
require'lspconfig'.cssls.setup {
capabilities = capabilities,
}
```
]],
default_config = {
root_dir = [[root_pattern("package.json", ".git") or bufdir]],
},
},
}
|
newoption
{
trigger = "asan",
description = "Enable Clang AddressSanitizer"
}
newoption
{
trigger = "msan",
description = "Enable Clang MemorySanitizer"
}
newoption
{
trigger = "ubsan",
description = "Enable Clang UndefinedBehaviorSanitizer"
}
dofile("source/viewer/shaders.lua")
if _ACTION == nil then
return
end
local asanEnabled = false
local msanEnabled = false
local ubsanEnabled = false
if _ACTION == "gmake" and _OPTIONS["cc"] == "clang" then
if _OPTIONS["asan"] then
asanEnabled = true
sanitizerEnabled = true
end
if _OPTIONS["msan"] then
msanEnabled = true
sanitizerEnabled = true
end
if _OPTIONS["ubsan"] then
ubsanEnabled = true
sanitizerEnabled = true
end
end
local sanitizerEnabled = asanEnabled or msanEnabled or ubsanEnabled
function sanitizer()
if asanEnabled then
buildoptions { "-fsanitize=address" }
linkoptions { "-fsanitize=address" }
end
if msanEnabled then
buildoptions { "-fsanitize=memory" }
linkoptions { "-fsanitize=memory" }
end
if ubsanEnabled then
buildoptions { "-fsanitize=undefined" }
linkoptions { "-fsanitize=undefined" }
end
if sanitizerEnabled then
buildoptions { "-fno-omit-frame-pointer" }
end
end
solution "xatlas"
configurations { "Release", "Debug" }
if _OPTIONS["cc"] ~= nil then
location(path.join("build", _ACTION) .. "_" .. _OPTIONS["cc"])
else
location(path.join("build", _ACTION))
end
platforms { "x86_64", "x86" }
startproject "viewer"
filter "platforms:x86"
architecture "x86"
filter "platforms:x86_64"
architecture "x86_64"
filter "configurations:Debug*"
defines { "_DEBUG" }
optimize "Debug"
symbols "On"
filter "configurations:Release"
defines "NDEBUG"
optimize "Full"
filter {}
if sanitizerEnabled then
optimize "Off"
symbols "On"
end
sanitizer()
local XATLAS_DIR = "source/xatlas"
project "xatlas_static"
kind "StaticLib"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
enablewarnings { "shadow" }
files { path.join(XATLAS_DIR, "xatlas.*") }
sanitizer()
project "xatlas"
kind "SharedLib"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
enablewarnings { "shadow" }
defines { "XATLAS_C_API=1", "XATLAS_EXPORT_API=1" }
files { path.join(XATLAS_DIR, "*.*") }
sanitizer()
local THIRDPARTY_DIR = "source/thirdparty"
local BGFX_DIR = path.join(THIRDPARTY_DIR, "bgfx")
local BIMG_DIR = path.join(THIRDPARTY_DIR, "bimg")
local BX_DIR = path.join(THIRDPARTY_DIR, "bx")
local EIGEN_DIR = path.join(THIRDPARTY_DIR, "eigen")
local EMBREE_DIR = path.join(THIRDPARTY_DIR, "embree3")
local ENKITS_DIR = path.join(THIRDPARTY_DIR, "enkiTS")
local GLFW_DIR = path.join(THIRDPARTY_DIR, "glfw")
local IGL_DIR = path.join(THIRDPARTY_DIR, "libigl")
local MIMALLOC_DIR = path.join(THIRDPARTY_DIR, "mimalloc")
local NATIVEFILEDIALOG_DIR = path.join(THIRDPARTY_DIR, "nativefiledialog")
local OIDN_DIR = path.join(THIRDPARTY_DIR, "oidn")
local OPENFBX_DIR = path.join(THIRDPARTY_DIR, "OpenFBX")
project "test"
kind "ConsoleApp"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
sanitizer()
includedirs { XATLAS_DIR, THIRDPARTY_DIR }
files "source/test/test.cpp"
links { "tiny_obj_loader", "xatlas_static" }
filter "action:vs*"
files "source/xatlas.natvis"
filter "system:linux"
links { "pthread" }
project "viewer"
kind "ConsoleApp"
language "C++"
cppdialect "C++14"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
sanitizer()
files { "source/viewer/*.*", "source/viewer/shaders/*.*" }
includedirs
{
XATLAS_DIR,
THIRDPARTY_DIR,
path.join(BGFX_DIR, "include"),
path.join(BX_DIR, "include"),
EIGEN_DIR,
EMBREE_DIR,
ENKITS_DIR,
path.join(GLFW_DIR, "include"),
path.join(IGL_DIR, "include"),
path.join(MIMALLOC_DIR, "include"),
path.join(NATIVEFILEDIALOG_DIR, "include"),
path.join(OIDN_DIR, "include"),
OPENFBX_DIR
}
links { "bgfx", "bimg", "bx", "cgltf", "enkiTS", "glfw", "imgui", "mimalloc", "nativefiledialog", "objzero", "OpenFBX", "stb_image", "stb_image_resize", "xatlas_static" }
filter "system:windows"
links { "bcrypt", "gdi32", "ole32", "psapi", "uuid"}
filter "system:linux"
links { "dl", "GL", "gtk-3", "gobject-2.0", "glib-2.0", "pthread", "X11", "Xcursor", "Xinerama", "Xrandr" }
filter "action:vs*"
files "source/xatlas.natvis"
includedirs { path.join(BX_DIR, "include/compat/msvc") }
filter { "system:windows", "action:gmake" }
includedirs { path.join(BX_DIR, "include/compat/mingw") }
group "examples"
local EXAMPLES_DIR = "source/examples"
project "example"
kind "ConsoleApp"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
sanitizer()
files { path.join(EXAMPLES_DIR, "example.cpp") }
includedirs { XATLAS_DIR, THIRDPARTY_DIR }
links { "stb_image_write", "tiny_obj_loader", "xatlas_static" }
filter "action:vs*"
files "source/xatlas.natvis"
filter "system:linux"
links { "pthread" }
project "example_c99"
kind "ConsoleApp"
language "C"
cdialect "C99"
warnings "Extra"
sanitizer()
files { path.join(EXAMPLES_DIR, "example_c99.c") }
includedirs { XATLAS_DIR, THIRDPARTY_DIR }
links { "objzero", "xatlas" }
filter "system:linux"
links { "m", "pthread" }
project "example_uvmesh"
kind "ConsoleApp"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
warnings "Extra"
sanitizer()
files { path.join(EXAMPLES_DIR, "example_uvmesh.cpp") }
includedirs { XATLAS_DIR, THIRDPARTY_DIR }
links { "stb_image_write", "tiny_obj_loader", "xatlas_static" }
filter "action:vs*"
files "source/xatlas.natvis"
filter "system:linux"
links { "pthread" }
group "thirdparty"
project "bgfx"
kind "StaticLib"
language "C++"
cppdialect "C++14"
exceptionhandling "Off"
rtti "Off"
sanitizer()
defines { "__STDC_FORMAT_MACROS" }
files
{
path.join(BGFX_DIR, "include/bgfx/**.h"),
path.join(BGFX_DIR, "src/*.cpp"),
path.join(BGFX_DIR, "src/*.h")
}
excludes
{
path.join(BGFX_DIR, "src/amalgamated.cpp")
}
includedirs
{
path.join(BX_DIR, "include"),
path.join(BIMG_DIR, "include"),
path.join(BIMG_DIR, "3rdparty"),
path.join(BIMG_DIR, "3rdparty/astc-codec/include"),
path.join(BIMG_DIR, "3rdparty/iqa/include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "3rdparty/dxsdk/include"),
path.join(BGFX_DIR, "3rdparty/khronos")
}
filter "configurations:Debug"
defines "BGFX_CONFIG_DEBUG=1"
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
includedirs { path.join(BX_DIR, "include/compat/msvc") }
excludes
{
path.join(BGFX_DIR, "src/glcontext_glx.cpp"),
path.join(BGFX_DIR, "src/glcontext_egl.cpp")
}
filter { "system:windows", "action:gmake" }
includedirs { path.join(BX_DIR, "include/compat/mingw") }
project "bimg"
kind "StaticLib"
language "C++"
cppdialect "C++14"
exceptionhandling "Off"
rtti "Off"
sanitizer()
defines
{
"BIMG_DECODE_ENABLE=0"
}
files
{
path.join(BIMG_DIR, "include/bimg/*.h"),
path.join(BIMG_DIR, "src/*.cpp"),
path.join(BIMG_DIR, "src/*.h")
}
includedirs
{
path.join(BX_DIR, "include"),
path.join(BIMG_DIR, "include")
}
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
includedirs { path.join(BX_DIR, "include/compat/msvc") }
filter { "system:windows", "action:gmake" }
includedirs { path.join(BX_DIR, "include/compat/mingw") }
project "bx"
kind "StaticLib"
language "C++"
cppdialect "C++14"
exceptionhandling "Off"
rtti "Off"
sanitizer()
defines { "__STDC_FORMAT_MACROS" }
files
{
path.join(BX_DIR, "include/bx/*.h"),
path.join(BX_DIR, "include/bx/inline/*.inl"),
path.join(BX_DIR, "include/tinystl/*.h"),
path.join(BX_DIR, "src/*.cpp")
}
excludes
{
path.join(BX_DIR, "src/amalgamated.cpp"),
path.join(BX_DIR, "src/crtnone.cpp")
}
includedirs
{
path.join(BX_DIR, "3rdparty"),
path.join(BX_DIR, "include")
}
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
includedirs { path.join(BX_DIR, "include/compat/msvc") }
filter { "system:windows", "action:gmake" }
includedirs { path.join(BX_DIR, "include/compat/mingw") }
project "cgltf"
kind "StaticLib"
language "C"
sanitizer()
files(path.join(THIRDPARTY_DIR, "cgltf.*"))
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "enkiTS"
kind "StaticLib"
language "C++"
cppdialect "C++11"
exceptionhandling "Off"
rtti "Off"
sanitizer()
files(path.join(ENKITS_DIR, "*.*"))
project "glfw"
kind "StaticLib"
language "C"
sanitizer()
files
{
path.join(GLFW_DIR, "include/*.h"),
path.join(GLFW_DIR, "src/context.c"),
path.join(GLFW_DIR, "src/egl_context.c"),
path.join(GLFW_DIR, "src/init.c"),
path.join(GLFW_DIR, "src/input.c"),
path.join(GLFW_DIR, "src/monitor.c"),
path.join(GLFW_DIR, "src/osmesa_context.c"),
path.join(GLFW_DIR, "src/vulkan.c"),
path.join(GLFW_DIR, "src/window.c"),
}
includedirs { path.join(GLFW_DIR, "include") }
filter "system:windows"
defines "_GLFW_WIN32"
files
{
path.join(GLFW_DIR, "src/win32_init.c"),
path.join(GLFW_DIR, "src/win32_joystick.c"),
path.join(GLFW_DIR, "src/win32_monitor.c"),
path.join(GLFW_DIR, "src/win32_thread.c"),
path.join(GLFW_DIR, "src/win32_time.c"),
path.join(GLFW_DIR, "src/win32_window.c"),
path.join(GLFW_DIR, "src/wgl_context.c")
}
filter "system:linux"
defines "_GLFW_X11"
files
{
path.join(GLFW_DIR, "src/glx_context.c"),
path.join(GLFW_DIR, "src/linux*.c"),
path.join(GLFW_DIR, "src/posix*.c"),
path.join(GLFW_DIR, "src/x11*.c"),
path.join(GLFW_DIR, "src/xkb*.c")
}
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
filter {}
project "imgui"
kind "StaticLib"
language "C++"
exceptionhandling "Off"
rtti "Off"
sanitizer()
files(path.join(THIRDPARTY_DIR, "imgui/*.*"))
project "mimalloc"
kind "StaticLib"
language "C"
sanitizer()
includedirs(path.join(MIMALLOC_DIR, "include"))
files(path.join(MIMALLOC_DIR, "src/*.*"))
excludes
{
path.join(MIMALLOC_DIR, "src/alloc-override*"),
path.join(MIMALLOC_DIR, "src/page-queue.c"),
path.join(MIMALLOC_DIR, "src/static.c")
}
project "nativefiledialog"
kind "StaticLib"
language "C++"
exceptionhandling "Off"
rtti "Off"
sanitizer()
includedirs(path.join(NATIVEFILEDIALOG_DIR, "include"))
files(path.join(NATIVEFILEDIALOG_DIR, "nfd_common.*"))
filter "system:windows"
files(path.join(NATIVEFILEDIALOG_DIR, "nfd_win.cpp"))
filter "system:linux"
files(path.join(NATIVEFILEDIALOG_DIR, "nfd_gtk.c"))
buildoptions(os.outputof("pkg-config --cflags gtk+-3.0"))
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "objzero"
kind "StaticLib"
language "C"
cdialect "C99"
sanitizer()
files(path.join(THIRDPARTY_DIR, "objzero/objzero.*"))
project "OpenFBX"
kind "StaticLib"
language "C++"
cppdialect "C++14"
exceptionhandling "Off"
rtti "Off"
sanitizer()
files(path.join(OPENFBX_DIR, "*.*"))
project "stb_image"
kind "StaticLib"
language "C"
sanitizer()
files(path.join(THIRDPARTY_DIR, "stb_image.*"))
project "stb_image_resize"
kind "StaticLib"
language "C"
sanitizer()
files(path.join(THIRDPARTY_DIR, "stb_image_resize.*"))
project "stb_image_write"
kind "StaticLib"
language "C"
sanitizer()
files(path.join(THIRDPARTY_DIR, "stb_image_write.*"))
project "tiny_obj_loader"
kind "StaticLib"
language "C++"
exceptionhandling "Off"
rtti "Off"
sanitizer()
files(path.join(THIRDPARTY_DIR, "tiny_obj_loader.*"))
|
return {
tag = 'colliders',
summary = 'Add a Collider with a CylinderShape to the World.',
description = 'Adds a new Collider to the World with a CylinderShape already attached.',
arguments = {
{
name = 'x',
type = 'number',
default = '0',
description = 'The x coordinate of the center of the cylinder.'
},
{
name = 'y',
type = 'number',
default = '0',
description = 'The y coordinate of the center of the cylinder.'
},
{
name = 'z',
type = 'number',
default = '0',
description = 'The z coordinate of the center of the cylinder.'
},
{
name = 'radius',
type = 'number',
default = '1',
description = 'The radius of the cylinder, in meters.'
},
{
name = 'length',
type = 'number',
default = '1',
description = 'The length of the cylinder, in meters.'
}
},
returns = {
{
name = 'collider',
type = 'Collider',
description = 'The new Collider.'
}
},
related = {
'CylinderShape',
'Collider',
'World:newCollider',
'World:newBoxCollider',
'World:newCapsuleCollider',
'World:newMeshCollider',
'World:newSphereCollider'
}
}
|
local Leftstrum = false
local Downstrum = false
local Upstrum = false
local Rightstrum = false
function onUpdate(elapsed)
setPropertyFromClass('ClientPrefs', 'middleScroll', false)
if middleScroll == true then
endSong()
end
songPos = getSongPosition()
local currentBeat = (songPos/5000)*(1200/60)
local currentBeat2 = (songPos/5000)*(180/60)
function onMoveCamera(focus)
if focus == 'boyfriend' then
-- called when the camera focus on boyfriend
elseif focus == 'dad' then
setProperty('camFollowPos.y',getProperty('camFollowPos.y') + (math.sin(currentBeat) * 0.6))
end
end
local currentBeat = (songPos/5000)*(curBpm/60)
noteTweenX(defaultPlayerStrumX0, 4, defaultPlayerStrumX0 - 50*math.sin((currentBeat2+4*0.25)*math.pi), 0.5)
noteTweenX(defaultPlayerStrumX1, 5, defaultPlayerStrumX1 - 350 + 2000*math.sin((currentBeat2+8*0.25)*math.pi), 3)
noteTweenX(defaultPlayerStrumX2, 6, defaultPlayerStrumX2 - 50*math.sin((currentBeat2+4*0.25)*math.pi), 0.5)
noteTweenX(defaultPlayerStrumX3, 7, defaultPlayerStrumX3 - 350 + 2000*math.sin((currentBeat2+8*0.25)*math.pi), 3)
noteTweenX(defaultOpponentStrumX0, 0, defaultOpponentStrumX0 + 50*math.sin((currentBeat2+4*0.25)*math.pi), 0.5)
noteTweenX(defaultOpponentStrumX1, 1, defaultOpponentStrumX1 + 350 - 2000*math.sin((currentBeat2+8*0.25)*math.pi), 3)
noteTweenX(defaultOpponentStrumX2, 2, defaultOpponentStrumX2 + 50*math.sin((currentBeat2+4*0.25)*math.pi), 0.5)
noteTweenX(defaultOpponentStrumX3, 3, defaultOpponentStrumX3 + 350 - 2000*math.sin((currentBeat2+8*0.25)*math.pi), 3)
setCharacterY('dad',getCharacterY('dad') + (math.sin(currentBeat2) * 0.3))
function opponentNoteHit(id, direction, noteType, isSustainNote)
setProperty('health', getProperty('health') - 1 * ((getProperty('health')/22))/8)
cameraShake(game, 0.015, 0.2)
cameraShake(other, 0.015, 0.2)
cameraShake(hud, 0.015, 0.2)
characterPlayAnim('gf', 'scared', true)
doTweenZoom('camerazoom','camGame',1,0.15,'quadInOut')
end
function goodNoteHit(id, direction, noteType, isSustainNote)
cameraShake(game, 0.005, 0.15)
doTweenZoom('camerazoom','camGame',0.85,0.15,'quadInOut')
end
function noteMiss(direction)
setProperty('health', getProperty('health') + 0.025)
end
function noteMissPress(direction)
setProperty('health', getProperty('health') + 0.025)
end
end
|
local Player = FindMetaTable("Player")
function Player:SetSocialCredit(value)
assert(isnumber(value), "Invalid value")
self:SetNWInt("SocialCredit", socialcredit.utils.Clamp(value))
socialcredit.Set(self:SteamID(), value)
hook.Run("OnSocialCreditUpdated", self)
end
function Player:AddSocialCredit(value)
assert(isnumber(value), "Invalid value")
self:SetSocialCredit(self:GetSocialCredit() + value)
end
hook.Add("PlayerInitialSpawn", "SocialCredit", function(ply)
local credit = socialcredit.Get(ply:SteamID()) or socialcredit.Config.DefaultValue
ply:SetNWInt("SocialCredit", credit)
end)
|
ix.dialogue = ix.dialogue or {}
ix.dialogue.list = ix.dialogue.list or {}
function ix.dialogue.LoadFromDir(directory)
for k, v in ipairs(file.Find(directory.."/*.lua", "LUA")) do
local niceName = v:sub(4, -5)
DIALOGUE = ix.dialogue.list[niceName] or {}
if (PLUGIN) then
DIALOGUE.plugin = PLUGIN.uniqueID
end
DIALOGUE.tree = {}
DIALOGUE.addTopic = function(topicID, data)
local topicData = {
statement = data.statement or "",
response = data.response or "",
preCallback = data.preCallback,
postCallback = data.postCallback,
options = data.options or {},
IsDynamic = data.IsDynamic or false,
GetDynamicOptions = data.GetDynamicOptions,
ResolveDynamicOption = data.ResolveDynamicOption,
IsDynamicFollowup = data.IsDynamicFollowup or false,
DynamicPreCallback = data.DynamicPreCallback
}
DIALOGUE.tree[topicID] = topicData
end
ix.util.Include(directory.."/"..v)
DIALOGUE.name = DIALOGUE.name or "Unknown"
ix.dialogue.list[niceName] = DIALOGUE
DIALOGUE = nil
end
end
function ix.dialogue.addTopic(id, topicID, statement, response, preCallback, postCallback, options)
local dialogue = ix.dialogue.list[id]
if not dialogue then return end
local topic = {}
topic.statement = statement or ""
topic.response = response or ""
topic.preCallback = preCallback
topic.postCallback = postCallback
topic.options = options or {}
dialogue.tree[topicID] = topic
end
function ix.dialogue.getTopic(id, topicID)
local dialogue = ix.dialogue.list[id]
if not dialogue then return end
return dialogue.tree[topicID]
end
hook.Add("DoPluginIncludes", "ixDialogueLib", function(path)
ix.dialogue.LoadFromDir(path.."/dialogue")
end)
if SERVER then
function ix.dialogue.notify(client, type, text)
net.Start("ixDialogueNotify")
net.WriteUInt(type, 4)
net.WriteString(text)
net.Send(client)
end
function ix.dialogue.notifyItemGet(client, text)
ix.dialogue.notify(client, 0, text)
end
function ix.dialogue.notifyItemLost(client, text)
ix.dialogue.notify(client, 1, text)
end
function ix.dialogue.notifyTaskGet(client, text)
ix.dialogue.notify(client, 2, text)
end
function ix.dialogue.notifyTaskComplete(client, text)
ix.dialogue.notify(client, 3, text)
end
function ix.dialogue.notifyMoneyReceive(client, text)
ix.dialogue.notify(client, 4, text)
end
function ix.dialogue.notifyMoneyLost(client, text)
ix.dialogue.notify(client, 5, text)
end
function ix.dialogue.notifyReputationReceive(client, text)
ix.dialogue.notify(client, 6, text)
end
function ix.dialogue.notifyReputationLost(client, text)
ix.dialogue.notify(client, 7, text)
end
end
|
--[[
Day 7: Today, I finished both halves, but manually searched for the answer for the second half...
I was getting tired. I need to drop the table dumper and figure out how to programmatically find the answer.
I've almost got it, but not quite.
]]
-- Table dumping routines... ----------------------------------------------------
function dump(...)
print(DataDumper(...), "\n---")
end
local dumplua_closure = [[
local closures = {}
local function closure(t)
closures[#closures+1] = t
t[1] = assert(loadstring(t[1]))
return t[1]
end
for _,t in pairs(closures) do
for i = 2,#t do
debug.setupvalue(t[1], i-1, t[i])
end
end
]]
local lua_reserved_keywords = {
'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for',
'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while' }
local function keys(t)
local res = {}
local oktypes = { stringstring = true, numbernumber = true }
local function cmpfct(a,b)
if oktypes[type(a)..type(b)] then
return a < b
else
return type(a) < type(b)
end
end
for k in pairs(t) do
res[#res+1] = k
end
table.sort(res, cmpfct)
return res
end
local c_functions = {}
for _,lib in pairs{'_G', 'string', 'table', 'math',
'io', 'os', 'coroutine', 'package', 'debug'} do
local t = _G[lib] or {}
lib = lib .. "."
if lib == "_G." then lib = "" end
for k,v in pairs(t) do
if type(v) == 'function' and not pcall(string.dump, v) then
c_functions[v] = lib..k
end
end
end
function DataDumper(value, varname, fastmode, ident)
local defined, dumplua = {}
-- Local variables for speed optimization
local string_format, type, string_dump, string_rep =
string.format, type, string.dump, string.rep
local tostring, pairs, table_concat =
tostring, pairs, table.concat
local keycache, strvalcache, out, closure_cnt = {}, {}, {}, 0
setmetatable(strvalcache, {__index = function(t,value)
local res = string_format('%q', value)
t[value] = res
return res
end})
local fcts = {
string = function(value) return strvalcache[value] end,
number = function(value) return value end,
boolean = function(value) return tostring(value) end,
['nil'] = function(value) return 'nil' end,
['function'] = function(value)
return string_format("loadstring(%q)", string_dump(value))
end,
userdata = function() error("Cannot dump userdata") end,
thread = function() error("Cannot dump threads") end,
}
local function test_defined(value, path)
if defined[value] then
if path:match("^getmetatable.*%)$") then
out[#out+1] = string_format("s%s, %s)\n", path:sub(2,-2), defined[value])
else
out[#out+1] = path .. " = " .. defined[value] .. "\n"
end
return true
end
defined[value] = path
end
local function make_key(t, key)
local s
if type(key) == 'string' and key:match('^[_%a][_%w]*$') then
s = key .. "="
else
s = "[" .. dumplua(key, 0) .. "]="
end
t[key] = s
return s
end
for _,k in ipairs(lua_reserved_keywords) do
keycache[k] = '["'..k..'"] = '
end
if fastmode then
fcts.table = function (value)
-- Table value
local numidx = 1
out[#out+1] = "{"
for key,val in pairs(value) do
if key == numidx then
numidx = numidx + 1
else
out[#out+1] = keycache[key]
end
local str = dumplua(val)
out[#out+1] = str..","
end
if string.sub(out[#out], -1) == "," then
out[#out] = string.sub(out[#out], 1, -2);
end
out[#out+1] = "}"
return ""
end
else
fcts.table = function (value, ident, path)
if test_defined(value, path) then return "nil" end
-- Table value
local sep, str, numidx, totallen = " ", {}, 1, 0
local meta, metastr = (debug or getfenv()).getmetatable(value)
if meta then
ident = ident + 1
metastr = dumplua(meta, ident, "getmetatable("..path..")")
totallen = totallen + #metastr + 16
end
for _,key in pairs(keys(value)) do
local val = value[key]
local s = ""
local subpath = path
if key == numidx then
subpath = subpath .. "[" .. numidx .. "]"
numidx = numidx + 1
else
s = keycache[key]
if not s:match "^%[" then subpath = subpath .. "." end
subpath = subpath .. s:gsub("%s*=%s*$","")
end
s = s .. dumplua(val, ident+1, subpath)
str[#str+1] = s
totallen = totallen + #s + 2
end
if totallen > 80 then
sep = "\n" .. string_rep(" ", ident+1)
end
str = "{"..sep..table_concat(str, ","..sep).." "..sep:sub(1,-3).."}"
if meta then
sep = sep:sub(1,-3)
return "setmetatable("..sep..str..","..sep..metastr..sep:sub(1,-3)..")"
end
return str
end
fcts['function'] = function (value, ident, path)
if test_defined(value, path) then return "nil" end
if c_functions[value] then
return c_functions[value]
elseif debug == nil or debug.getupvalue(value, 1) == nil then
return string_format("loadstring(%q)", string_dump(value))
end
closure_cnt = closure_cnt + 1
local res = {string.dump(value)}
for i = 1,math.huge do
local name, v = debug.getupvalue(value,i)
if name == nil then break end
res[i+1] = v
end
return "closure " .. dumplua(res, ident, "closures["..closure_cnt.."]")
end
end
function dumplua(value, ident, path)
return fcts[type(value)](value, ident, path)
end
if varname == nil then
varname = "return "
elseif varname:match("^[%a_][%w_]*$") then
varname = varname .. " = "
end
if fastmode then
setmetatable(keycache, {__index = make_key })
out[1] = varname
table.insert(out,dumplua(value, 0))
return table.concat(out)
else
setmetatable(keycache, {__index = make_key })
local items = {}
for i=1,10 do items[i] = '' end
items[3] = dumplua(value, ident or 0, "t")
if closure_cnt > 0 then
items[1], items[6] = dumplua_closure:match("(.*\n)\n(.*)")
out[#out+1] = ""
end
if #out > 0 then
items[2], items[4] = "local t = ", "\n"
items[5] = table.concat(out)
items[7] = varname .. "t"
else
items[2] = varname
end
return table.concat(items)
end
end
-- Table dumping routines... ----------------------------------------------------
print("Day 7")
-- Read input data...
INPUT = {}
for line in io.lines("input") do
table.insert(INPUT, line)
end
--for k,v in pairs(INPUT) do print(k,v) end
function printtable(t, c)
local out, tins = {}, table.insert
for i, v in pairs(t) do
if (i==c) then
tins(out, "(" .. v .. ")")
else
tins(out, v)
end
end
local tab = table.concat(out, ",")
--print(tab)
return tab
end
TESTDATA = {}
table.insert(TESTDATA, "pbga (66)")
table.insert(TESTDATA, "xhth (57)")
table.insert(TESTDATA, "ebii (61)")
table.insert(TESTDATA, "havc (66)")
table.insert(TESTDATA, "ktlj (57)")
table.insert(TESTDATA, "fwft (72) -> ktlj, cntj, xhth")
table.insert(TESTDATA, "qoyq (66)")
table.insert(TESTDATA, "padx (45) -> pbga, havc, qoyq")
table.insert(TESTDATA, "tknk (41) -> ugml, padx, fwft")
table.insert(TESTDATA, "jptl (61)")
table.insert(TESTDATA, "ugml (68) -> gyxo, ebii, jptl")
table.insert(TESTDATA, "gyxo (61)")
table.insert(TESTDATA, "cntj (57)")
-- node = name, weight, children...
function Day7a(input)
local all = {}
local childnames = {}
for i, v in pairs(input) do
local _, _, name, weight = v:find("(%S+)%s-%((%d+)%)")
local mysubs = {}
if (v:find("->")) then
local _, _, subs = v:find(".-->%s-(.+)")
subs = subs:gsub("%s", "")
for sub in subs:gmatch('([^,]+)') do
table.insert(mysubs, sub)
childnames[sub] = true
end
end
all[name] = {weight = weight, childnames = mysubs}
end
-- Find root node (node that has children, but that appears in no other node's children list)...
local rootname = ""
for name, node in pairs(all) do -- print(name,node.weight,#node.childnames)
if (#node.childnames) then
if (not childnames[name]) then
print("found root: " .. name)
rootname = name
end
end
end
--dump(all)
local tree = {}
local children = subtree(rootname, all)
tree = {name = rootname, weight = all[rootname].weight, children = children}
dump(tree)
treeweights(tree)
return 'blah'
end
function treeweights(node, level)
level = level or 1
if (#node.children == 0) then
return node.weight
end
local w = -200 -- last child weight...
local t = 0 -- total
for _, child in pairs(node.children) do
local weight = treeweights(child, level+1)
t = t + weight
if (w ~= -200) and (weight ~= w) then
print("offset: " .. weight - w)
end
end
print(string.rep('--', level) .. t+node.weight .. "(" .. node.name .. ")")
return t+node.weight
end
function subtree(name, all)
local node = all[name]
if (#node.childnames == 0) then return {} end
local out = {}
local nodeweight = 0
for _, childname in pairs(all[name].childnames) do
children = subtree(childname, all)
table.insert(out, {name = childname, weight = all[childname].weight, children = children})
end
return out
end
--Day7a(TESTDATA)
Day7a(INPUT)
-- Test A
--print("Test A (and B) Results...")
--TESTDATA = {0, 2, 7, 0}
--assert(Day7a(TESTDATA) == 'tknk')
--Day7a({5,1,10,0,1,7,13,14,3,12,8,10,7,12,0,6})
|
return class("JapanesePTPage", import(".TemplatePage.PtTemplatePage"))
|
-- This file is generated. Do not edit it manually. Please edit .shaderproto files.
shader_type_data = {
['Barrel'] = {
_Aspect = 'Float',
_BackColor = 'Color',
_Chroma = 'Float',
_Offset = 'Float',
_Scale = 'Float',
_Sigma = 'Float',
_T = 'Float',
},
['Barrel Hyper'] = {
_Aspect = 'Float',
_BackColor = 'Color',
_Chroma = 'Float',
_Offset = 'Float',
_Scale = 'Float',
_Sigma = 'Float',
_T = 'Float',
},
['Blink'] = {
_Amp = 'Float',
_Freq = 'Float',
_Mul = 'Float',
_Offset = 'Float',
_T = 'Float',
},
['Broken TV'] = {
_Roll = 'Float',
_T = 'Float',
},
['Change Texture With Fade'] = {
_Color = 'Color',
_Offsets = 'Vector',
_PrimaryTex = '2D',
_SubColor = 'Color',
_SubTex = '2D',
_T = 'Float',
},
['Color'] = {
_ColorAdd = 'Vector',
_ColorMul = 'Color',
_T = 'Float',
},
['Colorless'] = {
_T = 'Float',
},
['Fade'] = {
_InvertMask = 'Float',
_Mask = '2D',
_Offset = 'Float',
_SubColor = 'Color',
_SubTex = '2D',
_T = 'Float',
_Vague = 'Float',
},
['Fade Radial Blur'] = {
_Dir = 'Float',
_Size = 'Float',
_SubColor = 'Color',
_SubTex = '2D',
_T = 'Float',
_Zoom = 'Float',
},
['Flip Grid'] = {
_BackColor = 'Color',
_FlipDuration = 'Float',
_GridSize = 'Float',
_SubColor = 'Color',
_SubTex = '2D',
_T = 'Float',
},
['Gaussian Blur'] = {
_Offset = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Glitch'] = {
_T = 'Float',
},
['Glow'] = {
_Size = 'Float',
_Strength = 'Float',
_T = 'Float',
},
['Gray Wave'] = {
_Freq = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Kaleido'] = {
_Freq = 'Float',
_Repeat = 'Float',
_T = 'Float',
},
['Lens Blur'] = {
_Offset = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Masked Mosaic'] = {
_Mask = '2D',
_Size = 'Float',
_Strength = 'Float',
_T = 'Float',
},
['Mix Add'] = {
_AlphaFactor = 'Float',
_ColorAdd = 'Vector',
_ColorMul = 'Color',
_InvertMask = 'Float',
_Mask = '2D',
_T = 'Float',
},
['Mono'] = {
_ColorAdd = 'Vector',
_ColorMul = 'Color',
_T = 'Float',
},
['Motion Blur'] = {
_Offset = 'Float',
_Size = 'Float',
_T = 'Float',
_Theta = 'Float',
},
['Overglow'] = {
_CenterX = 'Float',
_CenterY = 'Float',
_Mul = 'Float',
_T = 'Float',
_Zoom = 'Float',
},
['Radial Blur'] = {
_Offset = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Rain'] = {
_Aspect = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Rand Roll'] = {
_Freq = 'Float',
_T = 'Float',
},
['Ripple'] = {
_Amp = 'Float',
_Aspect = 'Float',
_BlurSize = 'Float',
_RFreq = 'Float',
_T = 'Float',
_TFreq = 'Float',
},
['Ripple Move'] = {
_Amp = 'Float',
_Aspect = 'Float',
_BlurSize = 'Float',
_Fade = 'Float',
_RFreq = 'Float',
_T = 'Float',
_TFreq = 'Float',
_Width = 'Float',
},
['Roll'] = {
_T = 'Float',
_XSpeed = 'Float',
_YSpeed = 'Float',
},
['Rotation Blur'] = {
_Offset = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Shake'] = {
_Freq = 'Float',
_T = 'Float',
_XAmp = 'Float',
_YAmp = 'Float',
},
['Sharpen'] = {
_Size = 'Float',
_T = 'Float',
},
['Show Second Texture'] = {
_SubTex = '2D',
},
['Water'] = {
_Aspect = 'Float',
_Distort = 'Float',
_Freq = 'Float',
_Size = 'Float',
_T = 'Float',
},
['Wiggle'] = {
_AAmp = 'Float',
_BlinkAmp = 'Float',
_BlinkFreq = 'Float',
_Mono = 'Float',
_Mul = 'Float',
_Offset = 'Float',
_T = 'Float',
_TFreq = 'Float',
_XAmp = 'Float',
_XFreq = 'Float',
_YAmp = 'Float',
_YFreq = 'Float',
},
}
shader_float_data = {
['Barrel'] = {
_Aspect = 1.77777778,
_Chroma = 0,
_Offset = 0,
_Scale = 1,
_Sigma = 0.2,
_T = 0,
},
['Barrel Hyper'] = {
_Aspect = 1.77777778,
_Chroma = 0,
_Offset = 0,
_Scale = 1,
_Sigma = 0.2,
_T = 0,
},
['Blink'] = {
_Amp = -0.5,
_Freq = 10,
_Mul = 1,
_Offset = 0,
_T = 0,
},
['Broken TV'] = {
_Roll = 0.07,
_T = 0,
},
['Change Texture With Fade'] = {
_T = 0,
},
['Color'] = {
_T = 0,
},
['Colorless'] = {
_T = 0,
},
['Fade'] = {
_InvertMask = 0,
_Offset = 0,
_T = 0,
_Vague = 0.25,
},
['Fade Radial Blur'] = {
_Dir = 0,
_Size = 1,
_T = 0,
_Zoom = 0.5,
},
['Flip Grid'] = {
_FlipDuration = 0.5,
_GridSize = 64,
_T = 0,
},
['Gaussian Blur'] = {
_Offset = 0,
_Size = 1,
_T = 0,
},
['Glitch'] = {
_T = 0,
},
['Glow'] = {
_Size = 1,
_Strength = 1,
_T = 0,
},
['Gray Wave'] = {
_Freq = 0.5,
_Size = 50,
_T = 0,
},
['Kaleido'] = {
_Freq = 1,
_Repeat = 8,
_T = 0,
},
['Lens Blur'] = {
_Offset = 0,
_Size = 1,
_T = 0,
},
['Masked Mosaic'] = {
_Size = 4,
_Strength = 8,
_T = 0,
},
['Mix Add'] = {
_AlphaFactor = 0,
_InvertMask = 0,
_T = 0,
},
['Mono'] = {
_T = 0,
},
['Motion Blur'] = {
_Offset = 0,
_Size = 1,
_T = 0,
_Theta = 0,
},
['Overglow'] = {
_CenterX = 0.5,
_CenterY = 0.5,
_Mul = 0.5,
_T = 0,
_Zoom = 0.5,
},
['Radial Blur'] = {
_Offset = 0,
_Size = 1,
_T = 0,
},
['Rain'] = {
_Aspect = 1.77777778,
_Size = 2,
_T = 0,
},
['Rand Roll'] = {
_Freq = 10,
_T = 0,
},
['Ripple'] = {
_Amp = 0.01,
_Aspect = 1.77777778,
_BlurSize = 1,
_RFreq = 50,
_T = 0,
_TFreq = 3,
},
['Ripple Move'] = {
_Amp = 0.01,
_Aspect = 1.77777778,
_BlurSize = 1,
_Fade = 0.1,
_RFreq = 50,
_T = 0,
_TFreq = 3,
_Width = 0.1,
},
['Roll'] = {
_T = 0,
_XSpeed = 0,
_YSpeed = 0,
},
['Rotation Blur'] = {
_Offset = 0,
_Size = 1,
_T = 0,
},
['Shake'] = {
_Freq = 10,
_T = 0,
_XAmp = 1,
_YAmp = 1,
},
['Sharpen'] = {
_Size = 1,
_T = 0,
},
['Water'] = {
_Aspect = 1.77777778,
_Distort = 5,
_Freq = 50,
_Size = 10,
_T = 0,
},
['Wiggle'] = {
_AAmp = 0,
_BlinkAmp = 0,
_BlinkFreq = 0,
_Mono = 0,
_Mul = 1,
_Offset = 0,
_T = 0,
_TFreq = 0,
_XAmp = 0,
_XFreq = 0,
_YAmp = 0,
_YFreq = 0,
},
}
shader_color_data = {
['Barrel'] = {
_BackColor = Color.black,
},
['Barrel Hyper'] = {
_BackColor = Color.black,
},
['Change Texture With Fade'] = {
_Color = Color.white,
_SubColor = Color.white,
},
['Color'] = {
_ColorMul = Color.white,
},
['Fade'] = {
_SubColor = Color.white,
},
['Fade Radial Blur'] = {
_SubColor = Color.white,
},
['Flip Grid'] = {
_BackColor = Color.black,
_SubColor = Color.white,
},
['Mix Add'] = {
_ColorMul = Color.white,
},
['Mono'] = {
_ColorMul = Color.white,
},
}
shader_vector_data = {
['Change Texture With Fade'] = {
_Offsets = Vector4.zero,
},
['Color'] = {
_ColorAdd = Vector4.zero,
},
['Mix Add'] = {
_ColorAdd = Vector4.zero,
},
['Mono'] = {
_ColorAdd = Vector4.zero,
},
}
|
--#if game_constants
--(when using replace_strings with --game-constant-module-path [this_data.lua], all namespaced constants
-- below are replaced with their values (as strings), so this file can be skipped)
local memory = {
picked_emerald_address = 0x5dff
}
--(game_constants)
--#endif
return memory
|
---@class ClimateManager : zombie.iso.weather.ClimateManager
---@field private DISABLE_SIMULATION boolean
---@field private DISABLE_FX_UPDATE boolean
---@field private DISABLE_WEATHER_GENERATION boolean
---@field public FRONT_COLD int
---@field public FRONT_STATIONARY int
---@field public FRONT_WARM int
---@field public MAX_WINDSPEED_KPH float
---@field public MAX_WINDSPEED_MPH float
---@field private season ErosionSeason
---@field private lastMinuteStamp long
---@field private modDataTable KahluaTable
---@field private airMass float
---@field private airMassDaily float
---@field private airMassTemperature float
---@field private baseTemperature float
---@field private snowFall float
---@field private snowStrength float
---@field private snowMeltStrength float
---@field private snowFracNow float
---@field canDoWinterSprites boolean
---@field private windPower float
---@field private weatherPeriod WeatherPeriod
---@field private thunderStorm ThunderStorm
---@field private simplexOffsetA double
---@field private simplexOffsetB double
---@field private simplexOffsetC double
---@field private simplexOffsetD double
---@field private dayDoFog boolean
---@field private dayFogStrength float
---@field private gt GameTime
---@field private worldAgeHours double
---@field private tickIsClimateTick boolean
---@field private tickIsDayChange boolean
---@field private lastHourStamp int
---@field private tickIsHourChange boolean
---@field private tickIsTenMins boolean
---@field private currentFront ClimateManager.AirFront
---@field private colDay ClimateColorInfo
---@field private colDusk ClimateColorInfo
---@field private colDawn ClimateColorInfo
---@field private colNight ClimateColorInfo
---@field private colNightNoMoon ClimateColorInfo
---@field private colNightMoon ClimateColorInfo
---@field private colTemp ClimateColorInfo
---@field private colFog ClimateColorInfo
---@field private colFogLegacy ClimateColorInfo
---@field private colFogNew ClimateColorInfo
---@field private fogTintStorm ClimateColorInfo
---@field private fogTintTropical ClimateColorInfo
---@field private instance ClimateManager
---@field public WINTER_IS_COMING boolean
---@field public THE_DESCENDING_FOG boolean
---@field public A_STORM_IS_COMING boolean
---@field private climateValues ClimateValues
---@field private climateForecaster ClimateForecaster
---@field private climateHistory ClimateHistory
---@field dayLightLagged float
---@field nightLagged float
---@field protected desaturation ClimateManager.ClimateFloat
---@field protected globalLightIntensity ClimateManager.ClimateFloat
---@field protected nightStrength ClimateManager.ClimateFloat
---@field protected precipitationIntensity ClimateManager.ClimateFloat
---@field protected temperature ClimateManager.ClimateFloat
---@field protected fogIntensity ClimateManager.ClimateFloat
---@field protected windIntensity ClimateManager.ClimateFloat
---@field protected windAngleIntensity ClimateManager.ClimateFloat
---@field protected cloudIntensity ClimateManager.ClimateFloat
---@field protected ambient ClimateManager.ClimateFloat
---@field protected viewDistance ClimateManager.ClimateFloat
---@field protected dayLightStrength ClimateManager.ClimateFloat
---@field protected humidity ClimateManager.ClimateFloat
---@field protected globalLight ClimateManager.ClimateColor
---@field protected colorNewFog ClimateManager.ClimateColor
---@field protected precipitationIsSnow ClimateManager.ClimateBool
---@field public FLOAT_DESATURATION int
---@field public FLOAT_GLOBAL_LIGHT_INTENSITY int
---@field public FLOAT_NIGHT_STRENGTH int
---@field public FLOAT_PRECIPITATION_INTENSITY int
---@field public FLOAT_TEMPERATURE int
---@field public FLOAT_FOG_INTENSITY int
---@field public FLOAT_WIND_INTENSITY int
---@field public FLOAT_WIND_ANGLE_INTENSITY int
---@field public FLOAT_CLOUD_INTENSITY int
---@field public FLOAT_AMBIENT int
---@field public FLOAT_VIEW_DISTANCE int
---@field public FLOAT_DAYLIGHT_STRENGTH int
---@field public FLOAT_HUMIDITY int
---@field public FLOAT_MAX int
---@field private climateFloats ClimateManager.ClimateFloat[]
---@field public COLOR_GLOBAL_LIGHT int
---@field public COLOR_NEW_FOG int
---@field public COLOR_MAX int
---@field private climateColors ClimateManager.ClimateColor[]
---@field public BOOL_IS_SNOW int
---@field public BOOL_MAX int
---@field private climateBooleans ClimateManager.ClimateBool[]
---@field public AVG_FAV_AIR_TEMPERATURE float
---@field private windNoiseOffset double
---@field private windNoiseBase double
---@field private windNoiseFinal double
---@field private windTickFinal double
---@field private colFlare ClimateColorInfo
---@field private flareLaunched boolean
---@field private flareIntensity SteppedUpdateFloat
---@field private flareIntens float
---@field private flareMaxLifeTime float
---@field private flareLifeTime float
---@field private nextRandomTargetIntens int
---@field fogLerpValue float
---@field private seasonColorDawn ClimateManager.SeasonColor
---@field private seasonColorDay ClimateManager.SeasonColor
---@field private seasonColorDusk ClimateManager.SeasonColor
---@field private previousDay ClimateManager.DayInfo
---@field private currentDay ClimateManager.DayInfo
---@field private nextDay ClimateManager.DayInfo
---@field public PacketUpdateClimateVars byte
---@field public PacketWeatherUpdate byte
---@field public PacketThunderEvent byte
---@field public PacketFlare byte
---@field public PacketAdminVarsUpdate byte
---@field public PacketRequestAdminVars byte
---@field public PacketClientChangedAdminVars byte
---@field public PacketClientChangedWeather byte
---@field private networkLerp float
---@field private networkUpdateStamp long
---@field private networkLerpTime float
---@field private networkLerpTimeBase float
---@field private networkAdjustVal float
---@field private networkPrint boolean
---@field private netInfo ClimateManager.ClimateNetInfo
---@field private climateValuesFronts ClimateValues
---@field private windAngles float[]
---@field private windAngleStr String[]
ClimateManager = {}
---@private
---@return void
function ClimateManager:serverReceiveClientChangeWeather() end
---@protected
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@return float
---@overload fun(arg0:float, arg1:float, arg2:float, arg3:boolean)
function ClimateManager:getTimeLerpHours(arg0, arg1, arg2) end
---@protected
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@param arg3 boolean
---@return float
function ClimateManager:getTimeLerpHours(arg0, arg1, arg2, arg3) end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return ClimateColorInfo
function ClimateManager:getSeasonColor(arg0, arg1, arg2) end
---@public
---@param arg0 float
---@return float
function ClimateManager:ToMph(arg0) end
---@public
---@return boolean
function ClimateManager:getPrecipitationIsSnow() end
---@public
---@return boolean
function ClimateManager:isSnowing() end
---@public
---@return ClimateValues
function ClimateManager:getClimateValuesCopy() end
---@public
---@return int
function ClimateManager:getColorMax() end
---@public
---@return float
function ClimateManager:getCorrectedWindAngleIntensity() end
---@public
---@return ClimateManager.DayInfo
function ClimateManager:getNextDay() end
---@public
---@return ClimateColorInfo
function ClimateManager:getColNightNoMoon() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 float
---@param arg3 float
---@param arg4 float
---@param arg5 float
---@param arg6 boolean
---@return void
function ClimateManager:setSeasonColorDay(arg0, arg1, arg2, arg3, arg4, arg5, arg6) end
---@protected
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@return float
---@overload fun(arg0:float, arg1:float, arg2:float, arg3:boolean)
function ClimateManager:getTimeLerp(arg0, arg1, arg2) end
---@protected
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@param arg3 boolean
---@return float
function ClimateManager:getTimeLerp(arg0, arg1, arg2, arg3) end
---@public
---@return void
function ClimateManager:transmitClientChangeAdminVars() end
---@private
---@param arg0 ByteBuffer
---@param arg1 byte
---@param arg2 UdpConnection
---@return boolean
function ClimateManager:readPacketContents(arg0, arg1, arg2) end
---@public
---@param arg0 float
---@return float
function ClimateManager:clamp01(arg0) end
---@public
---@param arg0 float
---@return void
function ClimateManager:setViewDistance(arg0) end
---@public
---@return boolean
function ClimateManager:getEnabledFxUpdate() end
---@public
---@param arg0 float
---@param arg1 int
---@return void
function ClimateManager:transmitGenerateWeather(arg0, arg1) end
---@public
---@return boolean
function ClimateManager:isRaining() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 double
---@param arg3 float
---@param arg4 float
---@param arg5 float
---@param arg6 float
---@return void
---@overload fun(arg0:int, arg1:int, arg2:double, arg3:float, arg4:float, arg5:float, arg6:float, arg7:ClimateColorInfo)
function ClimateManager:triggerKateBobIntroStorm(arg0, arg1, arg2, arg3, arg4, arg5, arg6) end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 double
---@param arg3 float
---@param arg4 float
---@param arg5 float
---@param arg6 float
---@param arg7 ClimateColorInfo
---@return void
function ClimateManager:triggerKateBobIntroStorm(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) end
---@public
---@return float
function ClimateManager:getRainIntensity() end
---@public
---@param arg0 float
---@return float
function ClimateManager:posToPosNegRange(arg0) end
---@public
---@return double
function ClimateManager:getSimplexOffsetD() end
---@public
---@return ClimateColorInfo
function ClimateManager:getColFog() end
---@public
---@return float
function ClimateManager:getWindAngleIntensity() end
---@public
---@return Color
function ClimateManager:getGlobalLightInternal() end
---@public
---@param arg0 float
---@return void
function ClimateManager:transmitTriggerStorm(arg0) end
---@protected
---@param arg0 int
---@return double
function ClimateManager:getAirMassNoiseFrequencyMod(arg0) end
---@private
---@return void
function ClimateManager:updateViewDistance() end
---@public
---@return ClimateColorInfo
function ClimateManager:getFogTintStorm() end
---@public
---@return ClimateColorInfo
function ClimateManager:getColNight() end
---@public
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@return float
function ClimateManager:clerp(arg0, arg1, arg2) end
---@private
---@return void
function ClimateManager:setup() end
---@public
---@return boolean
function ClimateManager:getEnabledSimulation() end
---@public
---@param arg0 float
---@return void
function ClimateManager:transmitServerTriggerStorm(arg0) end
---@public
---@return float
function ClimateManager:getAirMass() end
---@public
---@return boolean
function ClimateManager:getIsThunderStorming() end
---@public
---@param arg0 float
---@return void
function ClimateManager:setDesaturation(arg0) end
---@public
---@return float
function ClimateManager:getTemperature() end
---@public
---@return float
function ClimateManager:getPrecipitationIntensity() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@param arg3 ClimateManager.AirFront
---@return void
function ClimateManager:CalculateWeatherFrontStrength(arg0, arg1, arg2, arg3) end
---@public
---@return ClimateColorInfo
function ClimateManager:getGlobalLight() end
---@public
---@return void
function ClimateManager:resetModded() end
---@public
---@return void
function ClimateManager:updateOLD() end
---@public
---@return void
---@overload fun(arg0:int)
function ClimateManager:execute_Simulation() end
---@public
---@param arg0 int
---@return void
function ClimateManager:execute_Simulation(arg0) end
---@public
---@return double
function ClimateManager:getSimplexOffsetB() end
---@public
---@return ClimateColorInfo
function ClimateManager:getFogTintTropical() end
---@public
---@return float
function ClimateManager:getSnowStrength() end
---@public
---@return void
function ClimateManager:launchFlare() end
---@public
---@param arg0 ByteBuffer
---@param arg1 UdpConnection
---@return void
function ClimateManager:receiveClimatePacket(arg0, arg1) end
---@public
---@param arg0 float
---@return void
function ClimateManager:transmitTriggerTropical(arg0) end
---@public
---@param arg0 int
---@return ClimateManager.ClimateBool
function ClimateManager:getClimateBool(arg0) end
---@public
---@return int
function ClimateManager:getBoolMax() end
---@public
---@return double
function ClimateManager:getWindNoiseFinal() end
---@public
---@return double
function ClimateManager:getWindNoiseBase() end
---@public
---@param arg0 IsoGridSquare
---@return float
---@overload fun(arg0:IsoGridSquare, arg1:BaseVehicle)
---@overload fun(arg0:IsoGridSquare, arg1:BaseVehicle, arg2:boolean)
function ClimateManager:getAirTemperatureForSquare(arg0) end
---@public
---@param arg0 IsoGridSquare
---@param arg1 BaseVehicle
---@return float
function ClimateManager:getAirTemperatureForSquare(arg0, arg1) end
---@public
---@param arg0 IsoGridSquare
---@param arg1 BaseVehicle
---@param arg2 boolean
---@return float
function ClimateManager:getAirTemperatureForSquare(arg0, arg1, arg2) end
---@private
---@return void
function ClimateManager:updateValues() end
---@private
---@param arg0 int
---@param arg1 String
---@return ClimateManager.ClimateColor
function ClimateManager:initClimateColor(arg0, arg1) end
---@public
---@param arg0 float
---@param arg1 boolean
---@return boolean
function ClimateManager:triggerCustomWeather(arg0, arg1) end
---@public
---@return void
function ClimateManager:stopWeatherAndThunder() end
---@public
---@param arg0 IsoGameCharacter
---@param arg1 float
---@return float
function ClimateManager:getWindForceMovement(arg0, arg1) end
---@public
---@param arg0 float
---@return void
function ClimateManager:setDayLightStrength(arg0) end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return int
---@overload fun(arg0:float, arg1:float, arg2:float)
function ClimateManager:clamp(arg0, arg1, arg2) end
---@public
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@return float
function ClimateManager:clamp(arg0, arg1, arg2) end
---@public
---@return int
function ClimateManager:getFloatMax() end
---@public
---@return ClimateColorInfo
function ClimateManager:getColNightMoon() end
---@public
---@param arg0 float
---@return void
function ClimateManager:setNightStrength(arg0) end
---@public
---@return void
function ClimateManager:update() end
---@public
---@return float
function ClimateManager:getNightStrength() end
---@public
---@return float
function ClimateManager:getAirMassTemperature() end
---@public
---@return float
function ClimateManager:getSeasonProgression() end
---@public
---@param arg0 int
---@return ClimateManager.ClimateColor
function ClimateManager:getClimateColor(arg0) end
---@public
---@return float
function ClimateManager:getCloudIntensity() end
---@public
---@param arg0 ClimateValues
---@return void
function ClimateManager:CopyClimateValues(arg0) end
---@public
---@return ClimateColorInfo
function ClimateManager:getColorNewFog() end
---@private
---@param arg0 UdpConnection
---@param arg1 byte
---@return boolean
function ClimateManager:writePacketContents(arg0, arg1) end
---@public
---@return float
function ClimateManager:getBaseTemperature() end
---@private
---@param arg0 int
---@param arg1 String
---@return ClimateManager.ClimateFloat
function ClimateManager:initClimateFloat(arg0, arg1) end
---@public
---@return float
function ClimateManager:getMaxWindspeedKph() end
---@public
---@return float
function ClimateManager:getWindSpeedMovement() end
---@public
---@return float
function ClimateManager:getWindPower() end
---@private
---@return void
function ClimateManager:updateSnowOLD() end
---@public
---@return float
function ClimateManager:getSnowIntensity() end
---@public
---@return ClimateManager.DayInfo
function ClimateManager:getCurrentDay() end
---@public
---@return KahluaTable
function ClimateManager:getModData() end
---@private
---@return void
function ClimateManager:updateOnTick() end
---@public
---@param arg0 DataInputStream
---@param arg1 int
---@return void
function ClimateManager:load(arg0, arg1) end
---@public
---@param arg0 int
---@return ClimateManager.ClimateFloat
function ClimateManager:getClimateFloat(arg0) end
---@public
---@return float
function ClimateManager:getWeatherInterference() end
---@public
---@return void
function ClimateManager:forceDayInfoUpdate() end
---@public
---@param arg0 UdpConnection
---@return void
function ClimateManager:sendInitialState(arg0) end
---@public
---@return double
function ClimateManager:getSimplexOffsetC() end
---@private
---@return void
function ClimateManager:serverReceiveClientChangeAdminVars() end
---@public
---@return String
function ClimateManager:getSeasonName() end
---@private
---@return void
function ClimateManager:initSeasonColors() end
---@public
---@return ClimateHistory
function ClimateManager:getClimateHistory() end
---@public
---@return float
function ClimateManager:getWindAngleRadians() end
---@public
---@param arg0 int
---@param arg1 float
---@return boolean
function ClimateManager:triggerCustomWeatherStage(arg0, arg1) end
---@public
---@return ClimateColorInfo
function ClimateManager:getColFogNew() end
---@public
---@return void
function ClimateManager:updateEveryTenMins() end
---@public
---@param arg0 IsoGameCharacter
---@return float
---@overload fun(arg0:IsoGameCharacter, arg1:boolean)
function ClimateManager:getAirTemperatureForCharacter(arg0) end
---@public
---@param arg0 IsoGameCharacter
---@param arg1 boolean
---@return float
function ClimateManager:getAirTemperatureForCharacter(arg0, arg1) end
---@public
---@param arg0 ClimateManager
---@return void
function ClimateManager:setInstance(arg0) end
---@public
---@return float
function ClimateManager:getDesaturation() end
---@public
---@param arg0 boolean
---@return void
function ClimateManager:setEnabledSimulation(arg0) end
---@public
---@param arg0 float
---@return void
function ClimateManager:transmitTriggerBlizzard(arg0) end
---@public
---@return void
function ClimateManager:resetAdmin() end
---@public
---@param arg0 boolean
---@return void
function ClimateManager:setPrecipitationIsSnow(arg0) end
---@public
---@return float
function ClimateManager:getFogIntensity() end
---@public
---@return float
function ClimateManager:getWindIntensity() end
---@public
---@return double
function ClimateManager:getSimplexOffsetA() end
---@public
---@param arg0 float
---@param arg1 float
---@return float
function ClimateManager:normalizeRange(arg0, arg1) end
---@public
---@return ErosionSeason
function ClimateManager:getSeason() end
---@private
---@return void
function ClimateManager:updateSnow() end
---@public
---@return ThunderStorm
function ClimateManager:getThunderStorm() end
---@public
---@return float
function ClimateManager:getDayLightStrength() end
---@public
---@return float
function ClimateManager:getDayMeanTemperature() end
---@public
---@return WeatherPeriod
function ClimateManager:getWeatherPeriod() end
---@public
---@param arg0 boolean
---@return void
function ClimateManager:setEnabledFxUpdate(arg0) end
---@public
---@return void
function ClimateManager:transmitStopWeather() end
---@public
---@return boolean
function ClimateManager:getEnabledWeatherGeneration() end
---@public
---@return void
function ClimateManager:transmitServerStopWeather() end
---@public
---@return void
function ClimateManager:postCellLoadSetSnow() end
---@public
---@param arg0 IsoMetaGrid
---@return void
function ClimateManager:init(arg0) end
---@public
---@return float
function ClimateManager:getWindspeedKph() end
---@public
---@return float
function ClimateManager:getAmbient() end
---@public
---@return ClimateManager
function ClimateManager:getInstance() end
---@public
---@return float
function ClimateManager:getGlobalLightIntensity() end
---@public
---@return float
function ClimateManager:getAirMassDaily() end
---@public
---@param arg0 float
---@return float
function ClimateManager:ToKph(arg0) end
---@private
---@return void
function ClimateManager:updateFx() end
---@public
---@return float
function ClimateManager:getHumidity() end
---@public
---@return void
function ClimateManager:transmitRequestAdminVars() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 float
---@param arg3 float
---@param arg4 float
---@param arg5 float
---@param arg6 boolean
---@return void
function ClimateManager:setSeasonColorDusk(arg0, arg1, arg2, arg3, arg4, arg5, arg6) end
---@public
---@return float
function ClimateManager:getMaxWindspeedMph() end
---@private
---@return void
function ClimateManager:updateTestFlare() end
---@public
---@param arg0 boolean
---@return void
function ClimateManager:setEnabledWeatherGeneration(arg0) end
---@public
---@return float
function ClimateManager:getWindAngleDegrees() end
---@public
---@param arg0 DataOutputStream
---@return void
function ClimateManager:save(arg0) end
---@private
---@param arg0 int
---@param arg1 String
---@return ClimateManager.ClimateBool
function ClimateManager:initClimateBool(arg0, arg1) end
---@public
---@return void
function ClimateManager:triggerWinterIsComingStorm() end
---@public
---@return ClimateForecaster
function ClimateManager:getClimateForecaster() end
---@public
---@param arg0 int
---@param arg1 int
---@param arg2 float
---@param arg3 float
---@param arg4 float
---@param arg5 float
---@param arg6 boolean
---@return void
function ClimateManager:setSeasonColorDawn(arg0, arg1, arg2, arg3, arg4, arg5, arg6) end
---@public
---@return float
function ClimateManager:getSeasonStrength() end
---@private
---@return void
function ClimateManager:updateWindTick() end
---@protected
---@param arg0 ClimateManager.DayInfo
---@param arg1 int
---@param arg2 int
---@param arg3 int
---@param arg4 int
---@return void
function ClimateManager:setDayInfo(arg0, arg1, arg2, arg3, arg4) end
---@public
---@return ClimateColorInfo
function ClimateManager:getColFogLegacy() end
---@public
---@return ClimateManager.DayInfo
function ClimateManager:getPreviousDay() end
---@public
---@return void
function ClimateManager:resetOverrides() end
---@public
---@return float
function ClimateManager:getViewDistance() end
---@protected
---@param arg0 ClimateManager.ClimateNetAuth
---@param arg1 byte
---@param arg2 UdpConnection
---@return void
function ClimateManager:transmitClimatePacket(arg0, arg1, arg2) end
---@public
---@param arg0 float
---@return void
function ClimateManager:setAmbient(arg0) end
---@public
---@param arg0 float
---@return void
function ClimateManager:transmitServerStartRain(arg0) end
---@public
---@return double
function ClimateManager:getWindTickFinal() end
---@private
---@param arg0 int
---@param arg1 int
---@param arg2 int
---@return void
function ClimateManager:updateDayInfo(arg0, arg1, arg2) end
---@public
---@param arg0 float
---@return String
function ClimateManager:getWindAngleString(arg0) end
---@public
---@return float
function ClimateManager:getFrontStrength() end
---@protected
---@param arg0 int
---@return float
function ClimateManager:getRainTimeMultiplierMod(arg0) end
---@public
---@param arg0 float
---@param arg1 float
---@param arg2 float
---@return float
function ClimateManager:lerp(arg0, arg1, arg2) end
---@public
---@return double
function ClimateManager:getWorldAgeHours() end
---@public
---@return void
function ClimateManager:transmitServerStopRain() end
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
keywordHandler:addKeyword({'task'}, StdModule.say, {npcHandler = npcHandler, text = 'Are you here to get a task or to report you finished task?'})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = 'Me humble name is Rafzan. Good old goblin name meaning honest, generous and nice person, I swear!'})
keywordHandler:addKeyword({'goblin'}, StdModule.say, {npcHandler = npcHandler, text = 'Most goblins so afraid of everything, that they fight everything. Me different. Me just want trade.'})
keywordHandler:addKeyword({'human'}, StdModule.say, {npcHandler = npcHandler, text = 'You humans are so big, strong, clever and beautiful. Me really feel little and green beside you. Must be sooo fun to be human. You surely always make profit!'})
keywordHandler:addKeyword({'profit'}, StdModule.say, {npcHandler = npcHandler, text = 'To be honest to me human friend, me only heard about it, never seen one. I imagine it\'s something cute and cuddly.'})
keywordHandler:addKeyword({'swamp'}, StdModule.say, {npcHandler = npcHandler, text = 'Swamp is horrible. Slowly eating away at health of poor little goblin. No profit here at all. Me will die poor and desperate, probably eaten by giant mosquitoes.'})
keywordHandler:addKeyword({'dwarf'}, StdModule.say, {npcHandler = npcHandler, text = 'Beardmen are nasty. Always want to kill little goblin. No trade at all. Not good, not good.'})
keywordHandler:addKeyword({'help'}, StdModule.say, {npcHandler = npcHandler, text = 'So much to do, so little help. Me poor goblin desperately needs help. Me have a few tasks me need to be done. I can offer you all money I made if you only help me a little with stuff which is easy to strong smart human but impossible for poor, little me.'})
keywordHandler:addKeyword({'thais'}, StdModule.say, {npcHandler = npcHandler, text = 'Me heard Thais is big city with king! Must be strong and clever, to become chief of all humans. Me cannot imagine how many people you have to beat up to become king of all humans. Surely he makes lot of profit in his pretty city.'})
keywordHandler:addKeyword({'elves'}, StdModule.say, {npcHandler = npcHandler, text = 'They are mean and cruel. Humble goblin rarely trades with them. They would rather kill poor me if not too greedy for stuff only me can get them. Still, they rob me of it for a few spare coins and there is noooo profit for poor goblin.'})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = 'Me job merchant is. Me trade with all kinds of things. Me not good trader though, so you get everything incredibly cheap! You might think me mad, but please don\'t rip off poor goblin too much. Me has four or five wives and dozens of kids to feed!'})
keywordHandler:addKeyword({'venore'}, StdModule.say, {npcHandler = npcHandler, text = 'Humans so clever. Much, much smarter than poor, stupid goblin. They have big rich town. Goblin lives here poor and hungry. Me so impressed by you strong and smart humans. So much to learn from you. Poor goblin only sees pretty city from afar. Poor goblin too afraid to go there.'})
keywordHandler:addKeyword({'gold'}, StdModule.say, {npcHandler = npcHandler, text = 'Me have seen a gold coin once or twice. So bright and shiny it hurt me poor eyes. You surely are incredibly rich human who has even three or four coins at once! Perhaps you want to exchange them for some things me offer? Just don\'t rob me too much, me little stupid goblin, have no idea what stuff is worth... you look honest, you surely pay fair price like I ask and tell if it\'s too cheap.'})
keywordHandler:addKeyword({'ratmen'}, StdModule.say, {npcHandler = npcHandler, text = 'Furry guys are strange fellows. Always collecting things and stuff. Not easy to make them share, oh there is noooo profit for little, poor me to be made. They build underground dens that can stretch quite far. Rumour has it the corym have strange tunnels that connect their different networks all over the world.'})
npcHandler:addModule(FocusModule:new())
|
local mod = PhysImpr.Modules.Register("FallProtect", "FallProtect")
mod.Name = "Released players don't take fall damage"
PhysImpr.FallPrevent = PhysImpr.FallPrevent or {}
function PhysImpr.PreventNextFall(ent)
PhysImpr.FallPrevent[ent] = true
end
function PhysImpr.PreventFallDamage(ent, vel)
if not mod.State then return end
if not PhysImpr.FallPrevent[ent] then return end
local tick = PhysImpr.FallPrevent[ent]
-- not number = didnt hit ground before taking fall damage (!?)
-- number = what tick they hit the ground; if they hit it this tick
-- then we're taking damage from that landing (=> prevent it)
if not isnumber(tick) or tick == engine.TickCount() then
local int = 64 + math.max(0, vel - 400) / 4
PhysImpr.StartVis("PlayerLand")
net.WriteVector(ent:GetPos())
net.WriteUInt(int, 16)
PhysImpr.SendVis()
return 0
else
-- didnt match; clean up any data we had
PhysImpr.FallPrevent[ent] = nil
end
end
function PhysImpr.ResetFallProtection(ent)
if PhysImpr.FallPrevent[ent] == true then
PhysImpr.FallPrevent[ent] = engine.TickCount()
end
end
hook.Add("GetFallDamage", "PhysImpr_NoFall", PhysImpr.PreventFallDamage)
hook.Add("OnPlayerHitGround", "PhysImpr_FallUnprotect", function(ply)
PhysImpr.ResetFallProtection(ply)
end)
hook.Add("OnPhysgunPickup", "PhysImpr_ProtectFall", function(pick, ent)
if not ent:IsPlayer() then return end
if not PhysImpr.Perms.Has(pick, "ProtectFall") then return end
PhysImpr.PreventNextFall(ent)
end)
|
local skynet = require "skynet"
local mc = require "skynet.multicast"
local channel
function task()
local i = 0
while(i < 100) do
skynet.sleep(100)
channel:publish("data"..i) --推送数据
i = i + 1
end
channel:delete()
skynet.exit()
end
skynet.start(function()
channel = mc.new() -- 创建一个频道,成功创建后,channel.channel 是这个频道的 id 。
skynet.error("new channel ID", channel.channel)
skynet.fork(task)
end)
|
--[[
Copyright (c) 2016 Calvin Rose
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local html = require 'moonmint.html'
local helper = require 'spec.helper'
local testHTML = helper.encode(html.encode, html.decode, assert)
test("HTML encoding/decoding", function()
test("Encodes/decodes simple html strings.", function()
testHTML("zyxwvut")
testHTML("1233456")
end)
test("Encodes/decodes strings with tags.", function()
testHTML("zyxwvut<hi>akjsk</hi>")
testHTML("1233456</div><div class=\"giggles\">")
end)
test("Encodes/decodes all bytes.", function()
for i = 0, 255 do
testHTML(string.char(i))
end
end)
test("Encodes/decodes strings of all bytes.", function()
for i = 0, 250 do
testHTML(string.char(i, i + 1, i + 2, i + 3, i + 4, i + 5))
end
end)
end)
|
return require("lapis.db.schema")
|
--
-- [boundary.com] Couchbase Lua Plugin
-- [author] Valeriu Paloş <me@vpalos.com>
--
--
-- Imports.
--
local fs = require('fs')
local json = require('json')
local http = require('http')
local os = require('os')
local sha1 = require('sha1')
local timer = require('timer')
local tools = require('tools')
local url = require('url')
--
-- Initialize.
--
local _buckets = {}
local _parameters = json.parse(fs.readFileSync('param.json')) or {}
local _serverHost = _parameters.serverHost or 'localhost'
local _serverPort = _parameters.serverPort or 8080
local _apiKey = _parameters.apiKey or error("API Key must be provided (see CloudStack UI)!")
local _secretKey = _parameters.secretKey or error("Secret Key must be provided (see CloudStack UI)!")
local _pollRetryCount = tools.fence(tonumber(_parameters.pollRetryCount) or 3, 0, 1000)
local _pollRetryDelay = tools.fence(tonumber(_parameters.pollRetryDelay) or 3000, 0, 1000 * 60 * 60)
local _pollInterval = tools.fence(tonumber(_parameters.pollInterval) or 5000, 100, 1000 * 60 * 60 * 24)
local _advancedMetrics = _parameters.advancedMetrics == true
--
-- Metrics source.
--
local _source =
(type(_parameters.source) == 'string' and _parameters.source:gsub('%s+', '') ~= '' and _parameters.source) or
os.hostname()
--
-- Compile a signed query string in CLoudStack-style from a given set of parameters.
--
function compileUri(parameters)
-- Inject fundamentals.
parameters['response'] = 'json'
parameters['apiKey'] = _apiKey
-- Compute query string.
local tuples = {}
for key, value in pairs(parameters) do
table.insert(tuples, tools.urlEncode(key) .. "=" .. tools.urlEncode(value))
end
local query = table.concat(tuples, '&')
-- Compile signature.
table.sort(tuples)
local text = table.concat(tuples, '&'):lower()
local signature = tools.urlEncode(tools.base64(sha1.hmac_binary(_secretKey, text)))
-- Assemble.
local uri = string.format('http://%s:%s/client/api?%s&signature=%s', _serverHost, _serverPort, query, signature)
-- print(uri)
return uri
end
--
-- Get a JSON data set from the server at the given URL (includes query string).
--
function list(parameters, callback)
local remaining = _pollRetryCount
local options = url.parse(compileUri(parameters))
-- Make sure connection is not dropped.
options['headers'] = {
['Connection'] = 'keep-alive'
}
-- Process data.
function handler(response)
local data = {}
response:once('error', retry)
response:on('data', function(chunk)
table.insert(data, chunk)
end)
response:on('end', function()
local success, data = pcall(json.parse, table.concat(data))
local failure = "Unable to parse response!"
local command = parameters['command']:lower()
if success then
local responseField = command .. "response"
if data[responseField] then
data = data[responseField]
failure = data['errorcode'] and data['errortext']
elseif data['errorresponse'] then
failure = data['errorresponse']['errortext']
end
end
if failure then
retry("ERROR: " .. failure)
else
local section = command:match('^list(%w+)s$')
if section then
data = data[section] or data[section .. 's'] or data
end
callback(data)
end
response:destroy()
end)
end
function retry(result)
if remaining > 0 then
remaining = remaining - 1
end
if remaining == 0 then
error(tostring(result.message or result))
end
timer.setTimeout(_pollRetryDelay, perform)
end
function perform()
local request = http.request(options, handler)
request:once('error', retry)
request:done()
end
perform()
end
--
-- Retrieve data in paginated queries.
--
function listPaginated(parameters, callback)
local page
local page = 0
local size = 500
local items = {}
-- Next page.
function advance()
page = page + 1
parameters['page'] = page
parameters['pagesize'] = size
-- Raw call.
list(parameters, function(data)
for _, item in ipairs(data) do
table.insert(items, item)
end
if #data == size then
process.nextTick(advance())
else
callback(items)
end
end)
end
advance()
end
--
-- Schedule poll.
--
function schedule()
timer.setTimeout(_pollInterval, poll)
end
--
-- Parse numeric metric value.
--
function parse(value)
if type(value) ~= 'number' then
value = tonumber((tostring(value):match('([%d%.]+)'))) or 0
end
return value
end
--
-- Metric aggregation functions.
--
function sum(items)
local result = 0
for _, item in ipairs(items) do
result = result + parse(item)
end
return result
end
function avg(items)
local result = 0
for _, item in ipairs(items) do
result = result + parse(item)
end
return result / #items
end
function min(items)
local result = parse(items[1])
for _, item in ipairs(items) do
local value = parse(item)
if result > value then
result = value
end
end
return result
end
function max(items)
local result = parse(items[1])
for _, item in ipairs(items) do
local value = parse(item)
if result < value then
result = value
end
end
return result
end
function cnt(items)
return #items
end
--
-- Create a new aggregator function that only aggregates filtered values.
--
function filter(value, aggregator)
return function(items)
local filtered = {}
for _, item in ipairs(items) do
if item == value then
table.insert(filtered, item)
end
end
return aggregator(filtered)
end
end
--
-- Produce a function that extrcts a capacity field of given kind.
--
function capacity(kind, field)
-- 0* = CAPACITY_TYPE_MEMORY
-- 1* = CAPACITY_TYPE_CPU
-- 2* = CAPACITY_TYPE_STORAGE
-- 3* = CAPACITY_TYPE_STORAGE_ALLOCATED
-- 4* = CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP
-- 5* = CAPACITY_TYPE_PRIVATE_IP
-- 6* = CAPACITY_TYPE_SECONDARY_STORAGE
-- 7* = CAPACITY_TYPE_VLAN
-- 8* = CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP
-- 9. = CAPACITY_TYPE_LOCAL_STORAGE
return function(set)
for _, subset in ipairs(set['capacity']) do
if subset['type'] == kind then
return subset[field]
end
end
end
end
--
-- Metrics reference table.
--
local DEFINITIONS = {
-- Zones.
{
request = {
['command'] = 'listZones',
['showcapacities'] = 'true'
},
standard = {
groupBy = {
'name'
},
metrics = {
['CLOUDSTACK_MEMORY_TOTAL'] = { field = capacity(0, 'capacitytotal'), apply = sum },
['CLOUDSTACK_MEMORY_USED'] = { field = capacity(0, 'capacityused'), apply = sum },
['CLOUDSTACK_CPU_TOTAL'] = { field = capacity(1, 'capacitytotal'), apply = sum },
['CLOUDSTACK_CPU_USED'] = { field = capacity(1, 'capacityused'), apply = sum },
['CLOUDSTACK_STORAGE_TOTAL'] = { field = capacity(2, 'capacitytotal'), apply = sum },
['CLOUDSTACK_STORAGE_USED'] = { field = capacity(2, 'capacityused'), apply = sum },
['CLOUDSTACK_STORAGE_ALLOCATED_TOTAL'] = { field = capacity(3, 'capacitytotal'), apply = sum },
['CLOUDSTACK_STORAGE_ALLOCATED_USED'] = { field = capacity(3, 'capacityused'), apply = sum },
['CLOUDSTACK_VIRTUAL_NETWORK_PUBLIC_IP_TOTAL'] = { field = capacity(4, 'capacitytotal'), apply = sum },
['CLOUDSTACK_VIRTUAL_NETWORK_PUBLIC_IP_USED'] = { field = capacity(4, 'capacityused'), apply = sum },
['CLOUDSTACK_PRIVATE_IP_TOTAL'] = { field = capacity(5, 'capacitytotal'), apply = sum },
['CLOUDSTACK_PRIVATE_IP_USED'] = { field = capacity(5, 'capacityused'), apply = sum },
['CLOUDSTACK_SECONDARY_STORAGE_TOTAL'] = { field = capacity(6, 'capacitytotal'), apply = sum },
['CLOUDSTACK_SECONDARY_STORAGE_USED'] = { field = capacity(6, 'capacityused'), apply = sum },
['CLOUDSTACK_VLAN_TOTAL'] = { field = capacity(7, 'capacitytotal'), apply = sum },
['CLOUDSTACK_VLAN_USED'] = { field = capacity(7, 'capacityused'), apply = sum },
['CLOUDSTACK_DIRECT_ATTACHED_PUBLIC_IP_TOTAL'] = { field = capacity(8, 'capacitytotal'), apply = sum },
['CLOUDSTACK_DIRECT_ATTACHED_PUBLIC_IP_USED'] = { field = capacity(8, 'capacityused'), apply = sum },
['CLOUDSTACK_LOCAL_STORAGE_TOTAL'] = { field = capacity(9, 'capacitytotal'), apply = sum },
['CLOUDSTACK_LOCAL_STORAGE_USED'] = { field = capacity(9, 'capacityused'), apply = sum },
}
}
},
-- Viewer sessions.
{
request = {
['command'] = 'listSystemVms',
['systemvmtype'] = 'consoleproxy'
},
standard = {
groupBy = {
'zonename'
},
metrics = {
['CLOUDSTACK_ACTIVE_VIEWER_SESSIONS'] = { field = 'activeviewersessions', apply = sum }
}
},
advanced = {
groupBy = {
'zonename',
'name'
}
}
},
-- Events.
{
request = {
['command'] = 'listEvents',
['listall'] = 'true'
},
standard = {
metrics = {
['CLOUDSTACK_EVENTS_INFO'] = { field = 'level', apply = filter('INFO', cnt) },
['CLOUDSTACK_EVENTS_WARN'] = { field = 'level', apply = filter('WARN', cnt) },
['CLOUDSTACK_EVENTS_ERROR'] = { field = 'level', apply = filter('ERROR', cnt) },
}
}
},
-- Alerts.
{
request = {
['command'] = 'listAlerts'
},
standard = {
metrics = {
['CLOUDSTACK_ALERTS'] = { field = 'type', apply = cnt },
['CLOUDSTACK_ALERTS_MEMORY'] = { field = 'type', apply = filter(0, cnt) },
['CLOUDSTACK_ALERTS_CPU'] = { field = 'type', apply = filter(1, cnt) },
['CLOUDSTACK_ALERTS_STORAGE'] = { field = 'type', apply = filter(2, cnt) },
}
}
},
-- Accounts.
{
request = {
['command'] = 'listAccounts',
['listall'] = 'true'
},
standard = {
metrics = {
['CLOUDSTACK_ACCOUNTS_TOTAL'] = { field = 'state', apply = cnt },
['CLOUDSTACK_ACCOUNTS_ENABLED'] = { field = 'state', apply = filter('enabled', cnt) },
}
}
}
}
--
-- Print a metric.
--
function metric(stamp, id, value, source)
if (type(source) == 'table') then
source = table.concat(source, '.'):gsub('%s+', '-')
end
print(string.format('%s %s %s %d', id, value, (source and source ~= '') or _source, stamp))
end
--
-- Extract fields from metrics sets as a flat array.
--
function extract(set, rule)
local result
local kind = type(rule.field)
if kind == 'string' then
result = set[rule.field] or rule.default or 0
elseif kind == 'function' then
result = rule.field(set) or rule.default or 0
end
return result
end
--
-- Extract, aggregate and compile metrics.
--
function produceMetrics(stamp, entries, groupBy, definitions)
local metrics = {}
-- Walk entries.
for _, entry in ipairs(entries) do
-- Compile group name.
local group = {}
for _, label in ipairs(groupBy or {}) do
if entry[label] then
table.insert(group, entry[label])
end
end
group = table.concat(group, '.'):gsub('%s+', '-')
-- Extract.
metrics[group] = metrics[group] or {}
for name, rule in pairs(definitions) do
metrics[group][name] = metrics[group][name] or {}
table.insert(metrics[group][name], extract(entry, rule))
end
end
-- Aggregate.
for group, sets in pairs(metrics) do
for name, rule in pairs(definitions) do
metrics[group][name] = rule.apply(metrics[group][name])
end
end
-- Sort groups.
local groups = {}
for group, _ in pairs(metrics) do
table.insert(groups, group)
end
table.sort(groups)
-- Publish.
for _, group in pairs(groups) do
for name, value in pairs(metrics[group]) do
metric(stamp, name, value, group)
end
end
end
--
-- Produce metrics.
--
function poll()
local stamp = os.time()
-- Reschedule poll after all requests have completed.
local remaining = 0
function request(options, callback)
remaining = remaining + 1
listPaginated(options, function(data)
callback(data)
remaining = remaining - 1
if remaining == 0 then
schedule()
end
end)
end
-- Process metrics definitions.
for _, definition in ipairs(DEFINITIONS) do
request(definition.request, function(data)
produceMetrics(
stamp,
data,
definition.standard.groupBy,
definition.standard.metrics)
if _advancedMetrics and definition.advanced then
produceMetrics(
stamp,
data,
definition.advanced.groupBy or definition.standard.groupBy,
definition.advanced.metrics or definition.standard.metrics)
end
end)
end
end
-- Trigger polling.
poll()
|
require 'mock.asset.ParticleHelper'
require 'mock.asset.ParticleProcs'
module 'mock'
local makeParticleSystem, makeParticleForce, makeParticleEmitter
--------------------------------------------------------------------
local function _unpack(m)
local tt=type(m)
if tt=='number' then return m,m end
if tt=='table' then return unpack(m) end
if tt=='function' then return m() end
error('????')
end
local EnumParticleType = {
{'distance', 'distance'},
{'timed', 'timed' }
}
--------------------------------------------------------------------
CLASS: ParticleEmitterConfig()
:MODEL {
Field 'name' :string();
Field 'type' :enum( EnumParticleType );
Field 'distance' :number() :range(0) ;
Field 'frequency' :type('vec2') :range(0) :getset('Frequency');
Field 'emission' :type('vec2') :range(0) :getset('Emission');
Field 'duration' :number();
Field 'surge' :int();
'----';
Field 'magnitude' :type('vec2') :range(0) :getset('Magnitude');
Field 'angle' :type('vec2') :range(-360, 360) :getset('Angle');
'----';
Field 'radius' :type('vec2') :range(0) :getset('Radius');
Field 'rect' :type('vec2') :range(0) :getset('Rect');
}
function ParticleEmitterConfig:__init()
self.name = 'emitter'
self.type = 'timed'
self.distance = 10
self.frequency = { 10, 10 }
self.magnitude = { 10, 10 }
self.angle = { 0, 0 }
self.surge = 0
self.emission = {1,1}
self.radius = {5,5}
self.rect = {0,0}
self.duration = -1
end
function ParticleEmitterConfig:build()
local em
if self.type == 'distance' then
em = MOAIParticleDistanceEmitter.new()
else
em = MOAIParticleTimedEmitter.new()
end
self:updateEmitter( em )
return em
end
function ParticleEmitterConfig:updateEmitter( em )
if self.distance and em.setDistance then em:setDistance( _unpack( self.distance ) ) end
if self.frequency and em.setFrequency then
local f1, f2 = _unpack( self.frequency )
em:setFrequency( 1/f1, f2 and 1/f2 or 1/f1 )
end
em.name = self.name
if self.angle then em:setAngle( _unpack(self.angle) ) end
if self.magnitude then em:setMagnitude( _unpack(self.magnitude) ) end
if self.radius[1] > 0 or self.radius[1] > 0 then
em:setRadius( _unpack(self.radius) )
else
local w, h = unpack( self.rect )
em:setRect( -w/2, -h/2, w/2, h/2 )
end
if self.emission then em:setEmission(_unpack(self.emission)) end
if self.surge then em:surge(self.surge) end
if em.setDuration then
em:setDuration( self.duration )
end
end
--------------------------------------------------------------------
function ParticleEmitterConfig:setFrequency( f1, f2 )
self.frequency = { f1 or 0 , f2 or 0 }
end
function ParticleEmitterConfig:getFrequency()
return unpack( self.frequency )
end
function ParticleEmitterConfig:setEmission( e1, e2 )
self.emission = { e1 or 0 , e2 or 0 }
end
function ParticleEmitterConfig:getEmission()
return unpack( self.emission )
end
function ParticleEmitterConfig:setMagnitude( min, max )
min = min or 0
self.magnitude = { min, max or min }
end
function ParticleEmitterConfig:getMagnitude()
return unpack( self.magnitude )
end
function ParticleEmitterConfig:setAngle( min, max )
min = min or 0
self.angle = { min, max or min }
end
function ParticleEmitterConfig:getAngle()
return unpack( self.angle )
end
function ParticleEmitterConfig:setRadius( r1, r2 )
self.radius = { r1 or 0 , r2 or 0 }
end
function ParticleEmitterConfig:getRadius()
return unpack( self.radius )
end
function ParticleEmitterConfig:setRect( w, h )
self.rect = { w or 1, h or 1 }
end
function ParticleEmitterConfig:getRect()
return unpack( self.rect )
end
--------------------------------------------------------------------
CLASS: ParticleStateConfig()
:MODEL {
Field 'name' :string() ;
Field 'active' :boolean() ;
Field 'life' :type('vec2') :range(0) :getset('Life');
Field 'initScript' :string() :no_edit();
Field 'renderScript' :string() :no_edit();
}
function ParticleStateConfig:__init()
self.name = 'state'
self.active = true
self.initScript = ''
self.renderScript = 'proc.p.moveAlong()\nsprite()\n'
self.life = { 1, 1 }
end
function ParticleStateConfig:build( regs )
regs = regs or {}
local iscript, rscript = false, false
local init,render
init = self.initScript and string.trim(self.initScript) or ''
render = self.renderScript and string.trim(self.renderScript) or ''
if init ~= '' then
local initFunc = loadstring( init )
if initFunc then iscript = makeParticleScript( initFunc, regs ) end
end
if render ~= '' then
renderFunc = loadstring( render )
if renderFunc then rscript = makeParticleScript( renderFunc, regs ) end
end
local regCount = 0
if regs.named then
for k,r in pairs(regs.named) do
if r.referred then
regCount = math.max( r.number, regCount )
end
end
end
builtScripts = { iscript, rscript }
local state = MOAIParticleState.new()
if self.damping then state:setDamping( self.damping ) end
if self.mass then state:setMass( _unpack(self.mass) ) end
if self.life then state:setTerm( _unpack(self.life) ) end
if builtScripts[1] then state:setInitScript ( builtScripts[1] ) end
if builtScripts[2] then state:setRenderScript ( builtScripts[2] ) end
-- if self.forces then
-- for i,f in ipairs(self.forces) do
-- if type(f)=='table' then
-- local force=makeParticleForce(f)
-- state:pushForce( force )
-- else
-- state:pushForce( f )
-- end
-- end
-- end
return state
end
function ParticleStateConfig:setLife( l1, l2 )
self.life = { l1, l2 or l1 }
end
function ParticleStateConfig:getLife()
return unpack( self.life )
end
--------------------------------------------------------------------
BLEND_MODES = {
{'alpha', 'alpha'},
{'add', 'add'},
{'multiply', 'multiply'},
{'normal', 'normal'},
{'mask', 'mask'},
{'solid', 'solid'},
}
CLASS: ParticleSystemConfig()
:MODEL{
Field 'particles' :int() :range(0);
Field 'sprites' :int() :range(0);
Field 'emitters' :array( ParticleEmitterConfig ) :sub() :no_edit();
Field 'states' :array( ParticleStateConfig ) :ref() :no_edit();
Field 'blend' :enum( BLEND_MODES );
Field 'deck' :asset( 'deck2d\\..*' );
}
function ParticleSystemConfig:__init()
self.particles = 100
self.sprites = 100
self.deck = false
self.stateCount = 0
self.emitters = {}
self.states = {}
self.allowPool = true
self.systemPool = {}
end
function ParticleSystemConfig:addEmitterConfig( config )
config = config or ParticleEmitterConfig()
table.insert( self.emitters, config )
return config
end
function ParticleSystemConfig:addStateConfig( config )
config = config or ParticleStateConfig()
table.insert( self.states, config )
return config
end
function ParticleSystemConfig:update()
end
function ParticleSystemConfig:buildStates()
local regs = {}
local builtStates = {}
for i, state in pairs( self.states ) do
table.insert( builtStates , state:build( regs ) )
end
local regCount = 0
if regs.named then
for k,r in pairs(regs.named) do
if r.referred then
regCount = math.max( r.number, regCount )
end
end
end
return builtStates, regCount
end
function ParticleSystemConfig:buildEmitter( name )
if not self.builtSystem then
self:buildSystem()
end
for i, emConfig in ipairs( self.emitters ) do
if emConfig.name == name then
local em = emConfig:build()
em:setSystem( self.builtSystem )
return em
end
end
return nil
end
function ParticleSystemConfig:buildSystem()
if self.built then return end
local system = MOAIParticleSystem.new()
local states, regCount = self:buildStates( regs )
system:reserveStates( #states )
for i, s in ipairs( states ) do
system:setState( i, s )
end
system.particleCount = self.particles or 50
system.spriteCount = self.sprites or 100
system.regCount = regCount + 1
system:reserveSprites ( system.spriteCount )
system:reserveParticles ( system.particleCount, system.regCount )
system:setDrawOrder( MOAIParticleSystem.ORDER_REVERSE )
if self.surge then system:surge(self.surge) end
setupMoaiProp( system, self )
system.config = self
self.builtSystem = system
return system
end
function ParticleSystemConfig:_pushToPool( sys )
if not self.allowPool then return end
table.insert( self.systemPool, sys )
sys:clearSprites()
sys:reserveParticles( sys.particleCount, sys.regCount )
end
function ParticleSystemConfig:requestSystem()
local sys = table.remove( self.systemPool )
if sys then return sys end
sys = self:buildSystem()
return sys
end
--[[
task of ParticleSystem is to:
1. hold ParticleState
2. hold ParticleEmitterSettings
]]
function loadParticleSystem( node )
local defData = loadAssetDataTable( node:getObjectFile('def') )
local systemConfig = deserialize( nil, defData )
return systemConfig
end
function saveParticleSystem( config, path )
return serializeToFile( config, path )
end
registerAssetLoader( 'particle_system', loadParticleSystem )
--------------------------------------------------------------------
function makeParticleForce(option)
assert(type(option)=='table')
local ft=option.type or 'force'
local f=MOAIParticleForce.new()
if ft=='force' then
f:setType(MOAIParticleForce.FORCE)
elseif ft=='gravity' then
f:setType(MOAIParticleForce.GRAVITY)
elseif ft=='offset' then
f:setType(MOAIParticleForce.OFFSET)
end
if option.magnitude then
if option.radius then
if option.magnitude>0 then
f:initBasin(option.radius,option.magnitude)
else
f:initAttractor(option.radius,-option.magnitude)
end
else
f:initRadial(option.magnitude)
end
else
f:initLinear(option.x or 0,option.y or 0)
end
f.name=option.name
return f
end
|
local function GetSpecEnts( ply )
local t = ply:Team()
local players = {}
-- if we're not on hunters, add props
if( t != TEAM_HUNTERS ) then
table.Add( players, team.GetPlayers( TEAM_PROPS ) )
end
-- if we're not on props, add hunters
if( t != TEAM_PROPS ) then
table.Add( players, team.GetPlayers( TEAM_HUNTERS ) )
end
-- remove dead players
local tempPlayers = {}
for _, v in pairs( players ) do
if( v:Alive() ) then
tempPlayers[#tempPlayers + 1] = v
end
end
return tempPlayers
end
function GM:PlayerDeathThink( ply )
local players = GetSpecEnts( ply )
-- default settings
if( !ply.spectateIndex ) then
ply.spectateIndex = 1
if( #players > 0 ) then
ply.spectateMode = OBS_MODE_CHASE
ply:SpectateEntity( players[ ply.spectateIndex ] )
else
ply.spectateMode = OBS_MODE_ROAMING
ply:SpectateEntity( nil )
end
ply:Spectate( ply.spectateMode )
end
if( #players > 0 ) then
if ply:KeyPressed( IN_JUMP ) then
ply.spectateMode = (ply.spectateMode % 3) + 4
ply:Spectate( ply.spectateMode )
elseif ply:KeyPressed( IN_ATTACK ) then
ply.spectateIndex = (ply.spectateIndex % #players) + 1
ply:SpectateEntity( players[ ply.spectateIndex ] )
elseif ply:KeyPressed( IN_ATTACK2 ) then
ply.spectateIndex = #players - (#players - ply.spectateIndex % #players) + 1
ply:SpectateEntity( players[ ply.spectateIndex ] )
end
end
-- this prevents respawning
return false
end
hook.Add( "PlayerSpawn", "Clear Spectator State", function( ply )
ply.spectateIndex = nil
ply.spectateMode = nil
end )
|
data:extend(
{
----------------------------------------------------------------------------------
{
type = "item",
name = "electric-nanfu",
icon = "__GodMode__/graphics/electric-nanfu-icon.png",
flags = {"goes-to-quickbar"},
subgroup = "energy",
order = "e[accumulator]-y[electric-nanfu]",
place_result = "electric-nanfu",
stack_size = 500
},
{
type = "item",
name = "solar-generator-big",
icon = "__GodMode__/graphics/solar-panel-big-icon.png",
flags = { "goes-to-quickbar" },
subgroup = "energy",
order = "z-z[solar-generator-big]",
place_result = "solar-generator-big",
stack_size = 500
},
----------------------------------------------------------------------------------
--[[
{
type = "item",
name = "electric-charging-sensor",
icon = "__GodMode__/graphics/electric-nanfu-icon.png",
flags = {"goes-to-quickbar"},
subgroup = "energy",
order = "e[accumulator]-z[electric-nanfu]",
place_result = "electric-charging-sensor",
stack_size = 50
},
--]]
}
)
|
nick = "Tattletale"
username = nil
realname = nil
password = "password"
logToConsole = true
threshold = 0.5
prior = 1/40
refeshRate = 0.5
server = "chat.freenode.net"
channels = {"#lesswrong", "#lw-bots", "##lw-meta"}
--set to nil or remove to put messages to the current channel
metaChannel = "##lw-meta"
--[[
--These parameters are only for testing
nick = "TattletaleTest"
channels = {"#lw-bots"}
logToConsole = true
metaChannel = nil
]]
|
-- Copyright (C) 2017 - DarkRoku12
-- Raw version.
-- Stack slot #1 = t.
local function set2( t , i , j , ival , jval )
t[ i ] = ival ; -- lua_rawseti(L, 1, i);
t[ j ] = jval ; -- lua_rawseti(L, 1, j);
end
local function sort_comp( a , b , comp )
if comp then
return comp( a , b )
end
return a < b ;
end
local auxsort ;
function auxsort( t , l , u , comp )
while l < u do
local i , j ; -- /* for tail recursion */
-- sort elements a[l], a[(l+u)/2] and a[u]
local a = t[ l ] -- lua_rawgeti(L, 1, l);
local b = t[ u ] -- lua_rawgeti(L, 1, u);
if sort_comp( b , a , comp ) then
set2( t , l , u , b , a ) -- /* swap a[l] - a[u] */
else
a , b = nil , nil ; -- lua_pop(L, 2);
end
if u - l == 1 then break end -- only 2 elements
i = math.floor( ( l + u ) / 2 ) ;
local a = t[ i ] -- lua_rawgeti(L, 1, i);
local b = t[ l ] -- lua_rawgeti(L, 1, l);
if sort_comp( a , b , comp ) then -- a[i] < a[l] ?
set2( t , i , l , b , a )
else
b = nil -- remove a[l]
b = t[ u ]
if sort_comp( b , a , comp ) then -- a[u]<a[i] ?
set2( t , i , u , b , a )
else
a , b = nil , nil ; -- lua_pop(L, 2);
end
end
if u - l == 2 then break end ; -- only 3 elements
local P = t[ i ] -- Pivot.
local P2 = P -- lua_pushvalue(L, -1);
local b = t[ u - 1 ]
set2( t , i , u - 1 , b , P2 )
-- a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
i = l ; j = u - 1 ;
while true do -- for( ; ; )
-- invariant: a[l..i] <= P <= a[j..u]
-- repeat ++i until a[i] >= P
i = i + 1 ; -- ++i
local a = t[ i ] -- lua_rawgeti(L, 1, i)
while sort_comp( a , P , comp ) do
i = i + 1 ; -- ++i
a = t[ i ] -- lua_rawgeti(L, 1, i)
end
-- repeat --j until a[j] <= P
j = j - 1 ; -- --j
local b = t[ j ]
while sort_comp( P , b , comp ) do
j = j - 1 ; -- --j
b = t[ j ] -- lua_rawgeti(L, 1, j)
end
if j < i then
P , a , b = nil , nil , nil ;
-- lua_pop(L, 3); /* pop pivot, a[i], a[j] */
break
end
set2( t , i , j , b , a )
end -- End while(true)
local a = t[ u - 1 ] -- lua_rawgeti(L, 1, u-1);
local b = t[ i ] -- lua_rawgeti(L, 1, i);
set2( t , u - 1 , i , b , a ) -- swap pivot (a[u-1]) with a[i]
-- a[l..i-1] <= a[i] == P <= a[i+1..u] */
-- adjust so that smaller half is in [j..i] and larger one in [l..u] */
if ( i - l ) < ( u - i ) then
j = l ;
i = i - 1 ;
l = i + 2 ;
else
j = i + 1 ;
i = u ;
u = j - 2 ;
end
auxsort( t , j , i , comp ) ; -- call recursively the smaller one */
end
-- end of while
-- repeat the routine for the larger one
end
-- sort function.
return function( t , comp )
assert( type( t ) == "table" )
if comp then
assert( type( comp ) == "function" )
end
auxsort( t , 1 , #t , comp )
end
|
local lpeg = require("lpeg")
local R, S, P, C = lpeg.R, lpeg.S, lpeg.P, lpeg.C
local Cf, Ct = lpeg.Cf, lpeg.Ct
local otFeatureMap = {
Ligatures = {
Required = "rlig",
Common = "liga",
Contextual = "clig",
Rare = "dlig",
Discretionary = "dlig",
Historic = "hlig"
},
Fractions = {
On = "frac",
Alternate = "afrc"
},
StylisticSet = function (i)
return string.format("ss%02i", tonumber(i))
end,
CharacterVariant = function (i)
return string.format("cv%02i", tonumber(i))
end,
Letters = {
Uppercase = "case",
SmallCaps = "smcp",
PetiteCaps = "pcap",
UppercaseSmallCaps = "c2sc",
UppercasePetiteCaps = "c2pc",
Unicase = "unic"
},
Numbers = {
Uppercase = "lnum",
Lining = "lnum",
LowerCase = "onum",
OldStyle = "onum",
Proportional = "pnum",
monospaced = "tnum",
SlashedZero = "zero",
Arabic = "anum"
},
Contextuals = {
Swash = "cswh",
Alternate = "calt",
WordInitial = "init",
WordFinal = "fina",
LineFinal = "falt",
Inner = "medi"
},
VerticalPosition = {
Superior = "sups",
Inferior = "subs",
Numerator = "numr",
Denominator = "dnom",
ScientificInferior = "sinf",
Ordinal = "ordn"
},
Style = {
Alternate = "salt",
Italic = "ital",
Ruby = "ruby",
Swash = "swsh",
Historic = "hist",
TitlingCaps = "titl",
HorizontalKana = "hkna",
VerticalKana = "vkna"
},
Diacritics = {
MarkToBase = "mark",
MarkToMark = "mkmk",
AboveBase = "abvm",
BelowBase = "blwm"
},
Kerning = {
Uppercase = "cpsp",
On = "kern"
},
CJKShape = {
Traditional = "trad",
Simplified = "smpl",
JIS1978 = "jp78",
JIS1983 = "jp83",
JIS1990 = "jp90",
Expert = "expt",
NLC = "nlck"
},
CharacterWidth = {
Proportional = "pwid",
Full = "fwid",
Half = "hwid",
Third = "twid",
Quarter = "qwid",
AlternateProportional = "palt",
AlternateHalf = "halt"
}
}
local function tagpos (pos, k, v)
return k, { posneg = pos, value = v }
end
-- Parser for feature strings
local featurename = C((1 - S",;:=")^1)
local value = C(SILE.parserBits.integer)
local tag = C(S"+-") * featurename * (P"=" * value)^0 * S",;:"^-1 / tagpos
local featurestring = Cf(Ct"" * tag^0, rawset)
-- Parser for fontspec strings
-- Refer to fontspec.pdf (see doc), Chapter 3, Table 4 (p. 37)
local fontspecsafe = R("AZ", "az", "09") + P":"
local fontspecws = SILE.parserBits.whitespace^0
local fontspecsep = P"," * fontspecws
local fontspecname = C(fontspecsafe^1)
local fontspeclist = fontspecws * P"{" *
Ct(fontspecws * fontspecname *
(fontspecsep * fontspecname * fontspecws)^0) *
P"}" * fontspecws
local otFeatures = pl.class(pl.Map)
function otFeatures:_init ()
self:super()
local str = SILE.settings:get("font.features")
local tbl = featurestring:match(str)
if not tbl then
SU.error("Unparsable Opentype feature string '"..str.."'")
end
for feat, flag in pairs(tbl) do
self:set(feat, flag.posneg == "+")
end
end
function otFeatures:__tostring ()
local ret = {}
for _, f in ipairs(self:items()) do
ret[#ret+1] = (f[2] and "+" or "-") .. f[1]
end
return table.concat(ret, ";")
end
function otFeatures:loadOption (name, val, invert)
local posneg = not invert
local key = otFeatureMap[name]
if not key then
SU.warn("Unknown OpenType feature " .. name)
else
local matches = lpeg.match(fontspeclist, val)
for _, v in ipairs(matches or { val }) do
v = v:gsub("^No", function () posneg = false; return "" end)
local feat = type(key) == "function" and key(v) or key[v]
if not feat then
SU.warn("Bad OpenType value " .. v .. " for feature " .. name)
else
self:set(feat, posneg)
end
end
end
end
-- Input like {Ligatures = Historic} or {Ligatures = "{Historic, Discretionary}"}
--
-- Most real-world use should be single value, but multiple value use is not
-- that odd. Junicode, for example, a common font among medievalists, has many
-- Stylistic Sets and Character Variations, many of which make sense to enable
-- simultaneously.
function otFeatures:loadOptions (options, invert)
SU.debug("features", "Features was", self)
for k, v in pairs(options) do
self:loadOption(k, v, invert)
end
SU.debug("features", "Features interpreted as", self)
end
function otFeatures:unloadOptions (options)
self:loadOptions(options, true)
end
local fontfn = SILE.Commands.font
local function registerCommands (_)
SILE.registerCommand("add-font-feature", function (options, _)
local otfeatures = otFeatures()
otfeatures:loadOptions(options)
SILE.settings:set("font.features", tostring(otfeatures))
end)
SILE.registerCommand("remove-font-feature", function(options, _)
local otfeatures = otFeatures()
otfeatures:unloadOptions(options)
SILE.settings:set("font.features", tostring(otfeatures))
end)
SILE.registerCommand("font", function (options, content)
local otfeatures = otFeatures()
-- It is guaranteed that future releases of SILE will not implement non-OT \font
-- features with capital letters.
-- Cf. https://github.com/sile-typesetter/sile/issues/992#issuecomment-665575353
-- So, we reserve 'em all. ⍩⃝
for k, v in pairs(options) do
if k:match('^[A-Z]') then
otfeatures:loadOption(k, v)
options[k] = nil
end
end
SU.debug("features", "Font features parsed as:", otfeatures)
options.features = (options.features and options.features .. ";" or "") .. tostring(otfeatures)
return fontfn(options, content)
end, tostring(SILE.Help.font) .. " (overridden)")
end
return {
registerCommands = registerCommands,
documentation = [[\begin{document}
As mentioned in Chapter 3, SILE automatically applies ligatures defined by the fonts
that you use. These ligatures are defined by tables of \em{features} within
the font file. As well as ligatures (multiple glyphs displayed as a single glyph),
the features tables also declare other glyph substitutions.
The \autodoc:package{features} package provides an interface to selecting the features that you
want SILE to apply to a font. The features available will be specific to the font file;
some fonts come with documentation explaining their supported features. Discussion
of OpenType features is beyond the scope of this manual.
These features can be turned on and off by passing ‘raw’ feature names to the
\autodoc:command{\font} command like so:
\begin{verbatim}
\line
\\font[features="+dlig,+hlig"]{...} \% turn on discretionary and historic ligatures
\line
\end{verbatim}
However, this is unwieldy and requires memorizing the feature codes. \autodoc:package{features}
provides two commands, \autodoc:command{\add-font-feature} and \autodoc:command{\remove-font-feature},
which make it easier to access OpenType features. The interface is patterned on the
TeX package \code{fontspec}; for full documentation of the OpenType features supported,
see the documentation for that package.\footnote{\code{http://texdoc.net/texmf-dist/doc/latex/fontspec/fontspec.pdf}}
Here is how you would turn on discretionary and historic ligatures with the \autodoc:package{features}
package:
\begin{verbatim}
\line
\\add-font-feature[Ligatures=Rare]\\add-font-feature[Ligatures=Discretionary]
...
\\remove-font-feature[Ligatures=Rare]\\remove-font-feature[Ligatures=Discretionary]
\line
\end{verbatim}
\end{document}]] }
|
--[[
Sem Klauke, 2019
Random Kill List, Gary's Mod, TTT
Loader for all server side files
]]--
include("random-kill-list_server.lua")
|
function fact(n, ans)
::call::
if n == 0 then
return ans
else
n, ans = n - 1, ans * n
goto call
end
end
print(fact(6, 1))
|
object_draft_schematic_dance_prop_prop_glowstick_r_s02 = object_draft_schematic_dance_prop_shared_prop_glowstick_r_s02:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_dance_prop_prop_glowstick_r_s02, "object/draft_schematic/dance_prop/prop_glowstick_r_s02.iff")
|
--===========================================================================--
-- --
-- System.Web.IContextOutputHandler --
-- --
--===========================================================================--
--===========================================================================--
-- Author : kurapica125@outlook.com --
-- URL : http://github.com/kurapica/PLoop --
-- Create Date : 2016/04/08 --
-- Update Date : 2018/03/15 --
-- Version : 1.0.0 --
--===========================================================================--
PLoop(function(_ENV)
--- Represents the interface of context output handler
__Sealed__() interface "System.Web.IContextOutputHandler" (function (_ENV)
extend "IHttpOutput" "IHttpContextHandler"
export {
HeadPhase = IHttpContextHandler.ProcessPhase.Head,
}
-----------------------------------------------------------------------
-- property --
-----------------------------------------------------------------------
property "ContentType" { Type = String, Default = "text/html" }
-- Override Method
function Process(self, context, phase)
if phase == HeadPhase then
context.Response.ContentType = self.ContentType
self.Context = context
return self:OnLoad(context)
else
return self:SafeRender(context.Response.Write, "")
end
end
end)
end)
|
object_tangible_collection_rare_rifle_trando_laser = object_tangible_collection_shared_rare_rifle_trando_laser:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_rare_rifle_trando_laser, "object/tangible/collection/rare_rifle_trando_laser.iff")
|
PKPlayer = {}
function PKPlayer.new()
local entity = entityManager:createEntity()
local boundingBox = entity:addBoundingBox()
boundingBox.rect = FloatRect.new(-6, 4, 10, 8)
local transform = entity:addTransform()
transform.position = Vector3.new(1920 / 2, 1080 / 2, 4)
transform.scale = Vector2.new(0.5, 0.5)
local input = entity:addInput()
input.speed = 100
local kb = entity:addKineticBody()
local texture = entity:addAnimatedSprite()
texture.texture_id = "pokemon_player_sheet"
texture:setCurrentAnimation("idle")
texture.currentAnimationFrame = 0
texture.sprite:setOrigin(32, 32)
local frame_defs = {}
i = 1
for y = 0,3 do
for x = 0,3 do
frame_defs[i] = { x=x * 64, y=y * 64, width=64, height=64}
i = i + 1
end
end
animations = {
up = {
{frame=frame_defs[13], time=0.1},
{frame=frame_defs[14], time=0.1},
{frame=frame_defs[15], time=0.1},
{frame=frame_defs[16], time=0.1},
},
down = {
{frame=frame_defs[1], time=0.1},
{frame=frame_defs[2], time=0.1},
{frame=frame_defs[3], time=0.1},
{frame=frame_defs[4], time=0.1},
},
left = {
{frame=frame_defs[5], time=0.1},
{frame=frame_defs[6], time=0.1},
{frame=frame_defs[7], time=0.1},
{frame=frame_defs[8], time=0.1},
},
right = {
{frame=frame_defs[9], time=0.1},
{frame=frame_defs[10], time=0.1},
{frame=frame_defs[11], time=0.1},
{frame=frame_defs[12], time=0.1},
},
idle = {
{frame=frame_defs[1], time=1}
}
}
texture:setAnimations(animations)
return entity
end
|
local _M = {}
function _M:match(route)
route:get('/index', 'index_controller', 'index')
route:group({
'locale',
'throttle'
}, function()
route:post('/login', 'auth_controller', 'login')
route:post('/send/sms', 'notify/sms_notify_controller', 'guest_send_sms')
route:get('/oauth/wechat/web', 'wechat_controller', 'webLogin')
route:get('/users/{id}', 'user_controller', 'show')
route:group({
'verify_guest_sms_code'
}, function()
route:post('/register', 'auth_controller', 'register')
route:patch('/forget-password', 'auth_controller', 'forget_password')
end)
route:group({
'authenticate',
}, function()
route:post('/logout', 'auth_controller', 'logout')
route:patch('/reset-password', 'auth_controller', 'reset_password')
route:group({
'token_refresh'
}, function()
route:get('/userinfo', 'user_controller', 'userinfo')
end)
end)
end)
end
return _M
|
local function get_icon(name)
local icons = {
-- Feedback
error = " ",
warning = " ",
info = " ",
hint = " ",
success = " ",
bulb = " ",
-- Actions
rename = " ",
preview = " ",
diagnostic = " ",
definition = " ",
reference = " ",
close = "",
-- Git
branch = " ",
added = " ",
removed = " ",
modified = "● ",
-- Separators
separator_left = " ",
separator_right = " ",
slant_left = " ◢",
slant_right = "◣ ",
line = "▌",
-- Other
keyboard = " ",
file = " ",
caret_right = " ",
caret_left = " ",
}
return icons[name]
end
return { get_icon = get_icon }
|
-- All credit for the emplacement gun entity goes to Zaubermuffin and his/her affiliates.
-- His/her steam profile: http://steamcommunity.com/id/zaubermuffin
-- ZAR3
-- Copyright (c) 2012 Zaubermuffin
--
-- 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.
--
-- Based on the original Bouncy Ball.
include('shared.lua')
-- Import the function(s) and remove their globals.
local FindAR3At = ZAR3_FindAR3At
ZAR3_FindAR3At, ZAR3_AR3Position = nil, nil
local AR3 = nil -- The AR3 we are currently using.
local Shooting = false -- If we are shooting or not
-- This message is used for both, getting in and out of AR3s.
local function ZAR3_S(msg)
AR3 = msg:ReadEntity()
local wep = LocalPlayer():GetActiveWeapon()
local vm = LocalPlayer():GetViewModel()
-- We won't mess around with you.
if not IsValid(wep) then
-- Worst case: Make us visible again.
if IsValid(vm) then
vm:SetNoDraw(false)
end
return
end
if IsValid(AR3) then
vm:SetNoDraw(true)
-- "nicer", but way buggier and breaking quite a lot:
--~ -- Holster it
--~ wep:SendWeaponAnim(ACT_VM_HOLSTER)
--~ -- Do we need to multiply with the playback rate? I doubt it
--~ -- Hide the weapon as soon as it's gone.
--~ -- I'd like to keep it, but the repeat-this-sequence glitch is annoying.
--~ timer.Simple(vm:SequenceDuration(), function() local vm = LocalPlayer():GetViewModel() if IsValid(vm) then vm:SetNoDraw(true) end end)
else
-- Make the weapon visible again.
if IsValid(vm) then
vm:SetNoDraw(false)
end
-- Play the "draw" animation.
wep:SendWeaponAnim(ACT_VM_DRAW)
-- No stuff until this has been done.
wep:SetNextPrimaryFire(math.max(CurTime() + wep:SequenceDuration(), wep:GetNextPrimaryFire()))
wep:SetNextSecondaryFire(math.max(CurTime() + wep:SequenceDuration(), wep:GetNextSecondaryFire()))
-- There seems to be a repeating-glitch, somehow, avoid that. Yes, if you start shooting it will break the animation, but it's better than having to re-draw all the time.
timer.Simple(vm:SequenceDuration(), function() if IsValid(wep) and wep == LocalPlayer():GetActiveWeapon() then wep:SendWeaponAnim(ACT_VM_IDLE) end end)
end
end
usermessage.Hook('ZAR3_S', ZAR3_S)
function ENT:Draw()
self:DrawModel()
end
-- Override CreateMove - because there seems to be no way to intercept attacks on the server,
-- we have to "catch" them on the client and tell the entity that way.
local function CreateMove(cmd)
if IsValid(AR3) then
if cmd:KeyDown(IN_ATTACK) then
cmd:SetButtons(cmd:GetButtons() - IN_ATTACK)
if not Shooting then
Shooting = true
RunConsoleCommand('zar3_attack', '1')
end
elseif Shooting then
Shooting = false
RunConsoleCommand('zar3_attack', '0')
end
if cmd:KeyDown(IN_ATTACK2) then
cmd:SetButtons(cmd:GetButtons() - IN_ATTACK2)
end
end
end
hook.Add('CreateMove', '_ZAR3CreateMove', CreateMove)
-- Hide the ammo while we're operating one of these.
local function HUDShouldDraw(name)
if IsValid(AR3) and name == 'CHudAmmo' then
return false
end
end
hook.Add('HUDShouldDraw', '_ZAR3HUDShouldDraw', HUDShouldDraw)
|
function start()
play_music("music/castle.mid");
process_outline()
add_wall_group(2, 1, 6, 2, 3, 0)
add_wall_group(2, 6, 6, 2, 3, 0)
add_wall_group(2, 3, 6, 3, 4, 0)
pig = add_npc("pig_guard", 2, 71, 182)
set_entity_direction(pig, DIR_S)
going_down = Active_Block:new{x=9, y=10, width=3, height=2}
going_out = Active_Block:new{x=5, y=13, width=3, height=2}
end
function logic()
if (going_down:entity_is_colliding(0)) then
next_player_layer = 4
change_areas("castle_knight_left1", DIR_S, 246, 86)
elseif (going_out:entity_is_colliding(0)) then
next_player_layer = 6
change_areas("castle", DIR_S, 320, 391)
end
end
function activate(activator, activated)
if (activated == pig) then
speak(false, false, true, t("PIG_TOWER_7"), "", pig, pig)
end
end
function collide(id1, id2)
end
function uncollide(id1, id2)
end
function action_button_pressed(n)
end
function attacked(attacker, attackee)
end
function stop()
end
|
-- #######################################
-- ## Project: MTA:scp-088 ##
-- ## Name: Ego ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
Ego = {};
Ego.__index = Ego;
--[[
]]
local curVehRot = 0
local oldVehRot = 0
-- ///////////////////////////////
-- ///// New //////
-- ///////////////////////////////
function Ego:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// FreecamFrame //////
-- ///////////////////////////////
function Ego:FreecamFrame()
--if(isPedAiming(localPlayer) ~= true) then
if(self.egoState == true) then
local camPosX, camPosY, camPosZ = getPedBonePosition ( getLocalPlayer(), 8 )
local angleZ = math.sin(self.rotY)
local angleY = math.cos(self.rotY) * math.cos(self.rotX)
local angleX = math.cos(self.rotY) * math.sin(self.rotX)
local camTargetX = camPosX + ( angleX ) * 100
local camTargetY = camPosY + angleY * 100
local camTargetZ = camPosZ + angleZ * 100
local veh = getPedOccupiedVehicle ( getLocalPlayer() )
if veh then
local rx, ry, curVehRot = getElementRotation ( veh )
local changedRotation = oldVehRot - curVehRot
oldVehRot = curVehRot
if not totalRot then
totalRot = curVehRot
end
totalRot = changedRotation * 2 + totalRot
local rotX = ( ( self.rotX * 360 / self.PI ) + totalRot ) / 360 * self.PI
if rotX > self.PI then
rotX = rotX - 2 * self.PI
elseif rotX < -self.PI then
rotX = rotX + 2 * self.PI
end
camTargetX = camPosX + ( math.cos(self.rotY) * math.sin(rotX) ) * 100
camTargetY = camPosY + ( math.cos(self.rotY) * math.cos(rotX) ) * 100
end
setCameraMatrix ( camPosX, camPosY, camPosZ, camTargetX, camTargetY, camTargetZ, 0, 80 )
else
local cameraAngleX = self.rotX
local cameraAngleY = self.rotY
local freeModeAngleZ = math.sin(cameraAngleY)
local freeModeAngleY = math.cos(cameraAngleY) * math.cos(cameraAngleX)
local freeModeAngleX = math.cos(cameraAngleY) * math.sin(cameraAngleX)
local camPosX, camPosY, camPosLastZ = getPedBonePosition(localPlayer, 5)
local zoom = self.zoom;
if(isPedInVehicle(localPlayer)) then
camPosX, camPosY, camPosLastZ = getElementPosition(getPedOccupiedVehicle(localPlayer))
camPosLastZ = camPosLastZ + 0.5
zoom = self.vehicleZoom;
end
local zOffset = 3
local camPosZ = camPosLastZ + zOffset
local mspeed = 2
local speed = 0
local ratio = 3
-- Update the camera position based on the forwards/backwards speed
PosX = camPosX + freeModeAngleX * speed
PosY = camPosY + freeModeAngleY * speed
camPosZ = camPosLastZ + freeModeAngleZ * speed
-- calculate a target based on the current position and an offset based on the angle
local camTargetX = PosX + freeModeAngleX * zoom
local camTargetY = PosY + freeModeAngleY * zoom
local camTargetZ = camPosZ + freeModeAngleZ * zoom
camPosX = PosX - ( camTargetX - PosX ) / ratio
camPosY = PosY - ( camTargetY - PosY ) / ratio
camPosZ = camPosZ - ( camTargetZ - camPosZ ) / ratio
local rotX, rotY, rotZ = self.rotX, self.rotY, freeModeAngleZ
local rx, ry, rz = math.rad(rotX), math.rad(rotY), math.rad(rotZ)
local matrix = {}
matrix[1] = {}
matrix[1][1] = math.cos(rz)*math.cos(ry) - math.sin(rz)*math.sin(rx)*math.sin(ry)
matrix[1][2] = math.cos(ry)*math.sin(rz) + math.cos(rz)*math.sin(rx)*math.sin(ry)
matrix[1][3] = -math.cos(rx)*math.sin(ry)
matrix[2] = {}
matrix[2][1] = -math.cos(rx)*math.sin(rz)
matrix[2][2] = math.cos(rz)*math.cos(rx)
matrix[2][3] = math.sin(rx)
matrix[3] = {}
matrix[3][1] = math.cos(rz)*math.sin(ry) + math.cos(ry)*math.sin(rz)*math.sin(rx)
matrix[3][2] = math.sin(rz)*math.sin(ry) - math.cos(rz)*math.cos(ry)*math.sin(rx)
matrix[3][3] = math.cos(rx)*math.cos(ry)
matrix[4] = {}
matrix[4][1], matrix[4][2], matrix[4][3] = getPedBonePosition(localPlayer, 31)
if not (isLineOfSightClear(PosX, PosY, camPosLastZ, camPosX, camPosY, camPosZ, true, false, false, false, false, false, false)) then
_,camPosX,camPosY,camPosZ = processLineOfSight(PosX, PosY, camPosLastZ, camPosX, camPosY, camPosZ, true, false, false, false, false, false, false)
end
setCameraMatrix ( camPosX, camPosY, camPosZ, camTargetX, camTargetY, camTargetZ )
end
-- Roll --
if(getPedMoveState(localPlayer) == "stand") then
local _, _, _, x1, y1 = getCameraMatrix()
local x2, y2, z = getElementPosition(localPlayer);
local rot = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
setPedRotation(localPlayer, rot-270)
-- setElementAlpha(localPlayer, 0)
end
-- else
-- if(getCameraTarget() ~= localPlayer) then
-- setCameraTarget(localPlayer);
-- setGameSpeed(1)
-- end
-- end
end
-- ///////////////////////////////
-- ///// FreecamMouse //////
-- ///////////////////////////////
function Ego:FreecamMouse(cX,cY,aX,aY)
if isCursorShowing() or isMTAWindowActive() then
self.delay = 5
return
elseif self.delay > 0 then
self.delay = self.delay - 1
return
end
local width, height = guiGetScreenSize()
local aX = aX - width / 2
local aY = aY - height / 2
self.rotX = self.rotX + aX * self.mouseSensitivity * 0.01745
self.rotY = self.rotY - aY * self.mouseSensitivity * 0.01745
if self.rotX > self.PI then
self.rotX = self.rotX - 2 * self.PI
elseif self.rotX < -self.PI then
self.rotX = self.rotX + 2 * self.PI
end
if self.rotY > self.PI then
self.rotY = self.rotY - 2 * self.PI
elseif self.rotY < -self.PI then
self.rotY = self.rotY + 2 * self.PI
end
if self.rotY < -self.PI / 2.05 then
self.rotY = -self.PI / 2.05
elseif self.rotY > self.PI / 2.05 then
self.rotY = self.PI / 2.05
end
-- Animation --
local _, _, _, x1, y1, z1 = getCameraMatrix();
local x2, y2, z2 = getElementPosition(localPlayer);
if(x1 and y1 and z1 and x2 and y2 and z2) and (isElementMoving(localPlayer) ~= true) and (getPedSimplestTask(localPlayer) == "TASK_SIMPLE_PLAYER_ON_FOOT") then
local oldrot = getPedRotation(localPlayer);
local rot = math.atan2(y2 - y1, x2 - x1) * 180 / math.pi
rot = rot+90
--[[setPedRotation(localPlayer, rot);
outputChatBox(oldrot-rot)
if(math.floor(oldrot-rot) > 0) then
if(getPedAnimation(localPlayer) == false) then
setPedAnimation(localPlayer, "ped", "Turn_R", 50, false, false, true);
end
elseif(math.floor(oldrot-rot) < 0) then
if(getPedAnimation(localPlayer) == false) then
setPedAnimation(localPlayer, "ped", "Turn_L", 50, false, false, true);
end
elseif(math.floor(oldrot-rot) == 0) then
if(getPedAnimation(localPlayer) ~= false) then
setPedAnimation(localPlayer)
end
end]]
end
end
-- ///////////////////////////////
-- ///// Start //////
-- ///////////////////////////////
function Ego:Start()
if(self.state == false) then
self.state = true;
addEventHandler("onClientPreRender", getRootElement(), self.freecamFrameFunc)
addEventHandler("onClientRender", getRootElement(), self.freecamFrameFunc)
addEventHandler("onClientCursorMove",getRootElement(), self.freecamMouseFunc)
end
end
-- ///////////////////////////////
-- ///// Stop //////
-- ///////////////////////////////
function Ego:Stop()
if(self.state == true) then
self.state = false;
removeEventHandler("onClientPreRender", getRootElement(), self.freecamFrameFunc)
removeEventHandler("onClientRender", getRootElement(), self.freecamFrameFunc)
removeEventHandler("onClientCursorMove",getRootElement(), self.freecamMouseFunc)
end
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///////////////////////////////
function Ego:Constructor(...)
self.freecamFrameFunc = function(...) self:FreecamFrame(...) end;
self.freecamMouseFunc = function(...) self:FreecamMouse(...) end;
self.naheFunc = function(key)
if(key == "num_add") and (isPedInVehicle(localPlayer) == false) or (key == "mouse_wheel_up") and (isPedInVehicle(localPlayer) == true) then
if(self.egoState == false) then
if(isPedInVehicle(localPlayer)) then
if(self.vehicleZoom > 2.5) then
self.vehicleZoom = self.vehicleZoom-1
end
else
if(self.zoom > 2.5) then
self.zoom = self.zoom-1
end
end
end
end
end;
self.fernFunc = function(key)
if(key == "num_sub") and (isPedInVehicle(localPlayer) == false) or (key == "mouse_wheel_down") and (isPedInVehicle(localPlayer) == true) then
if(self.egoState == false) then
if(isPedInVehicle(localPlayer)) then
if(self.vehicleZoom < 100) then
self.vehicleZoom = self.vehicleZoom+1
end
else
if(self.zoom < 50) then
self.zoom = self.zoom+1
end
end
end
end
end
self.toggleCharFunc = function()
if(self.egoState == false) then
self.egoState = true;
--self:Stop()
--setCameraTarget(localPlayer);
else
self.egoState = false;
--self:Start()
end
end;
self.resetFunc = function(key, state)
if(state == "down") then
self:Stop()
setCameraTarget(localPlayer);
else
self:Start()
end
end
self.rotX, self.rotY = 0, 0
self.camVehRot = 0
self.rot = 0
self.curVehRot = 0
self.oldVehRot = 0
self.state = false
self.egoState = false;
self.mouseSensitivity = 0.1
self.delay = 0
self.PI = math.pi
logger:OutputInfo("[CALLING] Ego: Constructor");
self.maxroll = 0;
self.zoom = 15;
self.vehicleZoom = 35;
self.currentroll = 0;
self.rollstate = false;
self.toggleCharFunc()
--bindKey("y", "down", self.toggleCharFunc);
bindKey("mouse_wheel_up", "down", self.naheFunc);
bindKey("mouse_wheel_down", "down", self.fernFunc);
bindKey("num_add", "down", self.naheFunc);
bindKey("num_sub", "down", self.fernFunc);
bindKey("backspace", "down", self.resetFunc);
bindKey("backspace", "up", self.resetFunc)
end
-- EVENT HANDLER --
function isPedAiming ( thePedToCheck )
if isElement(thePedToCheck) then
if getElementType(thePedToCheck) == "player" or getElementType(thePedToCheck) == "ped" then
if getPedTask(thePedToCheck, "secondary", 0) == "TASK_SIMPLE_USE_GUN" then
return true
end
end
end
return false
end
function isElementMoving(theElement)
if isElement(theElement)then --First check if the given argument is an element
local x, y, z = getElementVelocity(theElement) --Get the velocity of the element given in our argument
if x ~= 0 and y ~= 0 and z ~= 0 then --When there is a movement on X, Y or Z return true because our element is moving
return true
end
end
return false
end
|
require "../control/image_manager.lua"
Direction = {
LEFT = 0,
UP = 1,
RIGHT = 2,
DOWN = 3
}
Unit = {
UnitFilePath = "../unit.me5",
UnitGroupName = {
ATK = "ATK",
MOV = "MOV",
SPC = "SPC"
},
UnitClipingSize = {
ATK = {64, 64},
MOV = {48, 48},
SPC = {48, 48}
},
New = function(self, index)
local newUnit = {}
newUnit.Direction = Direction.DOWN
newUnit.AtkImage = ImageManager:CreateImage({
FilePath = self.UnitFilePath,
Group = {
Main = self.UnitGroupName.ATK,
Sub = index
},
IsLoadMirror = true
})
newUnit.AtkImage:SetClipingSize(self.UnitClipingSize.ATK[1], self.UnitClipingSize.ATK[2])
newUnit.AtkImage:SetClipingCoordinate(0, 0)
newUnit.MovImage = ImageManager:CreateImage({
FilePath = self.UnitFilePath,
Group = {
Main = self.UnitGroupName.MOV,
Sub = index
},
IsLoadMirror = true
})
newUnit.MovImage:SetClipingSize(self.UnitClipingSize.MOV[1], self.UnitClipingSize.MOV[2])
newUnit.MovImage:SetClipingCoordinate(0, 0)
newUnit.SpcImage = ImageManager:CreateImage({
FilePath = self.UnitFilePath,
Group = {
Main = self.UnitGroupName.SPC,
Sub = index
},
IsLoadMirror = true
})
newUnit.SpcImage:SetClipingSize(self.UnitClipingSize.SPC[1], self.UnitClipingSize.SPC[2])
newUnit.Layout = nil
newUnit.X = 0
newUnit.Y = 0
setmetatable(newUnit, self)
self.__index = self
return newUnit
end,
Show = function(self, layout, x, y)
self.X = x
self.Y = y
self.Layout = layout
self.AtkImageIndex = layout:AddImage(self.AtkImage, x, y, false)
self.MovImageIndex = layout:AddImage(self.MovImage, x, y, false)
self.SpcImageIndex = layout:AddImage(self.SpcImage, x, y, false)
self:Stop()
end,
Stop = function(self)
if self.Layout ~= nil then
self.Layout:HideImage(self.AtkImageIndex)
self.Layout:HideImage(self.SpcImageIndex)
if self.Direction == Direction.LEFT then
self.MovImage:Mirror(false)
self.MovImage:SetClipingCoordinate(0, 8)
elseif self.Direction == Direction.UP then
self.MovImage:Mirror(false)
self.MovImage:SetClipingCoordinate(0, 7)
elseif self.Direction == Direction.RIGHT then
self.MovImage:Mirror(true)
self.MovImage:SetClipingCoordinate(0, 8)
elseif self.Direction == Direction.DOWN then
self.MovImage:Mirror(false)
self.MovImage:SetClipingCoordinate(0, 6)
end
self.Layout:ShowImage(self.MovImageIndex)
end
end,
MoveLeft = function(self)
self.Direction = Direction.LEFT
local tick = 0
if self.X > 0 then
self.MovImage:Mirror(false)
for i = 0, 47 do
self.X = self.X - 1
if tick == 0 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 5)
tick = 1
elseif tick == 1 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 4)
tick = 0
end
self.Layout:MoveImage(self.MovImageIndex, self.X, self.Y)
end
self:Stop()
end
end,
MoveUp = function(self)
self.Direction = Direction.UP
local tick = 0
if self.Y > 0 then
self.MovImage:Mirror(false)
for i = 0, 47 do
self.Y = self.Y - 1
if tick == 0 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 3)
tick = 1
elseif tick == 1 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 2)
tick = 0
end
self.Layout:MoveImage(self.MovImageIndex, self.X, self.Y)
end
self:Stop()
end
end,
MoveRight = function(self)
self.Direction = Direction.RIGHT
local tick = 0
self.MovImage:Mirror(true)
for i = 0, 47 do
self.X = self.X + 1
if tick == 0 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 5)
tick = 1
elseif tick == 1 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 4)
tick = 0
end
self.Layout:MoveImage(self.MovImageIndex, self.X, self.Y)
end
self:Stop()
end,
MoveDown = function(self)
self.Direction = Direction.DOWN
local tick = 0
self.MovImage:Mirror(false)
for i = 0, 47 do
self.Y = self.Y + 1
if tick == 0 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 1)
tick = 1
elseif tick == 1 and i % 12 == 0 then
self.MovImage:SetClipingCoordinate(0, 0)
tick = 0
end
self.Layout:MoveImage(self.MovImageIndex, self.X, self.Y)
end
self:Stop()
end,
Attack = function(self)
self.Layout:HideImage(self.MovImageIndex)
self.Layout:MoveImage(self.AtkImageIndex, self.X - 8, self.Y - 8)
self.Layout:ShowImage(self.AtkImageIndex)
for i = 0, 3 do
if self.Direction == Direction.LEFT then
self.AtkImage:Mirror(false)
self.AtkImage:SetClipingCoordinate(0, 8 + i)
elseif self.Direction == Direction.UP then
self.AtkImage:Mirror(false)
self.AtkImage:SetClipingCoordinate(0, 4 + i)
elseif self.Direction == Direction.RIGHT then
self.AtkImage:Mirror(true)
self.AtkImage:SetClipingCoordinate(0, 8 + i)
elseif self.Direction == Direction.DOWN then
self.AtkImage:Mirror(true)
self.AtkImage:SetClipingCoordinate(0, i)
end
self.Layout:Refresh()
gameManager:Delay(150)
end
self:Stop()
end
}
|
----
-- @file PhysicsShapeHeightfieldTerrainBuilder
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function PhysicsShapeHeightfieldTerrainBuilder:calculateSerializeBufferSize()
end
---- Brief description.
-- <#Description#>
-- @param btSerializer <#btSerializer description#>
-- @return <#return value description#>
function PhysicsShapeHeightfieldTerrainBuilder:serialize(btSerializer)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function PhysicsShapeHeightfieldTerrainBuilder:getObjectType()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function PhysicsShapeHeightfieldTerrainBuilder:getClassName()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function PhysicsShapeHeightfieldTerrainBuilder:getType()
end
---- Brief description.
-- <#Description#>
-- @param size <#size description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.createArray(size)
end
---- Brief description.
-- <#Description#>
-- @param array <#array description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.destroyArray(array)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.create()
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.clone(object)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.destroy(object)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @param L <#L description#>
-- @param stack_index <#stack_index description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.load(object, L, stack_index)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function NJLI.PhysicsShapeHeightfieldTerrainBuilder.type()
end
|
return {
["button.okay"] = "Ok",
["button.remove"] = "Remover",
["button.rename"] = "Renomear",
["button.copy"] = "Cópia de",
["button.find"] = "Achar",
["button.comment"] = "Comente",
["button.uncomment"] = "Remover comentário",
["button.hide"] = "Esconder",
["button.show"] = "Mostrar",
["button.block.find"] = "Encontrar bloco",
["menu.myprogram"] = "Meu programa",
["menu.continue"] = "Continuar",
["menu.settings"] = "Configurações",
["menu.testers"] = "Versão testadores:",
["menu.developers"] = "Versão desenvolvedores:",
["programs.entername"] = "Digite nome programa",
["programs.changename"] = "Alterar nome programa",
["program.images"] = "Sprites",
["program.scripts"] = "Roteiros",
["program.sounds"] = "Sons",
["program.videos"] = "Vídeos",
["program.fonts"] = "Fontes",
["program.export"] = "Exportar",
["program.build"] = "Construir",
["program.editor"] = "Editor expressão",
["scripts.entername"] = "Digite nome roteiro",
["scripts.changename"] = "Alterar nome roteiro",
["images.entername"] = "Digite nome sprite",
["images.changename"] = "Alterar nome sprite",
["sounds.entername"] = "Digite nome som",
["sounds.changename"] = "Alterar nome som",
["videos.entername"] = "Digite nome vídeos",
["videos.changename"] = "Alterar nome vídeos",
["fonts.entername"] = "Digite nome fonte",
["fonts.changename"] = "Alterar nome fonte",
["blocks.entertext"] = "Digite texto",
["blocks.everyone"] = "Todos blocos",
["blocks.none"] = "Nenhum",
["blocks.events"] = "Eventos",
["blocks.onStart"] = "No início",
["blocks.onStart.params"] = {"Nota:"},
["blocks.vars"] = "Dados",
["blocks.setVar"] = "Definir valor variável",
["blocks.setVar.params"] = {"Nome variável:", "Valor:"},
["blocks.newText"] = "Criar texto",
["blocks.newText.params"] = {"Nome texto:", "Texto:", "Fonte:", "Tamanho:", "Cor:", "Opacidade (0-100):"},
["blocks.control"] = "Controle",
["blocks.requestApi"] = "Solicitar método API",
["blocks.requestApi.params"] = {"Lua código:"},
["editor.button.text"] = "Texto",
["editor.button.local"] = "Local",
["editor.button.hide"] = "Tapar",
["editor.list.var"] = "Variáveis",
["editor.list.table"] = "Tabelas",
["editor.list.fun"] = "Funções",
["editor.list.math"] = "Matemática",
["editor.list.prop"] = "Propriedades",
["editor.list.log"] = "Lógica",
["editor.list.device"] = "Dispositivo",
}
|
-- Change these:
local jid, password = "user@example.com", "secret";
-- This line squishes verse each time you run,
-- handy if you're hacking on Verse itself
--os.execute("squish --minify-level=none");
require "verse".init("client");
c = verse.new();
c:add_plugin("version");
c:add_plugin("pep");
-- Add some hooks for debugging
c:hook("opened", function () print("Stream opened!") end);
c:hook("closed", function () print("Stream closed!") end);
c:hook("stanza", function (stanza) print("Stanza:", stanza) end);
-- This one prints all received data
c:hook("incoming-raw", print, 1000);
-- Print a message after authentication
c:hook("authentication-success", function () print("Logged in!"); end);
c:hook("authentication-failure", function (err) print("Failed to log in! Error: "..tostring(err.condition)); end);
-- Print a message and exit when disconnected
c:hook("disconnected", function () print("Disconnected!"); os.exit(); end);
-- Now, actually start the connection:
c:connect_client(jid, password);
-- Catch the "ready" event to know when the stream is ready to use
c:hook("ready", function ()
print("Stream ready!");
c.version:set{ name = "verse example client" };
c:hook_pep("http://jabber.org/protocol/mood", function (event)
print(event.from.." is "..event.item.tags[1].name);
end);
c:hook_pep("http://jabber.org/protocol/tune", function (event)
print(event.from.." is listening to "..event.item:get_child_text("title"));
end);
c:send(verse.presence());
c:publish_pep(verse.stanza("tune", { xmlns = "http://jabber.org/protocol/tune" })
:tag("title"):text("Beautiful Cedars"):up()
:tag("artist"):text("The Spinners"):up()
:tag("source"):text("Not Quite Folk"):up()
:tag("track"):text("4"):up()
);
end);
print("Starting loop...")
verse.loop()
|
slot0 = class("ItemInfoLayer", import("..base.BaseUI"))
slot1 = 5
slot2 = 11
slot3 = {
RESOLVE = 2,
COMPOSE = 1
}
slot0.getUIName = function (slot0)
return "ItemInfoUI"
end
slot0.init = function (slot0)
pg.UIMgr.GetInstance():BlurPanel(slot0._tf, false, {
weight = slot0:getWeightFromData()
})
slot0.desc = slot0:findTF("window/item/display_panel/desc/Text")
slot0.name = slot0:findTF("window/item/display_panel/name_container/name")
slot0.iconType = slot0:findTF("window/item/display_panel/name_container/shiptype"):GetComponent(typeof(Image))
slot0.count = slot0:findTF("window/item/display_panel/icon_bg/count")
slot0.shipIcon = slot0:findTF("window/item/display_panel/icon_bg/icon/icon")
slot0.okBtn = slot0:findTF("window/actions/ok_button")
slot0.useBtn = slot0:findTF("window/actions/use_button")
slot0.batchUseBtn = slot0:findTF("window/actions/batch_use_button")
slot0.useOneBtn = slot0:findTF("window/actions/use_one_button")
slot0.composeBtn = slot0:findTF("window/actions/compose_button")
slot0.resolveBtn = slot0:findTF("window/actions/resolve_button")
slot0.itemTF = slot0:findTF("window/item")
slot0.stars = slot0.itemTF:Find("icon_bg/stars")
setText(slot0.okBtn:Find("pic"), i18n("msgbox_text_confirm"))
setText(slot0.resolveBtn:Find("pic"), i18n("msgbox_text_analyse"))
SetActive(slot0.batchUseBtn, false)
SetActive(slot0.useBtn, false)
setActive(slot0.okBtn, true)
setActive(slot0.composeBtn, false)
setActive(slot0.resolveBtn, false)
setActive(slot0.useOneBtn, false)
slot0.window = slot0:findTF("window")
slot0.top = slot0:findTF("window/top")
slot0.operatePanel = slot0:findTF("operate")
slot0.countTF = slot0:findTF("operate/item/icon_bg/count"):GetComponent(typeof(Text))
slot0.keepFateTog = slot0:findTF("got/keep_tog", slot0.operatePanel)
setText(slot0:findTF("label", slot0.keepFateTog), i18n("keep_fate_tip"))
slot0.operateBtns = {
Confirm = slot0:findTF("actions/confirm_button", slot0.operatePanel),
Cancel = slot0:findTF("actions/cancel_button", slot0.operatePanel),
Resolve = slot0:findTF("actions/resolve_button", slot0.operatePanel)
}
setText(slot0.operateBtns.Confirm:Find("label"), i18n("msgbox_text_confirm"))
setText(slot0.operateBtns.Cancel:Find("label"), i18n("msgbox_text_cancel"))
setText(slot0.operateBtns.Resolve:Find("label"), i18n("msgbox_text_analyse"))
SetActive(slot0.operatePanel, false)
SetActive(slot0.window, true)
SetActive(slot0.top, true)
slot0.operateMode = nil
slot0.operateBonusList = slot0:findTF("got/panel_bg/list", slot0.operatePanel)
slot0.operateBonusTpl = slot0:findTF("got/panel_bg/item", slot0.operatePanel)
slot0.operateCountdesc = slot0:findTF("count/image_text", slot0.operatePanel)
slot0.operateValue = slot0:findTF("count/number_panel/value", slot0.operatePanel)
slot0.operateLeftButton = slot0:findTF("count/number_panel/left", slot0.operatePanel)
slot0.operateRightButton = slot0:findTF("count/number_panel/right", slot0.operatePanel)
slot0.operateMaxButton = slot0:findTF("count/max", slot0.operatePanel)
end
slot0.setItemInfo = function (slot0, slot1, slot2)
slot3 = slot2:Find("icon_bg/stars")
slot4 = slot2:Find("display_panel/desc/Text")
slot5 = slot2:Find("display_panel/name_container/name")
slot6 = slot2:Find("display_panel/name_container/shiptype"):GetComponent(typeof(Image))
slot7 = slot2:Find("icon_bg/count")
slot8 = slot2:Find("icon_bg/icon/icon")
if slot2:Find("detail") then
if slot1:getConfig("type") == 11 then
onButton(slot0, slot9, function ()
slot0:emit(BaseUI.ON_DROP_LIST, {
item2Row = true,
itemList = _.map(slot1:getConfig("display_icon"), function (slot0)
return {
type = slot0[1],
id = slot0[2]
}
end),
content = slot1.getConfig(slot4, "display")
})
end, SFX_PANEL)
end
setActive(slot9, slot10)
end
setText(slot4, HXSet.hxLan(slot1:getConfig("display")))
setText(slot5, HXSet.hxLan(slot1:getConfig("name")))
SetActive(slot6, false)
if not IsNil(slot8) then
SetActive(slot8, false)
end
setActive(slot7, slot1.count > 0)
setText(slot7, slot1.count)
SetActive(slot3, false)
updateItem(slot2, slot1)
end
slot0.updateItemCount = function (slot0, slot1)
slot0.countTF.text = slot1
end
slot0.setItem = function (slot0, slot1)
slot0.itemVO = slot1
slot0:setItemInfo(slot1, slot0.itemTF)
setActive(slot0.okBtn, false)
setActive(slot0.useBtn, false)
setActive(slot0.batchUseBtn, false)
setActive(slot0.composeBtn, false)
setActive(slot0.resolveBtn, false)
setActive(slot0.useOneBtn, false)
slot2 = true
if slot0.contextData.mine and slot0.itemVO:getTempCfgTable() then
if slot3.compose_number > 0 and slot3.compose_number <= slot0.itemVO.count then
setActive(slot0.composeBtn, true)
slot0:setItemInfo(slot1, slot0:findTF("item", slot0.operatePanel))
slot0.operateMax = slot0.itemVO.count / slot3.compose_number
slot2 = false
end
if slot3.usage == ItemUsage.SOS then
setActive(slot0.useBtn, true)
setText(slot0.useBtn:Find("text"), 1)
slot2 = false
end
slot4 = slot0.itemVO:getConfig("type")
if slot0.itemVO:CanOpen() then
setActive(slot0.useBtn, true)
setText(slot0.useBtn:Find("text"), 1)
if slot0.itemVO.count > 1 then
setActive(slot0.batchUseBtn, true)
setText(slot0.batchUseBtn:Find("text"), math.min(slot0.itemVO.count, 10))
end
slot2 = false
elseif slot4 == Item.BLUEPRINT_TYPE then
slot6 = getProxy(TechnologyProxy).GetBlueprint4Item(slot5, slot0.itemVO.id)
if not LOCK_FRAGMENT_SHOP and slot6 and slot5:getBluePrintById(slot6):isMaxLevel() then
setActive(slot0.resolveBtn, true)
slot0:UpdateBlueprintResolveNum()
end
slot0:setItemInfo(slot1, slot0:findTF("item", slot0.operatePanel))
elseif slot4 == Item.TEC_SPEEDUP_TYPE then
setActive(slot0.resolveBtn, true)
slot0:UpdateSpeedUpResolveNum()
slot0:setItemInfo(slot1, slot0:findTF("item", slot0.operatePanel))
end
end
setActive(slot0.okBtn, slot2)
if slot0.itemVO:isBluePrintType() and slot0.contextData.fromMediatorName == EquipmentMediator.__cname then
setActive(slot0.okBtn, false)
setActive(slot0.useBtn, false)
setActive(slot0.batchUseBtn, false)
setActive(slot0.composeBtn, false)
setActive(slot0.resolveBtn, false)
setActive(slot0.useOneBtn, true)
onButton(slot0, slot0.useOneBtn, function ()
slot0:emit(ItemInfoMediator.ON_BLUEPRINT_SCENE)
end, SFX_PANEL)
end
end
slot0.setShipId = function (slot0, slot1)
slot0.shipId = slot1
SetActive(slot0.iconType, true)
if not IsNil(slot0.shipIcon) then
SetActive(slot0.shipIcon, true)
end
updateShip(slot0.itemTF, slot3)
setText(slot0.desc, pg.ship_data_statistics[slot1].desc or "")
setText(slot0.name, slot2.name)
SetActive(slot0.stars, true)
slot4, slot5, slot6 = ShipWordHelper.GetWordAndCV(slot2.skin_id, ShipWordHelper.WORD_TYPE_DROP)
setText(slot0.desc, slot6 or i18n("ship_drop_desc_default"))
slot7 = slot0.itemTF:Find("icon_bg/startpl")
slot9 = slot3:getStar()
for slot14 = slot0.stars.childCount, slot3:getMaxStar() - 1, 1 do
cloneTplTo(slot7, slot0.stars)
end
slot11 = slot10 - slot9
for slot15 = 0, slot0.stars.childCount - 1, 1 do
slot0.stars:GetChild(slot15).gameObject:SetActive(slot15 < slot10)
SetActive(slot16:Find("star_tpl"), slot11 <= slot15)
SetActive(slot16:Find("star_empty_tpl"), slot15 < slot11)
end
slot0.iconType.sprite = GetSpriteFromAtlas("shiptype", shipType2print(slot3:getShipType()))
setText(slot0.count, "")
end
slot0.doClose = function (slot0)
if slot0.playing then
return
end
slot0:emit(slot0.ON_CLOSE)
end
slot0.didEnter = function (slot0)
if slot0:findTF("OpenBox(Clone)") then
SetActive(slot1, false)
end
onButton(slot0, slot0._tf, function ()
if slot0.playing then
return
end
slot0:emit(slot1.ON_CLOSE)
end, SFX_CANCEL)
onButton(slot0, slot0._tf:Find("window/top/btnBack"), function ()
if slot0.playing then
return
end
slot0:emit(slot1.ON_CLOSE)
end, SFX_CANCEL)
onButton(slot0, slot0.okBtn, function ()
if slot0.playing then
return
end
slot0:emit(slot1.ON_CLOSE)
end, SFX_CONFIRM)
onButton(slot0, slot0.useBtn, function ()
slot0:emit(ItemInfoMediator.USE_ITEM, slot0.itemVO.id, 1)
end, SFX_CONFIRM)
onButton(slot0, slot0.batchUseBtn, function ()
slot0:emit(ItemInfoMediator.USE_ITEM, slot0.itemVO.id, math.min(slot0.itemVO.count, 10))
end, SFX_CONFIRM)
onButton(slot0, slot0.composeBtn, function ()
SetActive(slot0.operatePanel, true)
SetActive(slot0.window, false)
SetActive(slot0.top, false)
SetActive.operateMode = slot0.top.COMPOSE
SetActive:SetOperateCount(1)
end, SFX_CONFIRM)
onButton(slot0, slot0.resolveBtn, function ()
SetActive(slot0.operatePanel, true)
SetActive(slot0.window, false)
SetActive(slot0.top, false)
SetActive.operateMode = slot0.top.RESOLVE
SetActive:SetOperateCount(1)
end, SFX_PANEL)
pressPersistTrigger(slot0.operateLeftButton, 0.5, function (slot0)
if not slot0:UpdateCount(slot0.operateCount - 1) then
slot0()
return
end
slot0:SetOperateCount(slot0.operateCount - 1)
end, nil, true, true, 0.1, SFX_PANEL)
pressPersistTrigger(slot0.operateRightButton, 0.5, function (slot0)
if not slot0:UpdateCount(slot0.operateCount + 1) then
slot0()
return
end
slot0:SetOperateCount(slot0.operateCount + 1)
end, nil, true, true, 0.1, SFX_PANEL)
onButton(slot0, slot0.operateMaxButton, function ()
slot0:SetOperateCount(slot0.operateMax)
end, SFX_PANEL)
onButton(slot0, slot0.operateBtns.Cancel, function ()
SetActive(slot0.operatePanel, false)
SetActive(slot0.window, true)
SetActive(slot0.top, true)
end, SFX_CANCEL)
onButton(slot0, slot0.operateBtns.Confirm, function ()
slot0:emit(ItemInfoMediator.COMPOSE_ITEM, slot0.itemVO.id, slot0.operateCount)
slot0 = slot0.emit.itemVO:getTempCfgTable()
if slot0.itemVO.count - slot0.operateCount * slot0.compose_number < slot0.compose_number then
triggerButton(slot0.operateBtns.Cancel)
else
slot0:SetOperateCount(1)
end
end, SFX_CONFIRM)
onButton(slot0, slot0.operateBtns.Resolve, function ()
slot0:emit(ItemInfoMediator.SELL_BLUEPRINT, slot0.contextData.info.type, slot0.itemVO.id, slot0.operateCount)
if slot0.emit.itemVO.count < 1 then
triggerButton(slot0.operateBtns.Cancel)
else
slot0:SetOperateCount(1)
end
end, SFX_CONFIRM)
slot0.keepFateState = not getProxy(PlayerProxy).getData(slot2).GetCommonFlag(slot2, SHOW_DONT_KEEP_FATE_ITEM)
GetComponent(slot0.keepFateTog, typeof(Toggle)).isOn = slot0.keepFateState
function slot4()
slot0:UpdateBlueprintResolveNum()
slot0.UpdateBlueprintResolveNum:SetOperateCount(1)
end
onToggle(slot0, slot0.keepFateTog, function (slot0)
slot0.keepFateState = slot0
if slot0 then
pg.m02:sendNotification(GAME.CANCEL_COMMON_FLAG, {
flagID = SHOW_DONT_KEEP_FATE_ITEM
})
else
pg.m02:sendNotification(GAME.COMMON_FLAG, {
flagID = SHOW_DONT_KEEP_FATE_ITEM
})
end
slot1()
end)
slot4()
end
slot0.UpdateCount = function (slot0, slot1)
if slot0.operateMode == slot0.COMPOSE then
if not slot0.itemVO:getTempCfgTable().target_id or slot2.target_id <= 0 then
return false
end
return slot0.operateCount ~= math.clamp(slot1, 1, math.floor(slot0.itemVO.count / slot2.compose_number))
elseif slot0.operateMode == slot0.RESOLVE then
return slot0.operateCount ~= math.clamp(slot1, 1, slot0.itemVO.count)
end
end
slot0.SetOperateCount = function (slot0, slot1)
if slot0.operateMode == slot0.COMPOSE then
if not slot0.itemVO:getTempCfgTable().target_id or slot2.target_id <= 0 then
return
end
if slot0.operateCount ~= math.clamp(slot1, 1, math.floor(slot0.itemVO.count / slot2.compose_number)) then
slot0.operateCount = slot1
slot0:UpdateComposeCount()
end
slot0:updateItemCount(slot0.itemVO.count - slot0.operateCount * slot2.compose_number)
elseif slot0.operateMode == slot0.RESOLVE and slot0.operateCount ~= math.clamp(slot1, 0, slot0.operateMax) then
slot0.operateCount = slot1
slot0:UpdateResolvePanel()
slot0:updateItemCount(slot0.itemVO.count - slot0.operateCount)
end
end
slot0.RefreshBonusList = function (slot0, slot1, slot2)
if slot0.operateTemplate ~= slot1 then
removeAllChildren(slot0.operateBonusList)
slot0.operateTemplate = slot1
end
UIItemList.StaticAlign(slot0.operateBonusList, slot0.operateTemplate, slot2)
end
slot0.UpdateComposeCount = function (slot0)
setText(slot0.operateValue, slot1)
table.insert(slot3, {
type = DROP_TYPE_ITEM,
id = slot0.itemVO:getTempCfgTable().target_id,
count = slot0.operateCount
})
slot0:RefreshBonusList(slot0.operateBonusTpl, #{})
for slot7 = 1, #, 1 do
slot8 = slot0.operateBonusList:GetChild(slot7 - 1)
updateDrop(slot8, slot9)
setText(slot8:Find("name"), slot3[slot7].cfg.name)
onButton(slot0, slot8:Find("icon_bg"), function ()
slot0:emit(slot1.ON_DROP, )
end, SFX_PANEL)
end
for slot7, slot8 in pairs(slot0.operateBtns) do
setActive(slot8, slot7 == "Confirm" or slot7 == "Cancel")
end
setText(slot0.operateCountdesc, i18n("compose_amount_prefix"))
setActive(slot0.keepFateTog, false)
end
slot0.UpdateResolvePanel = function (slot0)
setText(slot0.operateValue, slot1)
table.insert(slot3, {
type = DROP_TYPE_RESOURCE,
id = slot0.itemVO:getConfig("price")[1],
count = slot0.itemVO.getConfig("price")[2] * slot0.operateCount
})
slot0:RefreshBonusList(slot0.operateBonusTpl, #{})
for slot7 = 1, #, 1 do
slot8 = slot0.operateBonusList:GetChild(slot7 - 1)
updateDrop(slot8, slot9)
setText(slot8:Find("name"), slot3[slot7].cfg.name)
onButton(slot0, slot8:Find("icon_bg"), function ()
slot0:emit(slot1.ON_DROP, )
end, SFX_PANEL)
end
for slot7, slot8 in pairs(slot0.operateBtns) do
setActive(slot8, slot7 == "Resolve" or slot7 == "Cancel")
end
setText(slot0.operateCountdesc, i18n("resolve_amount_prefix"))
if slot0.itemVO:getConfig("type") == Item.TEC_SPEEDUP_TYPE then
setActive(slot0.keepFateTog, false)
else
setActive(slot0.keepFateTog, true)
end
setButtonEnabled(slot0.operateBtns.Resolve, slot1 > 0)
end
slot0.UpdateBlueprintResolveNum = function (slot0)
slot1 = slot0.itemVO.count
if slot0.itemVO:getConfig("type") == Item.BLUEPRINT_TYPE then
slot3 = getProxy(TechnologyProxy)
slot5 = slot3:getBluePrintById(slot3:GetBlueprint4Item(slot0.itemVO.id))
if slot0.keepFateState and slot0.itemVO.count - slot5:getFateMaxLeftOver() < 0 then
slot1 = 0
end
end
slot0.operateMax = slot1
end
slot0.UpdateSpeedUpResolveNum = function (slot0)
slot1 = slot0.itemVO.count
if slot0.itemVO:getConfig("type") == Item.TEC_SPEEDUP_TYPE then
slot0.operateMax = slot1
end
end
slot0.willExit = function (slot0)
if slot0.leftEventTrigger then
ClearEventTrigger(slot0.leftEventTrigger)
end
if slot0.rightEventTrigger then
ClearEventTrigger(slot0.rightEventTrigger)
end
pg.UIMgr.GetInstance():UnblurPanel(slot0._tf)
end
slot0.PlayOpenBox = function (slot0, slot1, slot2)
if not slot1 or slot1 == "" then
slot2()
return
end
function slot3()
if slot0.playing or not slot0[slot1] then
return
end
slot0.playing = true
slot0[true]:SetActive(true)
SetActive(slot0.window, false)
SetActive(slot0.top, false)
slot0 = tf(slot0[])
slot0:SetParent(slot0._tf, false)
slot0:SetAsLastSibling()
slot1 = slot0:GetComponent("DftAniEvent")
slot1:SetTriggerEvent(function (slot0)
slot0()
end)
slot1.SetEndEvent(slot1, function (slot0)
if slot0[] then
SetActive(slot0[slot1], false)
slot0.playing = false
end
slot0:emit(slot2.ON_CLOSE)
end)
pg.CriMgr.GetInstance().PlaySoundEffect_V3(slot2, SFX_UI_EQUIPMENT_OPEN)
end
if slot0.findTF(slot0, slot1 .. "(Clone)") then
slot0[slot1] = go(slot4)
end
if not slot0[slot1] then
PoolMgr.GetInstance():GetPrefab("ui/" .. string.lower(slot1), "", true, function (slot0)
slot0:SetActive(true)
slot0[] = slot0
slot0()
end)
else
slot3()
end
end
return slot0
|
return{
name = "berry",
}
|
--====================================================================--
-- dmc_buttons.lua
--
-- by David McCuskey
-- Documentation: http://docs.davidmccuskey.com/display/docs/dmc_buttons.lua
--====================================================================--
--[[
Copyright (C) 2011-2013 David McCuskey. All Rights Reserved.
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.
--]]
--====================================================================--
-- DMC Corona Library : DMC Buttons
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.9.0"
--====================================================================--
-- DMC Corona Library Config
--====================================================================--
--====================================================================--
-- Support Functions
local Utils = {} -- make copying from dmc_utils easier
function Utils.extend( fromTable, toTable )
function _extend( fT, tT )
for k,v in pairs( fT ) do
if type( fT[ k ] ) == "table" and
type( tT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], tT[ k ] )
elseif type( fT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], {} )
else
tT[ k ] = v
end
end
return tT
end
return _extend( fromTable, toTable )
end
--====================================================================--
-- Configuration
local dmc_lib_data, dmc_lib_info
-- boot dmc_library with boot script or
-- setup basic defaults if it doesn't exist
--
if false == pcall( function() require( "dmc_corona_boot" ) end ) then
_G.__dmc_corona = {
dmc_corona={},
}
end
dmc_lib_data = _G.__dmc_corona
dmc_lib_info = dmc_lib_data.dmc_library
--====================================================================--
-- DMC Buttons
--====================================================================--
--====================================================================--
-- Configuration
dmc_lib_data.dmc_buttons = dmc_lib_data.dmc_buttons or {}
local DMC_BUTTONS_DEFAULTS = {
debug_active=false,
}
local dmc_states_data = Utils.extend( dmc_lib_data.dmc_buttons, DMC_BUTTONS_DEFAULTS )
--====================================================================--
-- Imports
local Objects = require 'dmc_objects'
local Utils = require 'dmc_utils'
local inheritsFrom = Objects.inheritsFrom
local CoronaBase = Objects.CoronaBase
--====================================================================--
-- Buttons base class
--====================================================================--
local ButtonBase = inheritsFrom( CoronaBase )
ButtonBase.NAME = "Button Base"
ButtonBase._SUPPORTED_VIEWS = nil
ButtonBase._PRINT_INCLUDE = Utils.extend( CoronaBase._PRINT_INCLUDE, { '_img_info', '_img_data', '_callback' } )
ButtonBase._PRINT_EXCLUDE = Utils.extend( CoronaBase._PRINT_EXCLUDE, {} )
ButtonBase.PHASE_PRESS = "press"
ButtonBase.PHASE_RELEASE = "release"
-- create a base image configuration
-- copied into state-specific tables
ButtonBase._BASE_IMAGE_CONFIG = {
source = "",
width = 0,
height = 0,
xOffset = 0,
yOffset = 0,
label = nil,
}
-- create a base label style configuration
-- copied into state-specific tables
ButtonBase._BASE_STYLE_CONFIG = {
font = native.systemFontBold,
size = 17,
color = { 255, 255, 255, 255 },
xOffset = 0,
yOffset = 0,
}
-- =============================
-- Constructor from CoronaBase
-- =============================
function ButtonBase:_init( options )
--print( "in ButtonBase:_init()" )
self:superCall( "_init" )
if self._SUPPORTED_VIEWS == nil then return end
local options = options or {}
-- create properties
self.id = ""
self._img_info = {}
self._img_data = {}
self._callback = {
onPress = nil,
onRelease = nil,
onEvent = nil,
}
-- setup our image info structure
self:_setImageInfo()
end
-- _setImageInfo()
--
-- setup the default parameters for each image state
--
function ButtonBase:_setImageInfo()
local img_list = self._SUPPORTED_VIEWS
local img_info = self._img_info
for i=1, #img_list do
local t = img_list[ i ] -- image string, eg 'active'
img_info[ t ] = Utils.extend( self._BASE_IMAGE_CONFIG, {} )
img_info[ t ].style = Utils.extend( self._BASE_STYLE_CONFIG, {} )
end
end
-- _createView()
--
-- create all of the display items for each image state
--
function ButtonBase:_createView()
if self._SUPPORTED_VIEWS == nil then return end
local img_info, img_data = self._img_info, self._img_data
local group, grp_info, img, label
local img_list = self._SUPPORTED_VIEWS
for i=1, #img_list do
local t = img_list[ i ] -- image string, eg 'active'
-- do Corona stuff
grp_info = img_info[ t ]
group = display.newGroup()
-- save to our object for reference
img_data[ t ] = group
self:insert( group, true )
group:addEventListener( "touch", self )
-- setup image
img = display.newImageRect( grp_info.source,
grp_info.width,
grp_info.height )
if img == nil then
print("\nERROR: image rect source '" .. tostring( grp_info.source ) .. "'\n\n" )
end
group:insert( img )
-- setup label
if ( grp_info.label ) then
label = display.newText( grp_info.label, 0, 0, grp_info.style.font, grp_info.style.size )
label:setTextColor( unpack( grp_info.style.color ) )
group:insert( label )
label:setReferencePoint( display.CenterReferencePoint )
label.x, label.y = grp_info.style.xOffset, grp_info.style.yOffset
end
end
end
function ButtonBase:destroy()
--print( "in ButtonBase:destroy()" )
local img_info, img_data = self._img_info, self._img_data
local img_list = self._SUPPORTED_VIEWS
for i=1, #img_list do
local obj, group
local t = img_list[ i ] -- image string, eg 'active'
Utils.destroy( img_info[ t ] )
img_info[ t ] = nil
-- get rid of image state groups ( display objects )
group = img_data[ t ]
while group.numChildren > 0 do
obj = group[1]
group:remove( obj )
--obj:removeSelf()
end
group:removeEventListener( "touch", self )
self:remove( group )
img_data[ t ] = nil
end
self._img_info = nil
self._img_data = nil
self._callback = nil
-- call after we do our cleanup
CoronaBase.destroy( self )
end
--== PUBLIC METHODS ============================================
-- x()
--
-- overridden from super
--
function ButtonBase.__setters:x( value )
local img_list = self._SUPPORTED_VIEWS
local i
for i=1, #img_list do
local t = img_list[ i ] -- 'active'
local img = self._img_data[ t ]
img.x = value + self._img_info[ t ].xOffset
end
end
-- y()
--
-- overridden from super
--
function ButtonBase.__setters:y( value )
local img_list = self._SUPPORTED_VIEWS
local i
for i=1, #img_list do
local t = img_list[ i ] -- 'active'
local img = self._img_data[ t ]
img.y = value + self._img_info[ t ].yOffset
end
end
--====================================================================--
-- Push Button class
--====================================================================--
local PushButton = inheritsFrom( ButtonBase )
PushButton.NAME = "Push Button"
PushButton._SUPPORTED_VIEWS = { "up", "down" }
function PushButton:_init( options )
--print( "in PushButton:_init()'")
self:superCall( "_init" )
local options = options or {}
local img_info, img_data = self._img_info, self._img_data
-- == define our properties ====================
-- these are display objects
img_data.default = nil
img_data.down = nil
-- setup our image info structure
self:_setImageInfo()
-- == overlay incoming options ====================
-- do top-level options first
if options.id then
self.id = options.id
end
if options.height then
img_info.up.height = options.height
img_info.down.height = options.height
end
if options.width then
img_info.up.width = options.width
img_info.down.width = options.width
end
if options.label then
img_info.up.label = options.label
img_info.down.label = options.label
end
if options.defaultSrc then
img_info.up.source = options.defaultSrc
img_info.down.source = options.defaultSrc
end
if options.upSrc then
img_info.up.source = options.upSrc
end
if options.downSrc then
img_info.down.source = options.downSrc
end
if options.style then
Utils.extend( options.style, img_info.up.style )
Utils.extend( options.style, img_info.down.style )
end
-- now do second-level options
if options.up then
Utils.extend( options.up, img_info.up )
end
if options.down then
Utils.extend( options.down, img_info.down )
end
if options.onPress and type( options.onPress ) == "function" then
self._callback.onPress = options.onPress
end
if options.onRelease and type( options.onRelease ) == "function" then
self._callback.onRelease = options.onRelease
end
if options.onEvent and type( options.onEvent ) == "function" then
self._callback.onEvent = options.onEvent
end
end
function PushButton:_initComplete()
local img_data = self._img_data
img_data.up.isVisible = true
img_data.down.isVisible = false
end
function PushButton:touch( e )
local phase = e.phase
local img_data = self._img_data
local onEvent = self._callback.onEvent
local onPress = self._callback.onPress
local onRelease = self._callback.onRelease
local result = true
local buttonEvent = {}
buttonEvent.target = self
buttonEvent.id = self.id
-- phase "BEGAN"
if phase == "began" then
buttonEvent.phase = ButtonBase.PHASE_PRESS
buttonEvent.name = "touch"
if onPress then
result = onPress( e )
elseif ( onEvent ) then
result = onEvent( buttonEvent )
end
self:dispatchEvent( buttonEvent )
display.getCurrentStage():setFocus( e.target )
self.isFocus = true
img_data.down.isVisible = true
img_data.up.isVisible = false
elseif self.isFocus then
-- check if touch is over the button
local bounds = self.contentBounds
local x,y = e.x,e.y
local isWithinBounds =
bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y
-- phase "MOVED"
if phase == "moved" then
-- show correct image state
img_data.down.isVisible = isWithinBounds
img_data.up.isVisible = not isWithinBounds
-- phase "ENDED"
elseif phase == "ended" or phase == "cancelled" then
if phase == "ended" then
buttonEvent.phase = ButtonBase.PHASE_RELEASE
buttonEvent.name = "touch"
if isWithinBounds then
if onRelease then
result = onRelease( e )
elseif onEvent then
result = onEvent( buttonEvent )
end
self:dispatchEvent( buttonEvent )
end
end
display.getCurrentStage():setFocus( nil )
self.isFocus = false
img_data.down.isVisible = false
img_data.up.isVisible = true
end
end
return result
end
--====================================================================--
-- BinaryButton button class
--====================================================================--
local BinaryButton = inheritsFrom( ButtonBase )
BinaryButton.NAME = "Binary Button"
BinaryButton._SUPPORTED_VIEWS = { 'active', 'inactive' }
BinaryButton.STATE_INACTIVE = "inactive"
BinaryButton.STATE_ACTIVE = "active"
function BinaryButton:new( options )
local o = self:_bless()
o:_init( options )
if options then o:_createView() end
return o
end
function BinaryButton:_init( options )
self:superCall( "_init" )
local options = options or {}
local img_info, img_data = self._img_info, self._img_data
-- == define our properties ====================
self.state = ""
-- these are display objects
img_data.active = nil
img_data.inactive = nil
-- setup our image info structure
self:_setImageInfo()
-- == overlay incoming options ====================
-- do top-level options first
if options.id then
self.id = options.id
end
if options.height then
img_info.active.height = options.height
img_info.inactive.height = options.height
end
if options.width then
img_info.active.width = options.width
img_info.inactive.width = options.width
end
if options.label then
img_info.active.label = options.label
img_info.inactive.label = options.label
end
if options.defaultSrc then
img_info.active.source = options.defaultSrc
img_info.inactive.source = options.defaultSrc
end
if options.inactiveSrc then
img_info.inactive.source = options.inactiveSrc
end
if options.activeSrc then
img_info.active.source = options.activeSrc
end
if options.style then
Utils.extend( options.style, img_info.active.style )
Utils.extend( options.style, img_info.inactive.style )
end
-- now do second-level options
if options.active then
Utils.extend( options.active, img_info.active )
end
if options.inactive then
Utils.extend( options.inactive, img_info.inactive )
end
if options.onPress and type( options.onPress ) == "function" then
self._callback.onPress = options.onPress
end
if options.onRelease and type( options.onRelease ) == "function" then
self._callback.onRelease = options.onRelease
end
if options.onEvent and type( options.onEvent ) == "function" then
self._callback.onEvent = options.onEvent
end
end
function BinaryButton:_initComplete()
local img_data = self._img_data
img_data.active.isVisible = false
img_data.inactive.isVisible = true
self:_setButtonState( BinaryButton.STATE_INACTIVE )
end
function BinaryButton:getNextState()
-- override this
end
function BinaryButton:touch( e )
local phase = e.phase
local onEvent = self._callback.onEvent
local onPress = self._callback.onPress
local onRelease = self._callback.onRelease
local result = true
local buttonEvent = {}
buttonEvent.target = self
buttonEvent.id = self.id
buttonEvent.state = self.state
local current_state = self.state
local other_state = self:getNextState()
-- phase "BEGAN"
if phase == "began" then
buttonEvent.phase = ButtonBase.PHASE_PRESS
buttonEvent.name = "touch"
if onPress then
result = onPress( e )
elseif onEvent then
result = onEvent( buttonEvent )
end
self:dispatchEvent( buttonEvent )
self:_setButtonImage( other_state )
display.getCurrentStage():setFocus( e.target )
self.isFocus = true
elseif self.isFocus then
-- check if touch is over the button
local bounds = self.contentBounds
local x,y = e.x,e.y
local isWithinBounds =
bounds.xMin <= x and bounds.xMax >= x and bounds.yMin <= y and bounds.yMax >= y
-- phase "MOVED"
if phase == "moved" then
--print ("moved")
if isWithinBounds then
self:_setButtonImage( other_state )
else
self:_setButtonImage( current_state )
end
-- phase "ENDED"
elseif phase == "ended" or phase == "cancelled" then
if phase == "ended" then
buttonEvent.phase = ButtonBase.PHASE_RELEASE
buttonEvent.name = "touch"
if isWithinBounds then
local state = BinaryButton.STATE_INACTIVE
if self.state == state then
state = BinaryButton.STATE_ACTIVE
end
self:_setButtonState( state )
buttonEvent.state = self.state
if onRelease then
result = onRelease( e )
elseif onEvent then
result = onEvent( buttonEvent )
end
self:dispatchEvent( buttonEvent )
end
end
display.getCurrentStage():setFocus( nil )
self.isFocus = false
self:_setButtonImage()
end
end
return result
end
function BinaryButton:_setButtonState( value )
-- no need to update if the same state
if self.state == value then return end
-- save the new state
self.state = value
self:_setButtonImage( value )
end
function BinaryButton:_setButtonImage( value )
local value = value or self.state
local img_data = self._img_data
-- change button view to reflect the current state
local showInactive = value == BinaryButton.STATE_INACTIVE
img_data.inactive.isVisible = showInactive
img_data.active.isVisible = not showInactive
end
--====================================================================--
-- Toggle Button class
--====================================================================--
local ToggleButton = inheritsFrom( BinaryButton )
ToggleButton.NAME = "Toggle Button"
-- for use with "down" image state
function ToggleButton:getNextState()
local state = BinaryButton.STATE_INACTIVE
if self.state == state then
state = BinaryButton.STATE_ACTIVE
end
return state
end
--====================================================================--
-- Radio Button class
--====================================================================--
local RadioButton = inheritsFrom( BinaryButton )
RadioButton.NAME = "Radio Button"
-- for use with "down" image state
function RadioButton:getNextState()
return BinaryButton.STATE_ACTIVE
end
--====================================================================--
-- Button Group base class
--====================================================================--
local ButtonGroupBase = inheritsFrom( CoronaBase )
ButtonGroupBase.NAME = "Button Group Base"
ButtonGroupBase._PRINT_INCLUDE = Utils.extend( CoronaBase._PRINT_INCLUDE, { '_group_buttons', '_selected_button' } )
ButtonGroupBase._PRINT_EXCLUDE = Utils.extend( CoronaBase._PRINT_EXCLUDE, {} )
function ButtonGroupBase:new( options )
local o = self:_bless()
o:_init( options )
return o
end
function ButtonGroupBase:_init( options )
self:superCall( "_init" )
-- create properties
self.setFirstActive = nil -- whether first load button is set to state active
self._group_buttons = {} -- table of our buttons to control
self._selected_button = nil -- this is handle to real object, not display
-- overlay incoming options
if options then Utils.extend( options, self ) end
end
function ButtonGroupBase:add( obj, params )
local params = params or {}
-- these are options which can be passed in
local opts = {
setActive = false,
}
-- process incoming options
Utils.extend( params, opts )
-- if this is the first button, make it active
if ( self.setFirstActive and #self._group_buttons == 0 ) or opts.setActive then
self:_setButtonGroupState( ToggleButton.STATE_INACTIVE, opts )
obj:_setButtonState( ToggleButton.STATE_ACTIVE )
self._selected_button = obj
end
-- do corona stuff
self:insert( obj.display )
obj:addEventListener( "touch", self )
-- add to our button array
table.insert( self._group_buttons, obj )
end
function ButtonGroupBase:destroy()
--print ( "in ButtonGroupBase:destroy()")
self._selected_button = nil
-- remove our buttons
while #self._group_buttons > 0 do
local button = table.remove( self._group_buttons, 1 )
button:removeEventListener( "touch", self )
button:destroy()
end
self._group_buttons = nil
-- call after we do our cleanup
CoronaBase.destroy( self )
end
function ButtonGroupBase:_setButtonGroupState( value )
for i=1, table.getn( self._group_buttons ) do
self._group_buttons[ i ]:_setButtonState( value )
end
end
--====================================================================--
-- Radio Group class
--====================================================================--
local RadioGroup = inheritsFrom( ButtonGroupBase )
RadioGroup.NAME = "Radio Group"
function RadioGroup:_init( options )
-- initialize with properties from super class
self:superCall( "_init" )
-- add new properties specific to our class
self.setFirstActive = true -- for first loaded button
-- set our properties with incoming options
if options then Utils.extend( options, self ) end
end
function RadioGroup:touch( e )
local btn = e.target
local button_label = e.id
if e.phase == ButtonBase.PHASE_RELEASE then
local sendEvent = true
if self._selected_button == btn then sendEvent = false end
-- turn all buttons off
self:_setButtonGroupState( ToggleButton.STATE_INACTIVE )
-- save selected button and set it to ON
self._selected_button = btn
btn:_setButtonState( ToggleButton.STATE_ACTIVE )
if sendEvent then
self:dispatchEvent( { name="change", target=btn, label=button_label, state=btn.state } )
end
return true
end
end
--====================================================================--
-- Toggle Group class
--====================================================================--
local ToggleGroup = inheritsFrom( ButtonGroupBase )
ToggleGroup.NAME = "Toggle Group"
function ToggleGroup:_init( options )
-- initialize with properties from above
self:superCall( "_init" )
-- add new properties specific to our class
self.setFirstActive = false -- for first loaded button
-- set our properties with incoming options
if options then Utils.extend( options, self ) end
end
function ToggleGroup:touch( e )
local btn = e.target
local btn_label = e.id
if e.phase == ButtonBase.PHASE_RELEASE then
-- if we have different button and the new state is STATE_ACTIVE
if self._selected_button ~= btn and e.state == ToggleButton.STATE_ACTIVE then
-- turn all buttons off
self:_setButtonGroupState( ToggleButton.STATE_INACTIVE )
-- save button and set it to ON
self._selected_button = btn
btn:_setButtonState( ToggleButton.STATE_ACTIVE )
end
self:dispatchEvent( { name="change", target=btn, label=btn_label, state=btn.state } )
return true
end
end
-- =========================================================
-- Button Factory
-- =========================================================
local Buttons = {}
-- export class instantiations for direct access
Buttons.ButtonBase = ButtonBase
Buttons.PushButton = PushButton
Buttons.BinaryButton = BinaryButton
Buttons.ToggleButton = ToggleButton
Buttons.RadioButton = RadioButton
Buttons.ButtonGroupBase = ButtonGroupBase
Buttons.RadioGroup = RadioGroup
Buttons.ToggleGroup = ToggleGroup
-- Button factory method
function Buttons.create( class_type, options )
local o
if class_type == "push" then
o = PushButton:new( options )
elseif class_type == "radio" then
o = RadioButton:new( options )
elseif class_type == "toggle" then
o = ToggleButton:new( options )
elseif class_type == "radioGroup" then
o = RadioGroup:new( options )
elseif class_type == "toggleGroup" then
o = ToggleGroup:new( options )
else
print ( "ERROR: Button Class Factory - unknown class type: " .. class_type )
end
return o
end
return Buttons
|
Button = script.Parent
Player = Button.Parent.Parent.Parent
admins = "xSoulStealerx"
admin = "Player"
admi = "SorcererBen"
adm = "acb227"
ad = "Scriptaxor"
a = "fresseh"
admina = "cop536"
function clicked()
if Player.Character.Name ~= admins or if Player.Character.Name ~= admin or if Player.Character.Name ~= admi or if Player.Character.Name ~= adm or if Player.Character.Name ~= ad or if Player.Character.Name ~= a or if Player.Character.Name ~= admina then
script.Parent.Parent.stuff.Visible = true
script.Parent.Visible = false
script.Parent.Parent.butta1.Visible = true
script.Parent.Parent.Frame1.Visible = true
script.Parent.Parent.Frame2.Visible = true
end
end
Button.MouseButton1Click:connect(clicked)
|
object_mobile_sd_crewman_04 = object_mobile_shared_sd_crewman_04:new {
}
ObjectTemplates:addTemplate(object_mobile_sd_crewman_04, "object/mobile/sd_crewman_04.iff")
|
mutated_kahmurra = Creature:new {
objectName = "@mob/creature_names:mutated_kahmurra",
socialGroup = "kahmurra",
faction = "",
level = 26,
chanceHit = 0.35,
damageMin = 230,
damageMax = 240,
baseXp = 2637,
baseHAM = 6800,
baseHAMmax = 8300,
armor = 0,
resists = {125,125,10,140,140,140,-1,-1,-1},
meatType = "meat_herbivore",
meatAmount = 50,
hideType = "hide_bristley",
hideAmount = 33,
boneType = "bone_mammal",
boneAmount = 37,
milk = 0,
tamingChance = 0.25,
ferocity = 7,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/mutated_kahmurra.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
controlDeviceTemplate = "object/intangible/pet/murra_hue.iff",
scale = 1.2,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"",""},
{"stunattack",""}
}
}
CreatureTemplates:addCreatureTemplate(mutated_kahmurra, "mutated_kahmurra")
|
require "imgui"
require "util"
require "love"
require "tileloader"
require "board"
-- dumb reminder for editor
-- set makeprg=love\ .
-- autocmd BufWritePost *.lua Make!
local showVars = true
local showStyle = false
local clearColor = {56, 16, 16}
local guiimages = {}
local tilesets = {}
local tokensets = {}
local currenttilesetname
local currenttileset
local currenttokensetname
local currenttokenset
local board
local splitboard
local rightmouseheld = false
local zoomlevel = 1.0 -- image pixels per screen pixel
local pixel_offset_x = 0
local pixel_offset_y = 0
local tileres = 64
local resolution = {}
local states = {
"init",
"connect (server)",
"connect (client)",
"determine first player",
"choose board layout",
"place pieces",
"your turn",
"opponent turn",
"game end"
} --not sure where this is going, we'll see how I feel about it tomorrow
local currentstate = states[1]
--
-- LOVE callbacks
--
function love.load(arg)
guiimages = loadGui()
tilesets = loadTiles()
tokensets = loadTokens()
currenttilesetname = "rpg"
currenttileset = tilesets.rpg
currenttokensetname = "simple"
currenttokenset = tokensets.simple
--this isn't where this is going to end up but until I decide how I'm handling states...
splitboard = createBoard()
board = combineSegments(splitboard)
end
function love.update(dt)
imgui.NewFrame()
end
function love.draw()
local status
local win_w, win_h = love.graphics.getWidth(), love.graphics.getHeight()
-- draw tile frame where mouse is
local m_x, m_y = love.mouse.getPosition()
--determine which tile mouse is on
local mouseoverx, mouseovery = pixelToGrid(m_x, m_y, true)
local quadx, quady = pixelToQuadXY(m_x, m_y)
-- Menu
if imgui.BeginMainMenuBar() then
if imgui.BeginMenu("File") then
if imgui.MenuItem("Toggle Fullscreen") then
if love.window.getFullscreen() then
love.window.setFullscreen(false)
-- restore old size
love.window.setMode(resolution.x, resolution.y, resolution.flags)
else
-- save size
resolution.x, resolution.y, resolution.flags = love.window.getMode()
love.window.setFullscreen(true, "desktop")
end
elseif imgui.MenuItem("Quit") then
love.event.quit()
end
imgui.EndMenu()
end
if imgui.BeginMenu("Help") then
-- show help
imgui.MenuItem("todo")
imgui.EndMenu()
end
if imgui.BeginMenu("Tileset") then
for tilesetname, tilesettiles in pairs(tilesets) do
if imgui.MenuItem(tilesetname) then
currenttilesetname = tilesetname
currenttileset = tilesettiles
end
end
imgui.EndMenu()
end
if imgui.BeginMenu("Tokenset") then
for tokensetname, tokensetsprites in pairs(tokensets) do
if imgui.MenuItem(tokensetname) then
currenttokensetname = tokensetname
currenttokenset = tokensetsprites
end
end
imgui.EndMenu()
end
if imgui.BeginMenu("Debug") then
if imgui.MenuItem("Variables") then
showVars = not showVars
elseif imgui.MenuItem("Style") then
showStyle = not showStyle
end
imgui.EndMenu()
end
imgui.EndMainMenuBar()
end
-- Debug window
if showVars then
imgui.Begin("Debug", false, {"AlwaysAutoResize"})
imgui.Text("Variables:"..
"\n currentstate = "..currentstate..
"\n currenttileset = "..currenttilesetname..
"\n currenttokenset = "..currenttokensetname..
"\n rightmouseheld = "..tostring(rightmouseheld)..
"\n zoomlevel = "..zoomlevel..
"\n pixel_offset_x, pixel_offset_y = "..pixel_offset_x..", ".. pixel_offset_y..
"\n tileres = "..tileres..
"\n center tile: "..(win_w/2 - pixel_offset_x)/(zoomlevel * tileres)..", "..(win_h/2 - pixel_offset_y)/(zoomlevel * tileres)..
"\n mouseover tile: "..mouseoverx..", "..mouseovery
)
imgui.End()
end
if showStyle then
imgui.Begin("Style Editor", false, {"AlwaysAutoResize"})
imgui.ShowStyleEditor()
imgui.End()
end
love.graphics.clear(clearColor[1], clearColor[2], clearColor[3], 255)
-- draw board
for board_y in range(#board) do
for board_x in range(#board[board_y]) do
-- love.graphics.draw( drawable, x, y, r, sx, sy, ox, oy, kx, ky )
love.graphics.draw(
currenttileset[board[board_y][board_x]],
(board_x - 1) * tileres * zoomlevel + pixel_offset_x,
(board_y - 1) * tileres * zoomlevel + pixel_offset_y,
0,
zoomlevel, zoomlevel
)
end
end
-- mouse tile selection frame
love.graphics.draw(
guiimages.frame,
mouseoverx * tileres * zoomlevel + pixel_offset_x,
mouseovery * tileres * zoomlevel + pixel_offset_y,
0,
zoomlevel, zoomlevel
)
-- mouse quadrant selection frame
-- love.graphics.draw(
-- guiimages.frame,
-- quadx * 12 * tileres * zoomlevel + pixel_offset_x,
-- quady * 12 * tileres * zoomlevel + pixel_offset_y,
-- 0,
-- zoomlevel * 12, zoomlevel * 12
-- )
imgui.Render()
end
function love.quit()
imgui.ShutDown()
end
--
-- User inputs
--
function love.textinput(t)
imgui.TextInput(t)
if not imgui.GetWantCaptureKeyboard() then
-- Pass event to the game
end
end
function love.keypressed(key)
imgui.KeyPressed(key)
if not imgui.GetWantCaptureKeyboard() then
-- Pass event to the game
end
end
function love.keyreleased(key)
imgui.KeyReleased(key)
if not imgui.GetWantCaptureKeyboard() then
-- Pass event to the game
end
end
function love.mousemoved(x, y, dx, dy)
imgui.MouseMoved(x, y)
if not imgui.GetWantCaptureMouse() then
-- Pass event to the game
if rightmouseheld then
pixel_offset_x = pixel_offset_x + dx
pixel_offset_y = pixel_offset_y + dy
end
end
end
function love.mousepressed(x, y, button)
imgui.MousePressed(button)
if not imgui.GetWantCaptureMouse() then
-- Pass event to the game
if button == 2 then
rightmouseheld = true
end
end
end
function love.mousereleased(x, y, button)
imgui.MouseReleased(button)
if not imgui.GetWantCaptureMouse() then
-- Pass event to the game
if button == 2 then
rightmouseheld = false
elseif button == 1 then
clickOnQuad(pixelToQuadXY(x, y))
end
end
end
--
-- oh god this is terrible
--
local lastQuadClicked = nil
function clickOnQuad(quadx, quady)
if (quadx == 0 or quadx == 1) and (quady == 0 or quady == 1) then
local quadnum = quadx == 0 and (quady == 0 and 1 or 3) or (quady == 0 and 2 or 4)
-- print("quad "..quadx..", "..quady.." ("..quadnum..") clicked\n")
if lastQuadClicked == nil then
lastQuadClicked = quadnum
elseif lastQuadClicked == quadnum then
splitboard = rotateSegment(splitboard, quadnum)
board = combineSegments(splitboard)
lastQuadClicked = nil
else
splitboard = swapSegments(splitboard, lastQuadClicked, quadnum)
board = combineSegments(splitboard)
lastQuadClicked = nil
end
end
end
--
-- i'm sorry
--
function love.wheelmoved(x, y)
imgui.WheelMoved(y)
if not imgui.GetWantCaptureMouse() then
-- Pass event to the game
local win_w, win_h = love.graphics.getWidth(), love.graphics.getHeight()
-- centered tile: [win_w/2 - off_x , win_h/2 - off_y] / (zoomold * tileres)
local tilecenter_x, tilecenter_y = pixelToGrid(win_w/2, win_h/2, false)
if y > 0 then
zoomlevel = zoomlevel * 0.9
if zoomlevel < 0.25 then
zoomlevel = 0.25
end
elseif y < 0 then
zoomlevel = zoomlevel * 1.1
if zoomlevel > 5 then
zoomlevel = 5
end
end
-- work it backwards for off_x and off_y
pixel_offset_x = win_w/2 - tilecenter_x * zoomlevel * tileres
pixel_offset_y = win_h/2 - tilecenter_y * zoomlevel * tileres
end
end
--
-- Utility stuff
--
function pixelToGrid(px_x, px_y, floorit)
local grid_x = (px_x - pixel_offset_x)/(zoomlevel * tileres)
local grid_y = (px_y - pixel_offset_y)/(zoomlevel * tileres)
if floorit then
grid_x = math.floor(grid_x)
grid_y = math.floor(grid_y)
end
return grid_x, grid_y
end
function pixelToQuadXY(px_x, px_y)
local grid_x, grid_y = pixelToGrid(px_x, px_y, true)
return math.floor(grid_x / 12), math.floor(grid_y / 12)
end
|
-- keysetup format for each key:
-- {event_register,event_number,{args...},{actions...}}
-- args -> hash map
-- actions -> array -> hash-map (key "action" always set to action name and key "key" always set to the name of the key to press)
-- remember arrays are 1 based not 0 based in lua
keysetup = {{"G_PRESSED",4,{},{{action="toggle_key",key="f"},{action="tap_key",key="x",count=3,duration=30,delay=20}}},{"TIMED",5,{time=1500,event_prefix="G"},{{{action="toggle_key",key="a"}},{{action="toggle_key",key="b"}}}}};
logging = true;
-- do not change the code below
OutputLogMessage("Script initialized\nWritten by: Douile\nhttps://github.com/Douile/logitech-toggle-keys/\n");
for i,v in pairs(keysetup) do
OutputLogMessage("%s:%d registered...\n",v[1],v[2]);
end
OutputLogMessage("\n- start runtime log -\n");
keyspressed = {};
keytimes = {};
function update_key(key,state)
if (state == true) then
PressKey(key);
keyspressed[key] = true;
word = "Pressed";
else
ReleaseKey(key);
keyspressed[key] = nil;
word = "Released"
end
if (logging == true) then
OutputLogMessage("+%d - %s %s\n",GetRunningTime(),word,key);
end
end
function handle_custom_events(setup_info,event,arg)
-- handle custom listeners such as G keys held
if (setup_info[1] == "TIMED") then
prefix = setup_info[3]["event_prefix"];
if (event == prefix.."_PRESSED" and setup_info[2] == arg) then
id = string.format("%s_%d",prefix,arg);
keytimes[id] = GetRunningTime();
if (logging == true) then
OutputLogMessage("+%d - Starting holding %s\n",GetRunningTime(),id);
end
elseif (event == prefix.."_RELEASED" and setup_info[2] == arg) then
id = string.format("%s_%d",prefix,arg);
time_held = GetRunningTime()-keytimes[id];
keytimes[id] = nil;
-- possibly add support for multiple time ranges of time held
if (time_held < setup_info[3]["time"]) then
dispatch_actions(setup_info[3],setup_info[4][1]);
else
dispatch_actions(setup_info[3],setup_info[4][2]);
end
end
return true;
end
return false;
end
function dispatch_actions(args,actions)
for i,action in pairs(actions) do
v = action["action"];
key = action["key"];
if (v == "toggle_key") then
if (keyspressed[key] == true) then
update_key(key,false);
else
update_key(key,true);
end
elseif (v == "press_key") then
update_key(key,true);
elseif (v == "release_key") then
update_key(key,false);
elseif (v == "tap_key") then
for n=0,action["count"],1 do
PressKey(key);
Sleep(action["duration"]);
ReleaseKey(key);
Sleep(action["delay"]);
end
end
end
end
function OnEvent(event, arg)
for i,v in pairs(keysetup) do
did_custom = handle_custom_events(v,event,arg);
if (did_custom == false) then -- (not did_custom)
if (event == v[1] and arg == v[2]) then
dispatch_actions(v[3],v[4]);
end
end
end
end
|
local import, _modules
do
local cache = {}
local nils = {}
function import(modname)
if nils[modname] then return end
local cached = cache[modname]
if cached ~= nil then return cached end
cached = _modules[modname]
if cached ~= nil then
cached = cached();
if cached == nil then
nils[modname] = true
else
cache[modname] = cached
end
return cached
end
end
end
_modules = {
|
--[[Copyright PrinceTommen - Script developed for CyanideEpic (twitch.tv/cyanideepic)]]--
--[[You are all allowed to use it as long as you don't pretend it's yours]]--
--[[Have fun !]]--
version =" 3.5"
--[[
Release Note:
3.5: Added: Multiple item slots system, including the items to throw (suggested by Portsanta and CyanideEpic)
Major interface enhancements to make the configuration faster in spite of the new options
Enhanced item shortage security, supporting the multiple slots
New functions to manage I/O in a more compact way (suggested by Niseg)
3.41: Fixed: Important glitch when the turtle returned to its starting position with a certain configuration
Displaying issues
3.4: Added: Favorite configuration system
Ability to choose the direction of the series of parallel tunnels (right or left)
Support of execution without torches or chests (will not try to place them)
Security that stops the turtle when it runs out of chests or torches (suggested by CyanideEpic)
Chests and torches status updated automatically
Security that requires the user to press enter before the turtle starts (suggested by CyanideEpic)
The turtle now returns to its starting position after it finishes
New rotation function as well a a specific torch placing function
Fixed: The turtle will now properly finish the hub after mining an odd number of tunnels
The torch placement has been modified to avoid conflicts with chests
3.3: Added: Enderchest Support (suggested by Niseg and Daniteh)
Release note
3.2: Fixed: Very important chest placing issue (only appeared in 3.1)
3.1: Added: New mining pattern for more efficiency (suggested by Niseg)
Smarter fuel management: Will now consume the "stored" fuel before refueling
Can now consume any type of fuel supported by turtles (check the wiki)
Fuel type can be changed while the turtle is mining
Optimized the mining of 3 blocks high tunnels
Better interface, instructions remain visible and a line is dedicated to the fuel status (updated automatically)
Option to throw cobblestone automatically (suggested by Niseg)
Fixed: Refueling issue in certain circumstances (reported by CyanideEpic)
]]--
function resetScreen()
term.clear()
term.setCursorPos(14,1)
write("Mining Turtle")
term.setCursorPos(5,2)
write("For CyanideEpic and his friends")
term.setCursorPos(1,13)
write("By PrinceTommen, version "..version)
term.setCursorPos(1,4)
end
function textOutput(output_message, x_screen_pos, z_screen_pos, clear_area)
term.setCursorPos(x_screen_pos,z_screen_pos)
if clear_area == 0 then
clear_area = string.len(output_message)
end
write(output_message..string.rep(" ", (clear_area - string.len(output_message))))
end
function securedInput(x_screen_pos, z_screen_pos, nature, lower_value, upper_value, example1, example2)
example = {example1, example2}
local function shortExample(example_int, example, boolStringPart)
tableShortExample = {}
tableShortExample[example_int] = example[example_int].." ("..string.sub(string.lower(example[example_int]), 1, 1)..") "
if boolStringPart then
return string.sub(string.lower(example[example_int]), 1, 1)
else
return tableShortExample[example_int]
end
end
incipit = shortExample(1, example, false).."/ "..shortExample(2, example, false)..": "
if nature == "text" then
repeat
textOutput(incipit, x_screen_pos, z_screen_pos, 39)
term.setCursorPos(string.len(incipit)+1,z_screen_pos)
user_input = string.sub(string.lower(read()), 1, 1)
until (user_input == shortExample(1, example, true) or user_input == shortExample(2, example, true))
elseif nature == "integer" then
repeat
textOutput(" ", x_screen_pos, z_screen_pos, (39 - x_screen_pos))
term.setCursorPos(x_screen_pos,z_screen_pos)
user_input = tonumber(read())
until (user_input >= lower_value and user_input <= upper_value)
end
return user_input
end
function clearLines(firstLine, lastLine)
a = 1
for a=1, (lastLine-firstLine+1) do
textOutput("", 1, (firstLine+a-1), 40)
end
end
function convertToBool(var, boolTrue)
if var == boolTrue then
var = true
else
var = false
end
return var
end
function turn(FacingAngle, Bool_rotation, Rotation_integer)
if Bool_rotation then
for u=1, Rotation_integer do
turtle.turnRight()
end
FacingAngle = FacingAngle + Rotation_integer
else
for u=1, Rotation_integer do
turtle.turnLeft()
end
FacingAngle = FacingAngle - Rotation_integer
end
FacingAngle = math.abs((FacingAngle - 1)%4+1)
return FacingAngle
end
local function refuel()
turtle.select(torches_slots+current_slot[2])
while not(turtle.refuel(1)) do
for f=1, fuel_slots do
current_slot[2], shortage[2] = rotateSlot(2, torches_slots+1, fuel_slots)
turtle.select(torches_slots+current_slot[2])
if turtle.refuel(1) then
boolRefuel = true
break
else
boolRefuel = false
end
end
if not(boolRefuel) then
textOutput("No Fuel -", 1, 11, 0)
current_slot[2], shortage[2] = manageShortage(2, torches_slots+1, torches_slots+fuel_slots)
end
end
refuel_count = 80 - turtle.getFuelLevel()
textOutput("Fuel OK -", 1, 11, 0)
return refuel_count
end
function moveForward(FacingAngle, Boolfb, moving_integer, digUpBool, digDownBool, refuel_count)
local moving_count = 1
for moving_count=1,moving_integer do
if (refuel_count == 80) then
refuel_count = refuel()
end
Bool1 = false
while not(Bool1) do
if (Boolfb) then
turtle.dig()
Bool1 = turtle.forward()
if (digUpBool) then
turtle.digUp()
end
if (digDownBool) then
turtle.digDown()
end
else
Bool1 = turtle.back()
if not(Bool1) then
turn(FacingAngle, true, 2)
turtle.dig()
turn(FacingAngle, false, 2)
end
end
end
moving_count = moving_count + 1
refuel_count = refuel_count + 1
end
return refuel_count
end
function moveUp(Boolud, moving_integer, refuel_count, Bool_DigFront)
local moving_count = 1
for moving_count=1, moving_integer do
if (refuel_count == 80) then
refuel_count = refuel()
end
Bool2 = false
if Bool_DigFront then
turtle.dig()
end
while not(Bool2) do
if (Boolud) then
turtle.digUp()
Bool2 = turtle.up()
else
turtle.digDown()
Bool2 = turtle.down()
end
end
moving_count = moving_count + 1
refuel_count = refuel_count + 1
end
return refuel_count
end
function manageShortage(managedItem, initial_item_slot, final_item_slot)
textOutput("The turtle has used all the "..(itemNames[managedItem+3]).." intitially given. Have you refilled all the "..(itemNames[managedItem+3]).." slots ?", 1, 4, 0)
textOutput("Press enter if all the "..(itemNames[managedItem+3]).." slots are refilled (slots "..(initial_item_slot).." to "..(final_item_slot)..").", 1, 7, 0)
repeat
turn(FacingAngle, true, 4)
os.startTimer(1)
press, key = os.pullEvent()
until (key == 28)
clearLines(4,10)
current_slot[managedItem] = 1
shortage[managedItem] = false
return current_slot[managedItem], shortage[managedItem]
end
function rotateSlot(managedItem, control_slot, rotation_controler)
if (turtle.getItemCount(control_slot) == 0) or (managedItem == 2) then
if current_slot[managedItem]==rotation_controler and (managedItem ~= 2) then
shortage[managedItem] = true
else
current_slot[managedItem]=((current_slot[managedItem])%rotation_controler)+1
end
end
return current_slot[managedItem], shortage[managedItem]
end
function inventoryManagement(refuel_count,Right_or_Left,throw_cobble)
function fullInventory(n)
n = m + 1
repeat
item_count = turtle.getItemCount(n)
if (item_count ~= 0) then
boolSlotOccupied = true
n = n + 1
else
boolSlotOccupied = false
end
until (boolSlotOccupied == false) or (n == 17)
return n
end
if Chest_approval then
m = torches_slots + chests_slots + fuel_slots + garbage_slots
thrown_slots = 0
if (turtle.getItemCount(16) ~= 0) and (m~=16) then
if fullInventory(m)==17 then
if throw_stuff then
for k=1, garbage_slots do
for j=1, (16-m) do
turtle.select(m - garbage_slots + k)
Bool_match_stuff = turtle.compareTo(m+j)
if Bool_match_stuff then
thrown_slots = thrown_slots + 1
turtle.select(m+j)
turtle.drop()
end
end
turtle.select(m - garbage_slots + k)
turtle.drop(turtle.getItemCount(m - garbage_slots + k)-1)
end
for z = (m+1), 16 do
for u = (z+1), 16 do
if turtle.getItemCount(u)~=0 then
turtle.select(u)
turtle.transferTo(z)
end
end
end
end
if not(throw_stuff) or ((thrown_slots <= 2) and (fullInventory(n)>15)) then
if shortage[3] then
textOutput("No Chests", 24, 11, 0)
current_slot[3], shortage[3] = manageShortage(3, torches_slots+fuel_slots+1, torches_slots+fuel_slots+chests_slots)
end
textOutput("Chests OK", 24, 11, 0)
if (Right_or_Left == "left") then
FacingAngle = turn(FacingAngle, true, 1)
else
FacingAngle = turn(FacingAngle, false, 1)
end
refuel_count = moveForward(FacingAngle, true, 1, false, true, refuel_count)
turtle.select(torches_slots+fuel_slots+current_slot[3])
turtle.digDown()
turtle.placeDown()
for u=(m+1),16 do
if turtle.getItemCount(u)~=0 then
turtle.select(u)
turtle.dropDown()
end
end
if enderchest then
turtle.select(torches_slots+fuel_slots+1)
turtle.drop()
turtle.digDown()
end
current_slot[3], shortage[3] = rotateSlot(3, torches_slots+fuel_slots+current_slot[3], chests_slots)
refuel_count = moveForward(FacingAngle, false, 1, false, false, refuel_count)
if (Right_or_Left == "left") then
FacingAngle = turn(FacingAngle, false, 1)
else
FacingAngle = turn(FacingAngle, true, 1)
end
end
end
end
end
turtle.select(1)
return refuel_count
end
function placeTorch(Position)
if Torch_approval then
if shortage[1] then
textOutput("No Torches -", 11, 11, 0)
current_slot[1], shortage[1] = manageShortage(1, 1, torches_slots)
end
textOutput("Torches OK -", 11, 11, 0)
turtle.select(current_slot[1])
if Position == "front" then
turtle.dig()
turtle.place()
elseif Position == "below" then
turtle.digDown()
turtle.placeDown()
elseif Position == "up" then
turtle.digUp()
turtle.placeUp()
end
current_slot[1], shortage[1] = rotateSlot(1, current_slot[1], torches_slots)
end
end
function digVerticalLayer(refuel_count, FacingAngle, Width, Height, Height_Position, Bool_Torches, Right_or_Left)
if Right_or_Left then
Right_or_Left = "left"
else
Right_or_Left = "right"
end
done_columns = 0
if (Height_Position == "up") then
for columns=1, math.floor(Width/4) do
turtle.digUp()
if (Height > 3) then
refuel_count = moveUp(true, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(false, (Height-2), refuel_count, true)
turtle.digDown()
end
refuel_count = moveForward(FacingAngle, true, 2, true, true, refuel_count)
refuel_count = inventoryManagement(refuel_count, Right_or_Left, throw_cobble)
if (Height > 3) then
refuel_count = moveUp(false, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(true, (Height-2), refuel_count, true)
turtle.digUp()
end
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
done_columns = done_columns + 1
if (Width - 4*done_columns ~= 0) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
end
end
if ((Width - 4*math.floor(Width/4)) == 0) then
Height_Position = "up"
elseif ((Width - 4*math.floor(Width/4)) == 1) then
turtle.digUp()
refuel_count = moveUp(false, (Height-3), refuel_count, false)
turtle.digDown()
refuel_count = inventoryManagement(refuel_count, Right_or_Left, throw_cobble)
Height_Position = "down"
elseif ((Width - 4*math.floor(Width/4)) >= 2) then
if (Height > 3) then
refuel_count = moveUp(true, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(false, (Height-2), refuel_count, true)
turtle.digDown()
end
turtle.digUp()
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
refuel_count = inventoryManagement(refuel_count, Right_or_Left, throw_cobble)
Height_Position = "down"
if ((Width - 4*math.floor(Width/4)) == 3) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
refuel_count = moveUp(true, (Height - 3), refuel_count, false)
turtle.digUp()
Height_Position = "up"
end
end
elseif (Height_Position == "down") then
for columns=1, math.floor(Width/4) do
turtle.digDown()
if (Height > 3) then
refuel_count = moveUp(false, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(true, (Height - 2), refuel_count, true)
turtle.digUp()
end
refuel_count = moveForward(FacingAngle, true, 2, true, true, refuel_count)
if (Height > 3) then
refuel_count = moveUp(true, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(false, (Height - 2), refuel_count, true)
turtle.digDown()
end
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
done_columns = done_columns + 1
if (Width - 4*done_columns ~= 0) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
end
refuel_count = inventoryManagement(refuel_count, Right_or_Left, throw_cobble)
if (done_columns%2 == 0) and Bool_Torches then
FacingAngle = turn(FacingAngle,true , 1)
placeTorch("front")
FacingAngle = turn(FacingAngle, false, 1)
end
end
if ((Width - 4*math.floor(Width/4)) == 0) then
Height_Position = "down"
elseif ((Width - 4*math.floor(Width/4)) == 1) then
turtle.digDown()
refuel_count = moveUp(true, (Height - 3), refuel_count, false)
turtle.digUp()
Height_Position = "up"
elseif ((Width - 4*math.floor(Width/4)) >= 2) then
if (Height > 3) then
refuel_count = moveUp(false, 1, refuel_count, false)
turtle.dig()
refuel_count = moveUp(true, (Height - 2), refuel_count, true)
turtle.digUp()
end
turtle.digDown()
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
Height_Position = "up"
if ((Width - 4*math.floor(Width/4)) == 3) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
refuel_count = moveUp(false, (Height - 3), refuel_count, false)
turtle.digDown()
refuel_count = inventoryManagement(refuel_count, Right_or_Left, throw_cobble)
Height_Position = "down"
end
end
end
return refuel_count, Height_Position
end
enderchest, throw_stuff, Chest_approval, Torch_approval, Chest_mismatch, Torch_mismatch = false, false, false, false, false, false
shortage, itemNames = {false, false, false}, {"torch", "fuel", "chest", "torches", "fuel", "chests"}
resetScreen()
if (io.open("favorite", "r") ~= nil) then
resetScreen()
textOutput("Do you wish to use your favorite configuration ?", 1, 4, 0)
Favorite_approval = securedInput(1, 6, "text", 0, 0, "Yes", "No")
if (Favorite_approval == "y") then
handle = fs.open("favorite", "r")
input = handle.readAll()
handle.close()
favorite = textutils.unserialize(input)
tunnels_integer = favorite.tunnels_integer
Width = favorite.Width
Height = favorite.Height
Length = favorite.Length
tunnels_separation = favorite.tunnels_separation
throw_stuff = favorite.throw_stuff
enderchest = favorite.enderchest
Torch_approval = favorite.Torch_approval
Chest_approval = favorite.Chest_approval
end
end
if (io.open("favorite", "r") == nil) or ((io.open("favorite", "r") ~= nil) and (Favorite_approval == "n")) then
resetScreen()
textOutput("Number of parallel tunnels ? ", 1, 4, 0)
tunnels_integer = securedInput(37, 4, "integer", 1, 1000, " ", " ")
textOutput("Width of the tunnels ? ", 1, 5, 0)
Width = securedInput(37, 5, "integer", 1, 1000, " ", " ")
term.setCursorPos(1,6)
textOutput("Height of the tunnels ? ", 1, 6, 0)
Height = securedInput(37, 6, "integer", 1, 200, " ", " ")
if (Height < 3) then
Height = 3
end
term.setCursorPos(1,7)
textOutput("Length of the tunnels ? ", 1, 7, 0)
Length = securedInput(37, 7, "integer", 1, 100000, " ", " ")
if (tunnels_integer > 1) then
term.setCursorPos(1,8)
textOutput("Separating blocks between tunnels ? ", 1, 8, 0)
tunnels_separation = securedInput(37, 8, "integer", 1, 1000, " ", " ")
else
tunnels_separation = 0
end
resetScreen()
textOutput("To use regular chests, press c", 1, 4, 0)
textOutput("To use an enderchest, press e", 1, 5, 0)
textOutput("To use torches, press t", 1, 6, 0)
textOutput("To throw away specific items, press p", 1, 7, 0)
textOutput("Press enter once you have chosen all the options you wanted to activate.", 1, 11, 0)
while true do
press, key = os.pullEvent()
if press == "key" and key == 28 then
break
elseif key == 46 then
if Chest_approval then
Chest_approval = false
textOutput("", 10, 9, 11)
else
Chest_approval = true
textOutput("Chests,", 10, 9, 11)
end
elseif key == 18 then
if enderchest then
enderchest = not(enderchest)
textOutput("", 10, 9, 11)
else
Chest_approval = true
enderchest = true
textOutput("Enderchest,", 10, 9, 11)
end
elseif key == 20 then
if Torch_approval then
Torch_approval = false
textOutput("", 1, 9, 8)
else
Torch_approval = true
textOutput("Torches,", 1, 9, 8)
end
elseif key == 25 then
if throw_stuff then
throw_stuff = not(throw_stuff)
textOutput("", 22, 9, 12)
else
throw_stuff = true
textOutput("Throw items.", 22, 9, 12)
end
end
end
resetScreen()
textOutput("Do you want to save this configuration as your favorite ?", 1, 4, 0)
New_favorite = securedInput(1, 6, "text", 0, 0, "Yes", "No")
if (New_favorite == "y") then
favorite = {}
favorite.tunnels_integer = tunnels_integer
favorite.Width = Width
favorite.Height = Height
favorite.Length = Length
favorite.tunnels_separation = tunnels_separation
favorite.Torch_approval = Torch_approval
favorite.Chest_approval = Chest_approval
favorite.throw_stuff = throw_stuff
favorite.enderchest = enderchest
output = textutils.serialize(favorite)
handle = fs.open("favorite", "w")
handle.write(output)
handle.close()
end
end
resetScreen()
textOutput("To manage extra slots, press s", 1, 4, 0)
textOutput("This option allows you to have several torches/fuel/chests slots, as well as different items to throw", 1, 6, 0)
textOutput("Else, press enter to skip this step.", 1, 10, 0)
torches_slots, chests_slots, garbage_slots = 0, 0, 0
while true do
press, key = os.pullEvent()
if press == "key" and key == 28 then
fuel_slots = 1
break
elseif key == 31 then
repeat
turtle.select(1)
resetScreen()
textOutput("Number of fuel slots ? ", 1, 4, 0)
fuel_slots = securedInput(29, 4, "integer", 1, 16, " ", " ")
slot_total = fuel_slots
if Torch_approval then
textOutput("Number of torches slots ? ", 1, 5, 0)
torches_slots = securedInput(29, 5, "integer", 1, 16, " ", " ")
slot_total = slot_total + torches_slots
end
if Chest_approval and not(enderchest) then
textOutput("Number of chests slots ? ", 1, 6, 0)
chests_slots = securedInput(29, 6, "integer", 1, 16, " ", " ")
slot_total = slot_total + chests_slots
end
if throw_stuff then
textOutput("Number of undesired items ? ", 1, 7, 0)
garbage_slots = securedInput(29, 7, "integer", 1, 16, " ", " ")
slot_total = slot_total + garbage_slots
end
until (slot_total < 16)
break
end
end
resetScreen()
if (tunnels_integer > 1) then
textOutput("The first tunnel will be in front of the turtle. Do you want the tunnels to be dug on the right or on the left of the first tunnel (They will be parallel to the first one) ?", 1, 4, 0)
Bool_direction = securedInput(1, 9, "text", 0, 0, "Right", "Left")
end
if (tunnels_integer == 1) and (Width > 1) then
textOutput("In front of the turtle will be one side of the tunnel. Do you want it to mine the rest on the left or on the right ?", 1, 4, 0)
Bool_direction = securedInput(1, 9, "text", 0, 0, "Right", "Left")
end
resetScreen()
if Torch_approval then
if torches_slots > 1 then
textOutput("Torches in the slots 1 to "..torches_slots, 1, 4, 0)
else
torches_slots = 1
textOutput("Torches in the slot 1", 1, 4, 0)
end
end
if fuel_slots > 1 then
textOutput("Fuel in the slots "..(torches_slots+1).." to "..(torches_slots+fuel_slots), 1, 5, 0)
else
fuel_slots = 1
textOutput("Fuel in the slot "..(torches_slots+1), 1, 5, 0)
end
if Chest_approval and not(enderchest) then
if chests_slots > 1 then
textOutput("Chests in the slots "..(torches_slots+fuel_slots+1).." to "..(torches_slots+fuel_slots+chests_slots), 1, 6, 0)
else
chests_slots = 1
textOutput("Chests in the slot "..(torches_slots+fuel_slots+1), 1, 6, 0)
end
end
if enderchest then
textOutput("The enderchest in the slot "..(torches_slots+fuel_slots+1), 1, 6, 0)
chests_slots = 1
end
if throw_stuff then
if garbage_slots > 1 then
textOutput("Please make sure there are samples of the items to throw in the slots "..(torches_slots+fuel_slots+chests_slots+1).." to "..(torches_slots+fuel_slots+chests_slots+garbage_slots), 1, 8, 0)
else
garbage_slots = 1
textOutput("Please make sure there is a sample of the item to throw in the slot "..(torches_slots+fuel_slots+chests_slots+1), 1, 8, 0)
end
end
if (Bool_direction == "r") then
Bool_direction = true
else
Bool_direction = false
end
textOutput("Press enter to start", 1, 11, 0)
while true do
press, key = os.pullEvent()
if press == "key" and key == 28 then
break
end
end
resetScreen()
textOutput("", 1, 11, 20)
if Torch_approval and (turtle.getItemCount(1) == 0) then
textOutput("The torches slot is empty. Are you sure you want to use torches ?", 1, 4, 0)
Torch_approval = convertToBool(securedInput(1, 6, "text", 0, 0, "Yes", "No"), "y")
elseif Torch_approval and (turtle.getItemCount(1) ~= 0) then
for u = 1, torches_slots-1 do
turtle.select(u+1)
if not(turtle.compareTo(1)) then
Torch_mismatch = true
end
end
if Torch_mismatch then
resetScreen()
textOutput("All the slots dedicated to the torches have not been set up correctly. Are you sure you want to use torches ?", 1, 4, 0)
Torch_approval = convertToBool(securedInput(1, 7, "text", 0, 0, "Yes", "No"), "y")
end
end
if Chest_approval and (turtle.getItemCount(torches_slots + fuel_slots + 1) == 0) then
resetScreen()
textOutput("The chests slot is empty. Are you sure you want to use chests ?", 1, 4, 0)
Chest_approval = convertToBool(securedInput(1, 6, "text", 0, 0, "Yes", "No"), "y")
elseif Chest_approval and (turtle.getItemCount(torches_slots + fuel_slots + 1) ~= 0) then
for u = 1, chests_slots-1 do
turtle.select(torches_slots + fuel_slots + u + 1)
if not(turtle.compareTo(torches_slots + fuel_slots + 1)) then
Chest_mismatch = true
end
end
if Chest_mismatch then
resetScreen()
textOutput("All the slots dedicated to the chests have not been set up correctly. Are you sure you want to use chests ?", 1, 4, 0)
Chest_approval = convertToBool(securedInput(1, 7, "text", 0, 0, "Yes", "No"), "y")
end
end
if Torch_approval then
empty_torches_slots = 0
for u = 1, torches_slots do
if turtle.getItemCount(u) == 0 then
empty_torches_slots = empty_torches_slots + 1
end
end
if empty_torches_slots == torches_slots then
shortage[1] = true
end
textOutput("No Torches -", 11, 11, 0)
end
if Torch_approval and (turtle.getItemCount(1) ~= 0) then
shortage[1] = false
textOutput("Torches OK -", 11, 11, 0)
end
if Chest_approval then
empty_chests_slots = 0
for u = 1, chests_slots do
if turtle.getItemCount(torches_slots + fuel_slots + u) == 0 then
empty_chests_slots = empty_chests_slots + 1
end
end
if empty_chests_slots == chests_slots then
shortage[3] = true
end
textOutput("No Chests -", 24, 11, 0)
end
if Chest_approval and (turtle.getItemCount(torches_slots + fuel_slots + 1) ~= 0) then
shortage[3] = false
textOutput("Chests OK -", 24, 11, 0)
end
textOutput("Fuel OK -", 1, 11, 0)
refuel_count = 80 - turtle.getFuelLevel()
FacingAngle, tunnel_forth, current_slot= 0, true, {1, 1, 1}
refuel_count = moveUp(true, 1, refuel_count, false)
if (Width == 1) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
end
for done_tunnels=1, tunnels_integer do
if (Width >= 2) then
for done_layers=1, math.ceil(Length/2) do
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, Width, Height, "down", false, Bool_direction)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, Width, Height, Height_Position, false, not(Bool_direction))
FacingAngle = turn(FacingAngle, Bool_direction, 1)
if (done_layers%4 == 0) then
refuel_count = moveUp(false, 1, refuel_count, false)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
placeTorch("front")
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count = moveUp(true, 1, refuel_count, false)
end
end
elseif (Width == 1) then
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, 2*math.ceil(Length/2), Height, "down", true, Bool_direction)
end
if (Height_Position == "up") then
refuel_count = moveUp(false, (Height - 3), refuel_count, false)
Height_Position = "down"
end
if tunnel_forth and (tunnels_integer - done_tunnels >= 1) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, ((2*Width)+tunnels_separation), Height, "down", false, not(Bool_direction))
if (Height_Position == "up") then
refuel_count = moveUp(false, (Height - 3), refuel_count, false)
Height_Position = "down"
end
FacingAngle = turn(FacingAngle, Bool_direction, 1)
placeTorch("below")
elseif not(tunnel_forth) then
refuel_count = moveForward(FacingAngle, true, 1, true, false, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, ((2*Width)-1+tunnels_separation), Height, "down", false, Bool_direction)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, ((2*Width)-1+tunnels_separation), Height, Height_Position, false, not(Bool_direction))
if (Height_Position == "up") then
refuel_count = moveUp(false, (Height - 3), refuel_count, false)
Height_Position = "down"
end
FacingAngle = turn(FacingAngle, Bool_direction, 2)
refuel_count = moveForward(FacingAngle, true, (Width-2), true, true, refuel_count)
placeTorch("front")
FacingAngle = turn(FacingAngle, not(Bool_direction), 2)
refuel_count = moveForward(FacingAngle, true, (Width-2), true, true, refuel_count)
if (tunnels_integer - done_tunnels ~= 0) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, (tunnels_separation+1), Height, Height_Position, false, Bool_direction)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, (tunnels_separation+1), Height, Height_Position, false, not(Bool_direction))
refuel_count = moveForward(FacingAngle, false, tunnels_separation, true, true, refuel_count)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
placeTorch("front")
FacingAngle = turn(FacingAngle, not(Bool_direction), 2)
end
end
if tunnel_forth and (tunnels_integer - done_tunnels == 0) and (Width > 1) then
refuel_count = moveForward(FacingAngle, false, 2*math.ceil(Length/2), false, false, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count = moveForward(FacingAngle, true, 1, false, false, refuel_count)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, (Width - 1), Height, Height_Position, false, Bool_direction)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count = moveForward(FacingAngle, true, 1, false, false, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 1)
refuel_count, Height_Position = digVerticalLayer(refuel_count, FacingAngle, (Width - 1), Height, Height_Position, false, not(Bool_direction))
if (Height_Position == "up") then
refuel_count = moveUp(false, (Height - 3), refuel_count, false)
Height_Position = "down"
end
refuel_count = moveForward(FacingAngle, false, (Width - 2), false, false, refuel_count)
FacingAngle = turn(FacingAngle, Bool_direction, 2)
end
if (Width == 1) and (tunnels_integer - done_tunnels ~= 0) then
refuel_count = moveForward(FacingAngle, true, 1, true, true, refuel_count)
elseif (Width == 1) and (tunnels_integer - done_tunnels == 0) and tunnel_forth then
refuel_count = moveForward(FacingAngle, false, (2*math.ceil(Length/2)), false, false, refuel_count)
end
tunnel_forth = not(tunnel_forth)
end
refuel_count = moveUp(false, 1, refuel_count, false)
if (Width == 1) and not(tunnel_forth) then
refuel_count = moveForward(FacingAngle, false, 1, false, false, refuel_count)
turn(FacingAngle, Bool_direction, 1)
end
refuel_count = moveForward(FacingAngle, false, ((tunnels_integer*Width) - 1 + (tunnels_separation*(tunnels_integer - 1))), false, false, refuel_count)
FacingAngle = turn(FacingAngle, not(Bool_direction), 1)
refuel_count = moveForward(FacingAngle, true, 1, false, false, refuel_count)
resetScreen()
write("Done. I hope I worked well !")
term.setCursorPos(1,8)
|
-- GoPrimaryKeys
-- GoColumns
-- GoValues
-- GoValuesWhere
-- GoValuesSet
redis = require "redis"
red = redis:new()
-- Init inital funcation
function Init()
local ok, err = red:connect("127.0.0.1", 6379)
ok, err = red:set("dog", "an animal")
local res, err = red:get("dog")
print("redis status: ",res)
end
-- InsertRewrite insert rewrite logic
function InsertRewrite (tab)
end
-- DeleteRewrite delete rewrite logic
function DeleteRewrite (tab)
end
-- UpdateRewrite update rewrite logic
function UpdateRewrite (tab)
end
-- QueryRewrite query rewrite logic
function QueryRewrite (sql)
end
-- Finalizer final destructor function
function Finalizer ()
red:close()
end
|
local wk = require("which-key")
local opts = {mode = 'n', silent = true, noremap = true}
local iopts = {mode = 'i', silent = true, noremap = true}
local buffers = require('mappings.buffers')
local empty_lines = require('mappings.empty_lines')
local files = require('mappings.files')
local git = require('mappings.git')
local lsp = require('mappings.lsp')
local open = require('mappings.open')
local project = require('mappings.project')
local toggle = require('mappings.toggle')
local search = require('mappings.search')
local session = require('mappings.session')
local window = require('mappings.window')
vim.g.mapleader = ' ' -- Space
-- Normal mode mappings
wk.register({
["<leader>"] = {
["<space>"] = { "<cmd>Telescope find_files<cr>", "Find Files" },
["/"] = { "<cmd>Telescope live_grep<cr>", "Search in project" },
[","] = { "<cmd>Telescope buffers<cr>", "Browse buffers" },
},
gc = {name = "+Comments"},
}, opts)
wk.register(buffers, opts)
wk.register(empty_lines, opts)
wk.register(files, opts)
wk.register(git, opts)
wk.register(lsp, opts)
wk.register(open, opts)
wk.register(project, opts)
wk.register(toggle, opts)
wk.register(search, opts)
wk.register(session, opts)
wk.register(window, opts)
-- Insert mode mappings
wk.register({ ["<C-Space>"] = { "<cmd>LspSignatureHelp<cr>", "Signature Help" } }, iopts)
|
Constants = {
SEMI_AUTO = 1,
BURST_FIRE = 2,
FULL_AUTO = 3,
}
AllowedAuto = {
[GetHashKey('GROUP_RIFLE')] = true,
[GetHashKey('GROUP_SMG')] = true,
}
Weapons = {}
function WeaponStub()
return {
Safety = false,
FiringMode = 1,
}
end
function GetWeapon(hash)
if not Weapons[hash] then
Weapons[hash] = WeaponStub()
end
return Weapons[hash]
end
function IsArmed()
return IsPedArmed(PlayerPedId(), 4)
end
function PlayClick(ped)
PlaySoundFromEntity(-1, 'Faster_Click', ped, 'RESPAWN_ONLINE_SOUNDSET', true)
end
function ShowNotification(message)
SetNotificationTextEntry('STRING')
AddTextComponentSubstringPlayerName(message)
DrawNotification(true, true)
end
|
-----------------------------------------------------
--[[
Name: cl_menu_bank_storage.lua
For: SantosRP
By: Ultra
]]--
local Panel = {}
function Panel:Init()
self:SetTitle( "Bank Storage" )
self:SetDeleteOnClose( false )
self.m_pnlInvLabel = vgui.Create( "DLabel", self )
self.m_pnlInvLabel:SetExpensiveShadow( 2, Color(0, 0, 0, 255) )
self.m_pnlInvLabel:SetTextColor( Color(255, 255, 255, 255) )
self.m_pnlInvLabel:SetFont( "Trebuchet24" )
self.m_pnlInvLabel:SetText( "Inventory" )
self.m_pnlInvLabel:SizeToContents()
self.m_pnlBankLabel = vgui.Create( "DLabel", self )
self.m_pnlBankLabel:SetExpensiveShadow( 2, Color(0, 0, 0, 255) )
self.m_pnlBankLabel:SetTextColor( Color(255, 255, 255, 255) )
self.m_pnlBankLabel:SetFont( "Trebuchet24" )
self.m_pnlBankLabel:SetText( "Bank Storage" )
self.m_pnlBankLabel:SizeToContents()
self.m_pnlInventoryList = vgui.Create( "SRP_ScrollPanel", self )
self.m_pnlInventoryList.Paint = function( _, intW, intH )
surface.SetDrawColor( 50, 50, 50, 100 )
surface.DrawRect( 0, 0, intW, intH )
end
self.m_pnlBankList = vgui.Create( "SRP_ScrollPanel", self )
self.m_pnlBankList.Paint = function( _, intW, intH )
surface.SetDrawColor( 50, 50, 50, 100 )
surface.DrawRect( 0, 0, intW, intH )
end
self.m_tblInvItems = {}
self.m_tblBankItems = {}
hook.Add( "GamemodeOnGetBankUpdate", "BankMenu", function()
if not ValidPanel( self ) or not self:IsVisible() then return end
self:Refresh()
end )
end
function Panel:Refresh()
for k, v in pairs( self.m_tblInvItems ) do
if ValidPanel( v ) then v:Remove() end
end
for k, v in pairs( self.m_tblBankItems ) do
if ValidPanel( v ) then v:Remove() end
end
self.m_tblInvItems = {}
self.m_tblBankItems = {}
for k, v in pairs( LocalPlayer():GetInventory() ) do
if not GAMEMODE.Inv:ValidItem( k ) then continue end
if GAMEMODE.Inv:GetItem( k ).JobItem then continue end
local pnl = vgui.Create( "SRPQMenuItemCard", self.m_pnlInventoryList )
pnl.BuildTrayButtons = function( pnl )
pnl.m_pnlBtnTray:Clear()
if not pnl.m_tblItem then return end
local takeBtn = vgui.Create( "SRP_Button", pnl.m_pnlBtnTray )
takeBtn:SetText( "Move To Bank" )
takeBtn.DoClick = function()
GAMEMODE.Net:MoveItemToNPCBank( k, 1 )
end
takeBtn.DoRightClick = function()
local dMenu = DermaMenu()
dMenu:AddOption( "Move 5", function() GAMEMODE.Net:MoveItemToNPCBank( k, 5 ) end )
dMenu:AddOption( "Move 10", function() GAMEMODE.Net:MoveItemToNPCBank( k, 10 ) end )
dMenu:AddOption( "Move 15", function() GAMEMODE.Net:MoveItemToNPCBank( k, 15 ) end )
dMenu:AddOption( "Move 25", function() GAMEMODE.Net:MoveItemToNPCBank( k, 25 ) end )
dMenu:AddOption( "Move 50", function() GAMEMODE.Net:MoveItemToNPCBank( k, 50 ) end )
dMenu:Open()
end
table.insert( pnl.m_tblTrayBtns, takeBtn )
pnl.m_pnlBtnTray:InvalidateLayout()
end
pnl:SetItemID( k )
pnl:SetItemAmount( v )
table.insert( self.m_tblInvItems, pnl )
end
for k, v in pairs( GAMEMODE.m_tblBankItems or {} ) do
if not GAMEMODE.Inv:ValidItem( k ) then continue end
local pnl = vgui.Create( "SRPQMenuItemCard", self.m_pnlBankList )
pnl.BuildTrayButtons = function( pnl )
pnl.m_pnlBtnTray:Clear()
if not pnl.m_tblItem then return end
local takeBtn = vgui.Create( "SRP_Button", pnl.m_pnlBtnTray )
takeBtn:SetText( "Move To Inventory" )
takeBtn.DoClick = function()
GAMEMODE.Net:TakeItemFromBank( k, 1 )
end
takeBtn.DoRightClick = function()
local dMenu = DermaMenu()
dMenu:AddOption( "Move 5", function() GAMEMODE.Net:TakeItemFromBank( k, 5 ) end )
dMenu:AddOption( "Move 10", function() GAMEMODE.Net:TakeItemFromBank( k, 10 ) end )
dMenu:AddOption( "Move 15", function() GAMEMODE.Net:TakeItemFromBank( k, 15 ) end )
dMenu:AddOption( "Move 25", function() GAMEMODE.Net:TakeItemFromBank( k, 25 ) end )
dMenu:AddOption( "Move 50", function() GAMEMODE.Net:TakeItemFromBank( k, 50 ) end )
dMenu:Open()
end
table.insert( pnl.m_tblTrayBtns, takeBtn )
pnl.m_pnlBtnTray:InvalidateLayout()
end
pnl:SetItemID( k )
pnl:SetItemAmount( v )
table.insert( self.m_tblBankItems, pnl )
end
self:InvalidateLayout()
end
function Panel:PerformLayout( intW, intH )
DFrame.PerformLayout( self, intW, intH )
local padding = 0
local half = intW /2
self.m_pnlInvLabel:SetPos( 5, 28 )
self.m_pnlBankLabel:SetPos( intW -self.m_pnlBankLabel:GetWide() -5, 28 )
self.m_pnlInventoryList:SetSize( half -(padding *2), intH -28 -self.m_pnlInvLabel:GetTall() -padding )
self.m_pnlInventoryList:SetPos( padding, 28 +self.m_pnlInvLabel:GetTall() +padding )
self.m_pnlBankList:SetSize( half -(padding *2), intH -28 -self.m_pnlInvLabel:GetTall() -padding )
self.m_pnlBankList:SetPos( padding +half, 28 +self.m_pnlInvLabel:GetTall() +padding )
for _, pnl in pairs( self.m_tblInvItems ) do
pnl:DockMargin( 0, 0, 0, 5 )
pnl:SetTall( 48 )
pnl:Dock( TOP )
end
for _, pnl in pairs( self.m_tblBankItems ) do
pnl:DockMargin( 0, 0, 0, 5 )
pnl:SetTall( 48 )
pnl:Dock( TOP )
end
end
function Panel:Open()
self:Refresh()
self:SetVisible( true )
self:MakePopup()
end
function Panel:OnClose()
GAMEMODE.Net:SendNPCDialogEvent( "bank_storage_end_dialog" )
end
vgui.Register( "SRPBankStorageMenu", Panel, "SRP_Frame" )
|
client = nil
service = nil
return function(data)
local getData = nil
local window = client.UI.Make("Window",{
Name = "BlockedUsers";
Title = "Blocked Users";
Icon = client.MatIcons.Dangerous;
Size = {300, 200};
MinSize = {180, 120};
AllowMultiple = false;
OnRefresh = function()
getData()
end
})
local scroller = window:Add("ScrollingFrame", {
List = {};
ScrollBarThickness = 3;
BackgroundTransparency = 1;
Position = UDim2.new(0, 0, 0, 35);
Size = UDim2.new(1, 0, 1, -40);
})
local search = window:Add("TextBox", {
Position = UDim2.new(0, 5, 0, 5);
Size = UDim2.new(1, -10, 0, 25);
BackgroundTransparency = 0.25;
BorderSizePixel = 0;
TextColor3 = Color3.new(1, 1, 1);
Text = "";
PlaceholderText = "Search";
TextStrokeTransparency = 0.8;
})
search:Add("ImageLabel", {
Image = client.MatIcons.Search;
Position = UDim2.new(1, -21, 0, 3);
Size = UDim2.new(0, 18, 0, 18);
ImageTransparency = 0.2;
BackgroundTransparency = 1;
})
local blockedUsers: {number} = {}
local function generate()
local filter = search.Text
scroller:ClearAllChildren()
local count = 0
for i, person in ipairs(blockedUsers) do
count += 1
local name = if type(person) == "number" then service.Players:GetNameFromUserIdAsync(person)
elseif person.DisplayName == person.Username then person.Username else string.format("%s (@%s)", person.DisplayName, person.Username)
local userId = if type(person) == "number" then person else person.Id
local plr = service.Players:GetPlayerByUserId(userId)
if filter == "" or string.find(name:lower(), filter:lower()) then
local entry = scroller:Add("TextLabel", {
Text = " "..name;
ToolTip = "ID: ".. userId;
BackgroundTransparency = (i%2 == 0 and 0) or 0.2;
Size = UDim2.new(1, -10, 0, 30);
Position = UDim2.new(0, 5, 0, (30*(i-1)));
TextXAlignment = "Left";
})
if plr then
entry:Add("TextLabel", {
Text = "Unblock";
BackgroundTransparency = 1;
Size = UDim2.new(0, 100, 0.9, 0);
Position = UDim2.new(1, -100, 0.05, 0);
OnClick = function()
service.StarterGui:SetCore("PromptUnblockPlayer", plr)
end
})
end
spawn(function()
entry:Add("ImageLabel", {
Image = service.Players:GetUserThumbnailAsync(userId, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420);
BackgroundTransparency = 1;
Size = UDim2.new(0, 30, 0, 30);
Position = UDim2.new(0, 0, 0, 0);
})
end)
end
end
scroller:ResizeCanvas(false, true, false, false, 5, 5)
window:SetTitle("Blocked Users ("..count..")")
end
function getData()
blockedUsers = service.StarterGui:GetCore("GetBlockedUserIds")
blockedUsers = select(2, xpcall(function()
return service.UserService:GetUserInfosByUserIdsAsync(blockedUsers)
end, function() return blockedUsers end))
generate()
end
search:GetPropertyChangedSignal("Text"):Connect(generate)
service.StarterGui:GetCore("PlayerBlockedEvent").Event:Connect(getData)
service.StarterGui:GetCore("PlayerUnblockedEvent").Event:Connect(getData)
getData()
window:Ready()
end
|
require 'hlslens'.setup()
|
local screenSize = Vector2(guiGetScreenSize())
local isScreenVisible = false
local fonts = {}
local colors = {
white = tocolor(255, 255, 255, 255),
orange = tocolor(235, 196, 15, 255),
grey = tocolor(180, 180, 180, 100),
}
local scale = 1
local isMousePressed = false
local prevMouseState = false
local mouseX = 0
local mouseY = 0
local screenData = {
nickname = "-",
rank = 0,
players_total = 0,
kills = 0,
reward = 0,
time_alive = 0,
accuracy = 0,
damage_taken = 0,
hp_healed = 0
}
local winTexts = {
"rank_wintext1"
}
local currentWinText = ""
function localize(name)
local res = getResourceFromName("pb_lang")
if (res) and (getResourceState(res) == "running") then
return exports.pb_lang:localize(name)
else
return name
end
end
function isMouseOver(x, y, w, h)
return mouseX >= x and mouseX <= x + w and mouseY >= y and mouseY <= y + h
end
local function drawButton(text, x, y, width, height, bg, color, scale)
if not bg then bg = tocolor(250, 250, 250) end
if not color then color = tocolor(0, 0, 0, 200) end
if not scale then scale = 1 end
dxDrawRectangle(x, y, width, height, bg)
dxDrawRectangle(x, y + height - 5, width, 5, tocolor(0, 0, 0, 10))
dxDrawText(text, x, y, x + width, y + height, color, scale, fonts.normal, "center", "center")
if isMouseOver(x, y, width, height) then
dxDrawRectangle(x, y, width, height, tocolor(0, 0, 0, 100))
if isMousePressed then
return true
end
end
return false
end
addEventHandler("onClientRender", root, function ()
if not isScreenVisible then
return
end
local currentMouseState = getKeyState("mouse1")
if not prevMouseState and currentMouseState then
isMousePressed = true
else
isMousePressed = false
end
prevMouseState = currentMouseState
local mx, my = getCursorPosition()
if mx then
mx = mx * screenSize.x
my = my * screenSize.y
else
mx, my = 0, 0
end
mouseX, mouseY = mx, my
dxDrawRectangle(0, 0, screenSize.x, screenSize.y, tocolor(0, 0, 0, 200))
dxDrawText(tostring(screenData.nickname), 50, 50, 51, 51, colors.white, 1, fonts.big, "left", "top")
local topText
if screenData.rank and screenData.rank <= 10 then
if screenData.rank == 1 then
topText = localize(currentWinText)
else
topText = localize("rank_top10text")
end
else
topText = localize("rank_losetext")
end
dxDrawText(topText, 50, 120, 51, 121, colors.orange, 1, fonts.medium, "left", "top")
dxDrawText("#"..tostring(screenData.rank), 0, 50, screenSize.x - 50 - 130, 51, colors.orange, scale, fonts.bigger_bold, "right", "top")
dxDrawText("/"..tostring(screenData.players_total), screenSize.x - 50 - 125, 50, screenSize.x, 51, colors.grey, scale, fonts.bigger, "left", "top")
local ry = 240
local rx = 50
local rtext = localize("rank_label") ..tostring(screenData.rank)
local rw = dxGetTextWidth(rtext, 1, fonts.medium)
local rh = dxGetFontHeight(1, fonts.medium)
dxDrawText(rtext, rx, ry, rx + rw, ry + 1, colors.white, 1, fonts.medium, "left", "top")
dxDrawLine(rx, ry + rh + 15, rx + rw, ry + rh + 15, colors.grey)
ry = ry + rh + 30
dxDrawText(localize("rank_time_survived"), rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
dxDrawText(tostring(screenData.time_alive).." "..localize("rank_minutes"), rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
-- ry = ry + 25
-- dxDrawText("ОЧКИ УБИЙСТВ", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
-- dxDrawText("9999", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
-- ry = ry + 25
-- dxDrawText("ОЧКИ ЧЕГО-ТО ЕЩЁ", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
-- dxDrawText("9999", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
if scale > 0.9 then
ry = 240
rx = rx + rw + 40
rtext = localize("rank_kills") .." "..tostring(screenData.kills)
rw = dxGetTextWidth(rtext, 1, fonts.medium)
dxDrawText(rtext, rx, ry, rx + rw, ry + 1, colors.white, 1, fonts.medium, "left", "top")
dxDrawLine(rx, ry + rh + 15, rx + rw, ry + rh + 15, colors.grey)
ry = ry + rh + 30
dxDrawText(localize("rank_accuracy"), rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
dxDrawText(tostring(screenData.accuracy).."%", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
ry = ry + 25
dxDrawText(localize("rank_damage_taken"), rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
dxDrawText(screenData.damage_taken, rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
ry = ry + 25
dxDrawText(localize("rank_healed_hp"), rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
dxDrawText(screenData.hp_healed, rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
end
ry = 240
rx = rx + rw + 40
rtext = localize("rank_reward") .. " "..tostring(screenData.reward)
rw = dxGetTextWidth(rtext, 1, fonts.medium)
dxDrawText(rtext, rx, ry, rx + rw, ry + 1, colors.white, 1, fonts.medium, "left", "top")
dxDrawLine(rx, ry + rh + 15, rx + rw, ry + rh + 15, colors.grey)
-- ry = ry + rh + 30
-- dxDrawText("ОЧКИ РАНГА", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
-- dxDrawText("9999", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
-- ry = ry + 25
-- dxDrawText("ОЧКИ УБИЙСТВ", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
-- dxDrawText("9999", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
-- ry = ry + 25
-- dxDrawText("ОЧКИ ЧЕГО-ТО ЕЩЁ", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "left", "top")
-- dxDrawText("9999", rx, ry, rx + rw, ry + 1, colors.grey, 1, fonts.small, "right", "top")
local bw = 200
local bh = 50
if drawButton(localize("rank_exit_to_lobby"), screenSize.x / 2 - bw / 2, screenSize.y - bh - 50, bw, bh) then
setVisible(false)
triggerEvent("onExitToLobby", resourceRoot)
end
end)
addEventHandler("onClientResourceStart", resourceRoot, function ()
fonts.bigger_bold = dxCreateFont("assets/Roboto-Bold.ttf", 54)
fonts.bigger = dxCreateFont("assets/Roboto-Regular.ttf", 54)
fonts.big = dxCreateFont("assets/Roboto-Regular.ttf", 35)
fonts.medium = dxCreateFont("assets/Roboto-Regular.ttf", 28)
fonts.small = dxCreateFont("assets/Roboto-Regular.ttf", 10)
fonts.normal = dxCreateFont("assets/Roboto-Bold.ttf", 14)
if screenSize.x < 1024 then
scale = 0.5
end
setVisible(false)
end)
function setVisible(visible)
if isScreenVisible == not not visible then
return
end
isScreenVisible = not not visible
showCursor(isScreenVisible)
end
function isVisible()
return isScreenVisible
end
function setScreenData(data)
if type(data) ~= "table" then
return
end
currentWinText = winTexts[math.random(1, #winTexts)]
screenData = data
end
|
local class = require 'lib.middleclass'
local Path = require 'qix.path'
local Zone = require 'qix.zone'
local Qix = class('Qix')
function Qix:initialize()
self.zones = {}
self.cursor = {x = 0, y = 0}
self.size = {x=1280,y=720}
self.speed = 3
self.current_path = nil
end
function Qix:update(dt)
local input_x, input_y = System.playerInput:get 'move'
local input_marker = System.playerInput:get 'action' == 1 or false
self:move_cursor(input_x * self.speed, input_y * self.speed)
if self.current_path and self.current_path.aborted and self.current_path.elapsed <= 0 then
self.current_path = nil
end
if self.current_path and not self.current_path.aborted then
local result = self.current_path:extend_to(self.cursor.x, self.cursor.y)
if result == "zone" then
print("Convert path into zone")
end
if not input_marker then
self:endPath()
end
else
if input_marker then
self:beginPath()
end
end
if self.current_path then self.current_path:update(dt) end
end
-- x and y are -1 to 1 and indicate the amount of input
function Qix:move_cursor(x, y)
local new_x = self.cursor.x + x
local new_y = self.cursor.y + y
new_x = math.min(new_x, self.size.x)
new_x = math.max(new_x, 0)
new_y = math.min(new_y, self.size.y)
new_y = math.max(new_y, 0)
-- additional logic about following lines?
self.cursor.x = new_x
self.cursor.y = new_y
end
function Qix:beginPath()
if self.current_path then
print("Tried to start new path while existing path is active")
return
end
self.current_path = Path:new(self.size.x, self.size.y)
self.current_path:beginPath(self.cursor.x, self.cursor.y)
end
function Qix:endPath()
if not self.current_path then
print("Tried to end path without active path existing")
return
end
self.current_path:abort()
end
function Qix:draw()
if self.current_path then
self.current_path:draw()
end
for z in ipairs(self.zones) do
z:draw()
end
-- draw cursor
love.graphics.draw(Assets.ui.cursor, self.cursor.x, self.cursor.y)
end
return Qix
|
-- @namespace foundation.com
--
-- Foundation MT, contains some various utilities for general minetest stuff
--
local mod = foundation.new_module("foundation_mt", "1.0.0")
-- Helper function for recovering some amount of hp
--
-- It will return the amount that was actually recovered
--
-- A return of 0 means nothing was recovered
--
-- @spec recover_hp(ObjectRef, Integer, Any): Integer
function foundation.com.recover_hp(entity, amount, reason)
local hp = entity:get_hp()
local hp_max = entity:get_properties().hp_max
local used_amount = math.min(hp + amount, hp_max) - hp
if used_amount > 0 then
entity:set_hp(hp + used_amount, reason)
end
return used_amount
end
-- A copy of minetest default's get_inventory_drops
--
-- Adds an inventory's items to a given drops list
--
-- @mutative
-- @spec get_inventory_drops(pos: Vector3, inventory: InventoryRef, drops: ItemStack[]): void
function foundation.com.get_inventory_drops(pos, inventory, drops)
local inv = minetest.get_meta(pos):get_inventory()
local n = #drops
for i = 1, inv:get_size(inventory) do
local stack = inv:get_stack(inventory, i)
if stack:get_count() > 0 then
n = n + 1
drops[n] = stack:to_table()
end
end
end
mod:require("groups.lua")
mod:require("schematic_helpers.lua")
|
local socket = require "socket"
local json = require "json"
print("Type the requirement that you want to do")
local requirement = io.read()
-- starts a connection to the server
local server = socket.connect("localhost", 80324)
-- table with the requirement
local reqtab = {
requirement = requirement
}
if server ~= nil then
-- encodes the requirement to a json format
local msg = json.encode(reqtab) .. "\n"
-- sends the requirement
server:send(msg)
-- gets a response
response = server:receive()
response = json.decode(response)
-- treats the response
if response.msg == "error" then
print("error! ", response.err)
else
if response.requirement == "hour" then
io.write(response.hour, ":", response.min, ":", response.sec, "\n")
elseif response.requirement == "test" then
print(response.msg)
end
end
server:close()
else
print("error, can't reach the server")
end
|
--
-- PubNub : Subscribe Example
--
require "pubnub"
require "PubnubUtil"
textout = PubnubUtil.textout
--
-- INITIALIZE PUBNUB STATE
--
pubnub_obj = pubnub.new({
publish_key = "demo",
subscribe_key = "demo",
secret_key = nil,
ssl = nil
})
--
-- STARTING WELCOME MESSAGE FOR THIS EXAMPLE
--
textout("...")
textout(" ")
--
-- HIDE STATUS BAR
--
display.setStatusBar( display.HiddenStatusBar )
--
-- FUNCTIONS USED FOR TEST
--
function subscribe( channel )
pubnub_obj:subscribe({
channel = channel,
connect = function()
textout('Connected to channel ')
textout(channel)
end,
callback = function(message)
--print(message.data.message)
textout(message)
end,
error = function()
textout("Oh no!!! Dropped 3G Conection!")
end,
})
end
--
-- MAIN TEST
--
subscribe("lua-1")
|
-- zauberer
local base = require 'base'
local inv = require 'inventory'
local kampf = require 'battle'
local logger = client.createLogger('zauberer')
local trigger = {}
-- ---------------------------------------------------------------------------
-- Zauber
local zaubererhandschuhe = {
feuersteinhandschuhe = 'feuer',
schlangenlederhandschuhe = 'feuer',
wandlerhandschuhe = '*',
}
local function hand(art)
local handschuhart = art or 'feuer'
local handschuhe = inv.ruestung.handschuhe()
if handschuhe ~= nil and handschuhe ~= ''
and zaubererhandschuhe[handschuhe] ~= '*'
and zaubererhandschuhe[handschuhe] ~= handschuhart
then
client.send('ziehe '..handschuhe..' aus')
end
client.send('hand '..(art or ''))
end
local function rueste(item)
client.send('rueste '..item)
end
local items_ruesten
local rueste_next_index = 1
local function rueste_next_item()
local item = items_ruesten[rueste_next_index]
rueste_next_index = rueste_next_index + 1
rueste(item)
end
-- ruestet nacheinander alle ruestungsteile
local function ruesten()
items_ruesten = inv.alleRuestungen()
rueste_next_index = 1
rueste_next_item()
client.createTimer(3, rueste_next_item, #items_ruesten-1)
end
local einstellbare_zauber = {
gp='giftpfeil', g='giftpfeil',
fb='feuerball', f='feuerball',
bl='blitz', b='blitz',
}
local zauber_staerken = {
k='klein',
m='mittel',
g='gross',
}
zauber_staerken['1'] = 'klein'
zauber_staerken['2'] = 'mittel'
zauber_staerken['3'] = 'gross'
local function spruchstaerke(spruch, staerke)
spruch = einstellbare_zauber[spruch] or spruch
staerke = zauber_staerken[staerke] or staerke
client.send('spruchstaerke '..spruch..' '..staerke)
end
-- blitz nur fuer stabschaden
local verletze_typen = {
fe='feuer', ei='eis', wa='wasser', ma='magie',
gi='gift', lu='wind', sa='saeure', kr='laerm',
bl='blitz', er='erde',
}
verletzeSchaden = nil
-- schaden fuer verletze einstellen
local function verletzeSchaden(schaden)
verletzeSchaden = verletze_typen[schaden] or schaden
client.send('verletzungstyp '..verletzeSchaden)
end
local function getVerletzeSchaden()
return verletzeSchaden
end
local function stabschaden(schaden)
if schaden == 'he' then
client.send('weihe zauberstab')
elseif schaden == 'bo' then
client.send('verfluche zauberstab')
else
schaden = verletze_typen[schaden] or schaden
client.send('stabschaden '..schaden)
end
end
-- ---------------------------------------------------------------------------
-- Trigger fuer Highlighting
trigger[#trigger+1] = client.createRegexTrigger('ist nun von einer (feurigen|eisigen|verschwommenen|magischen|giftgruenen|durchscheinenden|roetlichen|flimmernden|funkelnden) Aura eingehuellt.', nil, {'<green>'})
trigger[#trigger+1] = client.createRegexTrigger('Die Aura um Dein.* schwindet.', nil, {'<red>'})
trigger[#trigger+1] = client.createSubstrTrigger('Die Ausfuehrung Deines vorbereiteten Spruches wird verzoegert.', nil, {'<cyan>'})
trigger[#trigger+1] = client.createSubstrTrigger('Dir fehlen die noetigen Materialien!', nil, {'B','<red>'})
trigger[#trigger+1] = client.createSubstrTrigger('Deine Haende beginnen', nil, {'<green>'})
trigger[#trigger+1] = client.createSubstrTrigger('Die Verzauberung Deiner Haende laesst langsam nach.', nil, {'<red>'})
trigger[#trigger+1] = client.createSubstrTrigger('Du konzentrierst Deinen Willen auf Deinen Schutz.', nil, {'<green>'})
trigger[#trigger+1] = client.createSubstrTrigger('Dein Wille laesst nach.', nil, {'<red>'})
trigger[#trigger+1] = client.createSubstrTrigger('Ploetzlich loest sich Dein Schatten von Dir.', nil, {'<green>'})
trigger[#trigger+1] = client.createSubstrTrigger('Du hast jetzt eine zusaetzliche Hand zur Verfuegung.', nil, {'<green>'})
trigger[#trigger+1] = client.createSubstrTrigger('Deine Extrahand loest sich auf.', nil, {'<red>'})
trigger[#trigger+1] = client.createSubstrTrigger('Du wirst allmaehlich wieder langsamer.', nil, {'<red>'})
-- ---------------------------------------------------------------------------
-- Statuszeile
local statusConf =
'SKP:{skp:3} {hand:1} {extrahand:1} {wille:1} {sz:1} {ba:1}'
..'{er:1} {gesinnung:1} {gesundheit:4}'
local function convert(flag, to)
return flag == 'J' and to or ' '
end
local function statusZeile1(m)
local gesundheit =
convert(m[5],'G')..convert(m[6],'B')
..convert(m[7],'T')..convert(m[8],'F')
base.statusUpdate(
{'skp', m[3]},
{'gesinnung', m[4]},
{'gesundheit', gesundheit}
)
end
local function statusZeile2(m)
base.statusUpdate(
{'hand', m[1]},
{'extrahand', m[2]},
{'wille', m[3]},
{'sz', m[4]},
{'ba', m[5]},
{'er', m[6]}
)
end
trigger[#trigger+1] = client.createRegexTrigger('^STATUS1: ([0-9]+) ([0-9]+) ([0-9]+) (.) (.) (.) (.) (.)', statusZeile1, {'g'})
trigger[#trigger+1] = client.createRegexTrigger('^STATUS2: (.) (.) (.) (.) (.) (.) ([0-9]+) (.+)', statusZeile2, {'g'})
client.disableTrigger(trigger)
local function createFunctionMitGegner(cmd)
return
function()
client.send(cmd..' '..kampf.getGegner())
end
end
local function createFunctionMitHands(n, cmd)
return
function()
inv.doWithHands(n, cmd)
end
end
-- ---------------------------------------------------------------------------
-- Guild class Zauberer
local class = require 'utils.class'
local Guild = require 'guild.guild'
local Zauberer = class(Guild)
function Zauberer:info()
client.send('stabinfo')
client.send('verletzungstyp')
client.send('ginhalt')
end
function Zauberer:entsorgeLeiche()
client.send('entsorge leiche')
end
function Zauberer:enable()
-- Standardfunktionen ------------------------------------------------------
base.statusConfig(statusConf)
-- Trigger -----------------------------------------------------------------
client.createSubstrTrigger(base.charName()..' loest sich in Luft auf.', nil, {'<red>'})
client.enableTrigger(trigger)
-- Tasten ------------------------------------------------------------------
local keymap = base.keymap
keymap.F5 = function() hand('feuer') end
keymap.S_F5 = function() hand('eis') end
keymap.F6 = function() hand('saeure') end
keymap.S_F6 = createFunctionMitGegner('giftpfeil')
keymap.F7 = createFunctionMitGegner('feuerball')
keymap.S_F7 = createFunctionMitGegner('blitz')
keymap.F8 = createFunctionMitGegner('verletze')
keymap.S_F8 = createFunctionMitGegner('entkraefte')
keymap.M_a = 'vorahnung'
keymap.M_b = 'erdbeben'
keymap.M_d = 'zauberschild'
keymap.M_e = 'nachtsicht schwach'
keymap.M_f = createFunctionMitGegner('irritiere')
keymap.M_g = createFunctionMitGegner('schmerzen')
keymap.M_i = 'wille'
keymap.M_j = createFunctionMitHands(2, 'extrahand')
keymap.M_k = 'schattenkaempfer'
keymap.M_l = 'licht'
keymap.M_m = 'schutzhuelle'
keymap.M_p = 'befriede'
keymap.M_r = 'schutzzone'
keymap.M_t = 'teleport'
keymap.M_v = 'schutz'
keymap.M_y = hand
keymap.M_x = 'schnell'
keymap.M_z = 'erschoepfung'
-- Aliases -----------------------------------------------------------------
client.createStandardAlias(
'skills', 0, function() client.send('tm llystrathe faehigkeiten') end
)
client.createStandardAlias(
'quests', 0, function() client.send('tm llystrathe anforderungen') end
)
client.createStandardAlias('ruesten', 0, ruesten)
client.createStandardAlias('cs', 1, verletzeSchaden)
client.createStandardAlias('zs', 1, stabschaden)
client.createStandardAlias('as', 2, spruchstaerke)
end
return Zauberer
|
--[[
linkerator.lua
Linkerator functionality for adapted for Ludwig
Thanks to N00bZXI for the autocomplete changes
--]]
local function OnFullMatch(match)
local list = Ludwig:GetItemsNamedLike(match)
if list and list[1] then
return (select(2, GetItemInfo(list[1])))
end
return match
end
local function OnPartialMatch(match)
local list = Ludwig:GetItemsNamedLike(match)
if list and list[1] then
return '[[' .. GetItemInfo(list[1])
end
return '[[' .. match
end
local function Linkerator_OnChar(self, ...)
local text = self:GetText()
if text ~= '' then
if text:match('%[%[(.+)%]') then
self:SetText(text:gsub('%[%[(.+)%]', OnFullMatch))
else
self:SetText(text:gsub('%[%[(.+)', OnPartialMatch))
self:HighlightText(#text, -1)
end
end
end
if ChatFrameEditBox:GetScript('OnChar') then
ChatFrameEditBox:HookScript('OnChar', Linkerator_OnChar)
else
ChatFrameEditBox:SetScript('OnChar', Linkerator_OnChar)
end
|
-- Copyright (C) 2018 XiaoShan mivm.cn
local m, s, o
m = Map("k3usb", translate("k3usb"))
m.description = translate("k3 usb mode")
s = m:section(TypedSection, "config", translate("usb mode"))
s.anonymous = true
o = s:option(Flag, "usb3_enable", translate("usb3 enable :"))
o.description = translate("usb3 mode enable")
o.default = 1
return m
|
local mod = DBM:NewMod(1856, "DBM-TombofSargeras", nil, 875)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 17522 $"):sub(12, -3))
mod:SetCreatureID(116407)
mod:SetEncounterID(2036)
mod:SetZone()
--mod:SetBossHPInfoToHighest()
--mod:SetUsedIcons(1)
mod:SetHotfixNoticeRev(16282)
mod.respawnTime = 29
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 232174 231904 234194 240319 241590",
"SPELL_CAST_SUCCESS 231854 231729 234129",
"SPELL_AURA_APPLIED 231998 231729 231904 234016 241600 233429 232061",
"SPELL_AURA_APPLIED_DOSE 231998",
"SPELL_AURA_REMOVED 233429 234016 241600",
"SPELL_AURA_REMOVED_DOSE 233429",
"SPELL_PERIODIC_DAMAGE 231768",
"SPELL_PERIODIC_MISSED 231768",
"UNIT_DIED",
"INSTANCE_ENCOUNTER_ENGAGE_UNIT",
"UNIT_SPELLCAST_SUCCEEDED boss1"
)
--[[
(ability.id = 232174 or ability.id = 231904) and type = "begincast" or
(ability.id = 231854 or ability.id = 232061) and type = "cast" or
(ability.id = 233429 or ability.id = 232061) and (type = "applybuff" or type = "removebuff") or
(target.id = 116569 or target.id = 117596 or target.id = 117522 or target.id = 120545) and type = "death" or
(ability.id = 241590 or ability.id = 240319 or ability.id = 234194) and type = "begincast" or (abilty.id = 231729 or ability.id = 234129 or ability.id = 234016) and type = "cast"
--]]
--Harjatan
local warnJaggedAbrasion = mod:NewStackAnnounce(231998, 2, nil, "Tank")
local warnFrigidBlows = mod:NewStackAnnounce(233429, 2)
--Razorjaw Wavemender
local warnAqueousBurst = mod:NewTargetAnnounce(231729, 2, nil, false)--Spammy
--Razorjaw Gladiator
local warnDrivenAssault = mod:NewTargetAnnounce(234016, 3, nil, false)--Spammy
--Mythic (Eggs and tadpoles)
local warnSicklyFixate = mod:NewTargetAnnounce(241600, 4)
--Harjatan
local specWarnJaggedAbrasion = mod:NewSpecialWarningStack(231998, nil, 4, nil, nil, 1, 6)
local specWarnJaggedAbrasionOther = mod:NewSpecialWarningTaunt(231998, nil, nil, nil, 1, 2)
local specWarnUncheckedRage = mod:NewSpecialWarningCount(231854, nil, nil, nil, 2, 2)
local specWarnDrenchingWaters = mod:NewSpecialWarningMove(231768, nil, nil, nil, 1, 2)
local specWarnCommandingroar = mod:NewSpecialWarningSwitch(232192, "-Healer", nil, nil, 1, 2)
local specWarnDrawIn = mod:NewSpecialWarningSpell(232061, nil, nil, nil, 1, 2)
local specWarnFrostyDischarge = mod:NewSpecialWarningSpell(232174, nil, nil, nil, 1, 2)
--Razorjaw Wavemender
local specWarnAqueousBurst = mod:NewSpecialWarningMoveAway(231729, nil, nil, nil, 1, 2)
local yellAqueousBurst = mod:NewShortYell(231729)
local specWarnTendWounds = mod:NewSpecialWarningInterrupt(231904, "HasInterrupt")
local specWarnTendWoundsDispel = mod:NewSpecialWarningDispel(231904, "MagicDispeller")
--Razorjaw Gladiator
local specWarnDrivenAssault = mod:NewSpecialWarningRun(234016, nil, nil, 2, 4, 2)
--Mythic (Eggs and tadpoles)
local specWarnHatching = mod:NewSpecialWarningSwitch(240319, nil, nil, 2, 1, 2)
local specWarnSicklyFixate = mod:NewSpecialWarningRun(241600, nil, nil, 2, 4, 2)
local specWarnTantrum = mod:NewSpecialWarningSpell(241590, nil, nil, nil, 2, 2)
--Harjatan
mod:AddTimerLine(BOSS)
local timerUncheckedRageCD = mod:NewNextCountTimer(20, 231854, nil, nil, nil, 2)--5 power per second heroic, 20 seconds for 100 energy
local timerDrawInCD = mod:NewNextTimer(59, 232061, nil, nil, nil, 6)
local timerCommandingRoarCD = mod:NewNextTimer(31.8, 232192, nil, nil, nil, 1)
mod:AddTimerLine(DBM_ADDS)
--Razorjaw Wavemender
local timerAqueousBurstCD = mod:NewCDTimer(6, 231729, nil, false, nil, 3)--6-8
--Razorjaw Gladiator
local timerDrivenAssault = mod:NewTargetTimer(10, 234016, nil, false, nil, 3)--Too many spawn, this would be spammy so off by default
local timerSplashCleaveCD = mod:NewCDTimer(12, 234129, nil, false, nil, 5, nil, DBM_CORE_TANK_ICON)
--Mythic
mod:AddTimerLine(ENCOUNTER_JOURNAL_SECTION_FLAG12)
local timerHatchingCD = mod:NewNextTimer(40.6, 240319, nil, nil, nil, 1)--40.6-42
local berserkTimer = mod:NewBerserkTimer(360)
--Harjatan
local countdownUncheckedRage = mod:NewCountdown(20, 231854)
--mod:AddSetIconOption("SetIconOnShield", 228270, true)
--mod:AddInfoFrameOption(227503, true)
--mod:AddRangeFrameOption("5/8/15")
mod:AddNamePlateOption("NPAuraOnSicklyFixate", 241600)
mod:AddNamePlateOption("NPAuraOnDrivenAssault", 234016)
mod:AddSetIconOption("SetIconOnWavemender", "ej14555", true, true)
mod.vb.rageCount = 0
local seenMobs = {}
function mod:OnCombatStart(delay)
self.vb.rageCount = 0
table.wipe(seenMobs)
timerUncheckedRageCD:Start(-delay, 1)
countdownUncheckedRage:Start()
specWarnUncheckedRage:Schedule(16-delay, 1)
specWarnUncheckedRage:ScheduleVoice(16-delay, "gathershare")
timerCommandingRoarCD:Start(17.3-delay)
timerDrawInCD:Start(58-delay)
if not self:IsEasy() then
if self:IsMythic() then
timerHatchingCD:Start(30.5-delay)
berserkTimer:Start(360-delay)
end
else
berserkTimer:Start(480-delay)--Confirm in LFR too?
end
if self.Options.NPAuraOnSicklyFixate and self:IsMythic() or self.Options.NPAuraOnDrivenAssault then
DBM:FireEvent("BossMod_EnableHostileNameplates")
end
end
function mod:OnCombatEnd()
-- if self.Options.RangeFrame then
-- DBM.RangeCheck:Hide()
-- end
-- if self.Options.InfoFrame then
-- DBM.InfoFrame:Hide()
-- end
if self.Options.NPAuraOnSicklyFixate and self:IsMythic() or self.Options.NPAuraOnDrivenAssault then
DBM.Nameplate:Hide(true, nil, nil, nil, true, true)
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 232174 then
specWarnFrostyDischarge:Show()
specWarnFrostyDischarge:Play("phasechange")
self.vb.rageCount = 0
timerCommandingRoarCD:Start(17.1)
timerUncheckedRageCD:Start(21.1, 1)--21.1-23.5
countdownUncheckedRage:Start(21)
specWarnUncheckedRage:Schedule(17, 1)
specWarnUncheckedRage:Play(17, "gathershare")
timerDrawInCD:Start()
if self:IsMythic() then
timerHatchingCD:Start(30)
end
elseif spellId == 231904 then
if self:CheckInterruptFilter(args.sourceGUID, false, true) then
specWarnTendWounds:Show(args.sourceName)
specWarnTendWounds:Play("kickcast")
end
elseif spellId == 234194 then
--warnFrostySpittle:Show()
--timerFrostySpittleCD:Start(nil, args.sourceGUID)
elseif spellId == 241590 then
specWarnTantrum:Show()
specWarnTantrum:Play("aesoon")
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 231729 then
timerAqueousBurstCD:Start(nil, args.sourceGUID)
elseif spellId == 231854 then--Unchecked Rage
self.vb.rageCount = self.vb.rageCount + 1
timerUncheckedRageCD:Start(nil, self.vb.rageCount+1)
countdownUncheckedRage:Start()
specWarnUncheckedRage:Schedule(17, self.vb.rageCount+1)
specWarnUncheckedRage:ScheduleVoice(17, "gathershare")
elseif spellId == 234129 then
timerSplashCleaveCD:Start(nil, args.sourceGUID)
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 231998 then
local uId = DBM:GetRaidUnitId(args.destName)
if self:IsTanking(uId) then
local amount = args.amount or 1
if amount >= 4 then--Lasts 30 seconds, cast every 5 seconds, swapping will be at 6
if args:IsPlayer() then--At this point the other tank SHOULD be clear.
specWarnJaggedAbrasion:Show(amount)
specWarnJaggedAbrasion:Play("stackhigh")
else--Taunt as soon as stacks are clear, regardless of stack count.
if not UnitIsDeadOrGhost("player") and not DBM:UnitDebuff("player", args.spellName) then
specWarnJaggedAbrasionOther:Show(args.destName)
specWarnJaggedAbrasionOther:Play("tauntboss")
else
warnJaggedAbrasion:Show(args.destName, amount)
end
end
else
if amount % 2 == 0 then
warnJaggedAbrasion:Show(args.destName, amount)
end
end
end
elseif spellId == 231729 then
warnAqueousBurst:CombinedShow(1, args.destName)
if args:IsPlayer() then
specWarnAqueousBurst:Show()
specWarnAqueousBurst:Play("runout")
yellAqueousBurst:Yell()
end
elseif spellId == 231904 then
specWarnTendWoundsDispel:Show(args.destName)
if self.Options.SpecWarn231904dispel then
specWarnTendWoundsDispel:Play("dispelnow")
end
elseif spellId == 234016 then
timerDrivenAssault:Start(10, args.destName)
warnDrivenAssault:CombinedShow(1, args.destName)
if args:IsPlayer() and self:AntiSpam(3, 4) then
specWarnDrivenAssault:Show()
specWarnDrivenAssault:Play("justrun")
specWarnDrivenAssault:ScheduleVoice(1, "keepmove")
end
if self.Options.NPAuraOnDrivenAssault then
DBM.Nameplate:Show(true, args.sourceGUID, spellId)
end
elseif spellId == 241600 then
warnSicklyFixate:CombinedShow(0.5, args.destName)
if args:IsPlayer() and self:AntiSpam(3, 3) then
specWarnSicklyFixate:Show()
specWarnSicklyFixate:Play("justrun")
specWarnSicklyFixate:ScheduleVoice(1, "keepmove")
end
if self.Options.NPAuraOnSicklyFixate then
DBM.Nameplate:Show(true, args.sourceGUID, spellId)
end
elseif spellId == 232061 then
timerUncheckedRageCD:Stop()
countdownUncheckedRage:Cancel()
specWarnUncheckedRage:Cancel()
specWarnUncheckedRage:CancelVoice()
timerCommandingRoarCD:Stop()
timerDrawInCD:Stop()
specWarnDrawIn:Show()
specWarnDrawIn:Play("phasechange")
end
end
mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 233429 then
local amount = args.amount or 0
if amount < 4 or self:AntiSpam(5, 1) then
--Every 5 seconds or every stack under 4
warnFrigidBlows:Show(args.destName, amount)
end
elseif spellId == 234016 then
timerDrivenAssault:Stop(args.destName)
if self.Options.NPAuraOnDrivenAssault then
DBM.Nameplate:Hide(true, args.sourceGUID, spellId)
end
elseif spellId == 241600 then
if self.Options.NPAuraOnSicklyFixate then
DBM.Nameplate:Hide(true, args.sourceGUID, spellId)
end
end
end
mod.SPELL_AURA_REMOVED_DOSE = mod.SPELL_AURA_REMOVED
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 231768 and destGUID == UnitGUID("player") and self:AntiSpam(2, 2) then
specWarnDrenchingWaters:Show()
specWarnDrenchingWaters:Play("runaway")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
function mod:UNIT_DIED(args)
local cid = self:GetCIDFromGUID(args.destGUID)
if cid == 116569 then--Razorjaw Wavemender
timerAqueousBurstCD:Stop(args.destGUID)
elseif cid == 117596 then--Razorjaw Gladiator
timerSplashCleaveCD:Stop(args.destGUID)
--elseif cid == 117522 then--Darkscale Taskmaster
--timerFrostySpittleCD:Stop(args.destGUID)
elseif cid == 120545 then--Incubated Egg
end
end
--"<26.92 17:09:49> [INSTANCE_ENCOUNTER_ENGAGE_UNIT] Fake Args:#boss1#false#false#false#??#nil#normal#0#boss2#false#false#false#??#nil#normal#0#boss3#false#false#false#??#nil#normal#0#boss4#false#false#false#??#nil#normal#0#boss5#false#false#false#??#nil#normal#0#Real Args:", -- [74]
--"<26.93 17:09:49> [UNIT_TARGETABLE_CHANGED] nameplate3#false#false#true#Razorjaw Gladiator#Creature-0-2083-1676-7590-117596-00011E36EB#elite#10751230", -- [75]
--"<26.93 17:09:49> [UNIT_TARGETABLE_CHANGED] nameplate4#false#false#true#Razorjaw Gladiator#Creature-0-2083-1676-7590-117596-00009E36EB#elite#10751230", -- [76]
--Didn't live long enough to see if IEEU would work for these, based on above it wouldn't or it wouldn't be as fast as UNIT_TARGETABLE_CHANGED. However UNIT_TARGETABLE_CHANGED might rely on nameplate unitIDs
function mod:INSTANCE_ENCOUNTER_ENGAGE_UNIT()
for i = 1, 5 do
local unitID = "boss"..i
local GUID = UnitGUID(unitID)
if GUID and not seenMobs[GUID] then
seenMobs[GUID] = true
local cid = self:GetCIDFromGUID(GUID)
if cid == 116569 then--Razorjaw Wavemender
--timerAqueousBurstCD:Start(1, GUID)
if self.Options.SetIconOnWavemender then
self:ScanForMobs(GUID, 0, 8, 2, 0.2, 12, "SetIconOnWavemender")
end
end
end
end
end
function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, _, spellGUID)
local spellId = tonumber(select(5, strsplit("-", spellGUID)), 10)
if spellId == 232192 then--Commanding Roar
specWarnCommandingroar:Show()
specWarnCommandingroar:Play("killmob")
timerCommandingRoarCD:Start()
elseif spellId == 240347 then--Warn Players of Hatching Eggs
specWarnHatching:Show()
specWarnHatching:Play("killmob")
timerHatchingCD:Start()
end
end
|
-- Local instances of Global tables --
local PA = PersonalAssistant
local PAJ = PA.Junk
local PAHF = PA.HelperFunctions
-- ---------------------------------------------------------------------------------------------------------------------
local function _unmarkAllPAItemIdsFromJunk(paItemId)
PAJ.debugln("#_unmarkAllPAItemIdsFromJunk(%s)", tostring(paItemId))
local customPAItems = {
[paItemId] = {}
}
local excludeJunk, excludeCharacterBound, excludeStolen = false, false, false
local paItemIdComparator = PAHF.getPAItemIdComparator(customPAItems, excludeJunk, excludeCharacterBound, excludeStolen)
local bagCache = SHARED_INVENTORY:GenerateFullSlotData(paItemIdComparator, PAHF.getAccessibleBags())
PAJ.debugln("#bagCache = "..tostring(#bagCache))
for index = #bagCache, 1, -1 do
local itemData = bagCache[index]
local isJunk = IsItemJunk(itemData.bagId, itemData.slotIndex)
if isJunk then
SetItemIsJunk(itemData.bagId, itemData.slotIndex, false)
PlaySound(SOUNDS.INVENTORY_ITEM_UNJUNKED)
end
end
end
local function _markAllPAItemIdsAsJunk(paItemId)
PAJ.debugln("#_markAllPAItemIdsAsJunk(%s)", tostring(paItemId))
local customPAItems = {
[paItemId] = {}
}
local excludeJunk, excludeCharacterBound, excludeStolen = true, false, false
local paItemIdComparator = PAHF.getPAItemIdComparator(customPAItems, excludeJunk, excludeCharacterBound, excludeStolen)
local bagCache = SHARED_INVENTORY:GenerateFullSlotData(paItemIdComparator, PAHF.getAccessibleBags())
PAJ.debugln("#bagCache = "..tostring(#bagCache))
for index = #bagCache, 1, -1 do
local itemData = bagCache[index]
if CanItemBeMarkedAsJunk(itemData.bagId, itemData.slotIndex) then
SetItemIsJunk(itemData.bagId, itemData.slotIndex, true)
PlaySound(SOUNDS.INVENTORY_ITEM_JUNKED)
end
end
end
-- ---------------------------------------------------------------------------------------------------------------------
local function getNonStolenItemLink(itemLink)
-- if itemLink is NOT stolen, directly return it
if not IsItemLinkStolen(itemLink) then return itemLink end
-- if it is stolen, remove first the stolen information
local itemLinkMod = string.gsub(itemLink, "1(:%d+:%d+|h|h)$", "0%1")
-- then also remove the red border
itemLinkMod = string.gsub(itemLinkMod, "%d+(:%d+:%d+:%d+:%d+:%d+:%d+|h|h)$", "0%1")
return itemLinkMod
end
local function isItemLinkPermanentJunk(itemLink)
local PAJCUstomPAItemIds = PAJ.SavedVars.Custom.PAItemIds
local paItemId = PAHF.getPAItemLinkIdentifier(itemLink)
return PAHF.isKeyInTable(PAJCUstomPAItemIds, paItemId)
end
local function isItemPermanentJunk(bagId, slotIndex)
local PAJCUstomPAItemIds = PAJ.SavedVars.Custom.PAItemIds
local paItemId = PAHF.getPAItemIdentifier(bagId, slotIndex)
return PAHF.isKeyInTable(PAJCUstomPAItemIds, paItemId)
end
local function addItemLinkToPermanentJunk(itemLink)
PAJ.debugln("PA.Junk.addItemLinkToPermanentJunk")
if PAJ.SavedVars.Custom.customItemsEnabled then
local PAJCUstomPAItemIds = PAJ.SavedVars.Custom.PAItemIds
local paItemId = PAHF.getPAItemLinkIdentifier(itemLink)
-- only add the entry if it is an UPDATE case, or if it does not exist yet
if not PAHF.isKeyInTable(PAJCUstomPAItemIds, paItemId) then
local localItemLink = getNonStolenItemLink(itemLink)
PAJCUstomPAItemIds[paItemId] = {
itemLink = localItemLink,
junkCount = 0,
ruleAdded = GetTimeStamp()
}
PA.Junk.println(SI_PA_CHAT_JUNK_RULES_ADDED, localItemLink:gsub("%|H0", "|H1"))
-- loop though whole inventory to mark all matching items
_markAllPAItemIdsAsJunk(paItemId)
-- refresh the list (if it was initialized)
if PA.JunkRulesList then PA.JunkRulesList:Refresh() end
else
PAJ.debugln("ERROR; PAJ rule already existing")
end
end
end
local function removeItemLinkFromPermanentJunk(itemLink)
PAJ.debugln("PA.Junk.removeItemLinkFromPermanentJunk")
if PAJ.SavedVars.Custom.customItemsEnabled then
local PAJCUstomPAItemIds = PAJ.SavedVars.Custom.PAItemIds
local paItemId = PAHF.getPAItemLinkIdentifier(itemLink)
if PAHF.isKeyInTable(PAJCUstomPAItemIds, paItemId) then
-- is in table, delete rule
PAJCUstomPAItemIds[paItemId] = nil
PAJ.println(SI_PA_CHAT_JUNK_RULES_DELETED, itemLink:gsub("%|H0", "|H1"))
-- loop though whole inventory to unmark all matching items
_unmarkAllPAItemIdsFromJunk(paItemId)
-- refresh the list (if it was initialized)
if PA.JunkRulesList then PA.JunkRulesList:Refresh() end
else
PAJ.debugln("ERROR; PAJ rule not existing, cannot be deleted")
end
end
end
-- ---------------------------------------------------------------------------------------------------------------------
-- Export
PA.Junk = PA.Junk or {}
PA.Junk.Custom = {
isItemLinkPermanentJunk = isItemLinkPermanentJunk,
isItemPermanentJunk = isItemPermanentJunk,
addItemLinkToPermanentJunk = addItemLinkToPermanentJunk,
removeItemLinkFromPermanentJunk = removeItemLinkFromPermanentJunk
}
|
-- 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.
function media_transform(data, eos)
done = 0
slen = string.len(data)
if ts.ctx['fit'] > 0 then
if ts.ctx['fit'] + slen >= ts.ctx['len'] then
need = ts.ctx['len'] - ts.ctx['fit']
done = 1
else
need = slen
end
ts.ctx['fit'] = ts.ctx['fit'] + need
ts.ctx['passed'] = ts.ctx['passed'] + slen
return data:sub(1, need), done
elseif ts.ctx['passed'] + slen >= ts.ctx['offset'] then
spos = ts.ctx['offset'] - ts.ctx['passed'] + 1
need = ts.ctx['passed'] + slen - ts.ctx['offset']
if need >= ts.ctx['len'] then
need = ts.ctx['len']
done = 1
end
epos = spos + need - 1
ts.ctx['fit'] = ts.ctx['fit'] + need
ts.ctx['passed'] = ts.ctx['passed'] + slen
return data:sub(spos, epos), done
else
ts.ctx['passed'] = ts.ctx['passed'] + slen
return nil, eos
end
end
function read_response()
http_status = ts.server_response.header.get_status()
ts.debug(string.format('server_response status = %d', http_status))
if http_status ~= 200 then
return
end
ts.http.resp_cache_transformed(0)
ts.http.resp_cache_untransformed(1)
if ts.ctx['transform_add'] == 1 then
return
end
ts.hook(TS_LUA_RESPONSE_TRANSFORM, media_transform)
ts.ctx['fit'] = 0
ts.ctx['passed'] = 0
end
function cache_lookup()
status = ts.http.get_cache_lookup_status()
ts.debug(string.format('cache lookup status: %d', status))
if status ~= TS_LUA_CACHE_LOOKUP_HIT_FRESH and status ~= TS_LUA_CACHE_LOOKUP_HIT_STALE then
return
end
http_status = ts.cached_response.header.get_status()
ts.debug(string.format('cached_response http status: %d', http_status))
if http_status ~= 200 then
return
end
ts.http.resp_cache_transformed(0)
ts.hook(TS_LUA_RESPONSE_TRANSFORM, media_transform)
ts.ctx['transform_add'] = 1
ts.ctx['fit'] = 0
ts.ctx['passed'] = 0
end
function do_remap()
url = ts.client_request.get_url()
ts.debug(string.format('src_url = %s', url))
param_s = string.find(url, '?')
start_s, start_e, start_val = string.find(url, 'start=(%d+)', param_s)
if start_s ~= nil then
end_s, end_e, end_val = string.find(url, 'end=(%d+)', start_e)
offset_s, offset_e, offset_val = string.find(url, 'offset=(%d+)', end_e)
len_s, len_e, len_val = string.find(url, 'len=(%d+)', offset_e)
in_query = true
else
start_s, start_e, start_val = string.find(url, "/start_(%d+)")
end_s, end_e, end_val = string.find(url, "/end_(%d+)", start_e)
offset_s, offset_e, offset_val = string.find(url, "/offset_(%d+)", end_e)
len_s, len_e, len_val = string.find(url, "/len_(%d+)", offset_e)
end
start_val = tonumber(start_val)
end_val = tonumber(end_val)
offset_val = tonumber(offset_val)
len_val = tonumber(len_val)
if start_val == nil or end_val == nil or offset_val == nil or len_val == nil then
ts.http.set_resp(400, "params invalid\n")
return 0
end
if start_val < 0 or end_val < start_val or offset_val < 0 or len_val <= 0 then
ts.http.set_resp(400, "params invalid\n")
return 0
end
if in_query then
slash = url:len() - url:reverse():find("/") + 1
cache_url = string.format('%sstart_%d/end_%d/%s', string.sub(url, 1, slash), start_val, end_val, string.sub(url, slash+1, param_s-1))
else
cache_url = string.format('%s%s', string.sub(url, 1, end_e), string.sub(url, len_e))
end
ts.debug(string.format('cache_url = %s', cache_url))
ts.http.set_cache_url(cache_url)
ts.client_request.header['Range'] = nil
ts.ctx['start'] = start_val
ts.ctx['end'] = end_val
ts.ctx['offset'] = offset_val
ts.ctx['len'] = len_val
ts.hook(TS_LUA_HOOK_CACHE_LOOKUP_COMPLETE, cache_lookup)
ts.hook(TS_LUA_HOOK_READ_RESPONSE_HDR, read_response)
return 0
end
|
return {
init_effect = "",
name = "Z字旗·三笠",
time = 0,
picture = "",
desc = "炮击、命中提高5%",
stack = 1,
id = 6235,
icon = 6235,
last_effect = "",
effect_list = {
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "cannonPower",
number = 500
}
},
{
type = "BattleBuffAddAttrRatio",
trigger = {
"onAttach"
},
arg_list = {
attr = "attackRating",
number = 500
}
}
}
}
|
-----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Perfaumand
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- !pos -39 -3 69 233
-----------------------------------
require("scripts/globals/quests")
require("scripts/globals/missions")
require("scripts/globals/keyitems")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local WildcatSandy = player:getCharVar("WildcatSandy")
local currentMission = player:getCurrentMission(SANDORIA)
local missionStatus = player:getCharVar("MissionStatus")
if currentMission == tpz.mission.id.sandoria.RANPERRE_S_FINAL_REST and ((player:hasKeyItem(tpz.ki.ANCIENT_SANDORIAN_BOOK) and missionStatus == 3) or missionStatus == 4 or missionStatus == 5) then
player:startEvent(49) -- Optional 6-2 CS
elseif currentMission == tpz.mission.id.sandoria.RANPERRE_S_FINAL_REST and missionStatus == 6 then
player:startEvent(50) -- Optional 6-2 CS
elseif currentMission == tpz.mission.id.sandoria.RANPERRE_S_FINAL_REST and missionStatus == 7 then
player:startEvent(79) -- Optional 6-2 CS
elseif player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy, 18) == false then
player:startEvent(560)
else
player:startEvent(522)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 560 then
player:setMaskBit(player:getCharVar("WildcatSandy"), "WildcatSandy", 18, true)
end
end
|
--[[
Copyright 2020 megagrump@pm.me
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
local ffi, bit = require('ffi'), require('bit')
local C = ffi.C
local File = {
getBuffer = function(self) return self._bufferMode, self._bufferSize end,
getFilename = function(self) return self._name end,
getMode = function(self) return self._mode end,
isOpen = function(self) return self._mode ~= 'c' and self._handle ~= nil end,
}
local fopen, getcwd, chdir, unlink, mkdir, rmdir
local BUFFERMODE, MODEMAP
local ByteArray = ffi.typeof('unsigned char[?]')
local function _ptr(p) return p ~= nil and p or nil end -- NULL pointer to nil
function File:open(mode)
if self._mode ~= 'c' then return false, "File " .. self._name .. " is already open" end
if not MODEMAP[mode] then return false, "Invalid open mode for " .. self._name .. ": " .. mode end
local handle = _ptr(fopen(self._name, MODEMAP[mode]))
if not handle then return false, "Could not open " .. self._name .. " in mode " .. mode end
self._handle, self._mode = ffi.gc(handle, C.fclose), mode
self:setBuffer(self._bufferMode, self._bufferSize)
return true
end
function File:close()
if self._mode == 'c' then return false, "File is not open" end
C.fclose(ffi.gc(self._handle, nil))
self._handle, self._mode = nil, 'c'
return true
end
function File:setBuffer(mode, size)
local bufferMode = BUFFERMODE[mode]
if not bufferMode then
return false, "Invalid buffer mode " .. mode .. " (expected 'none', 'full', or 'line')"
end
if mode == 'none' then
size = math.max(0, size or 0)
else
size = math.max(2, size or 2) -- Windows requires buffer to be at least 2 bytes
end
local success = self._mode == 'c' or C.setvbuf(self._handle, nil, bufferMode, size) == 0
if not success then
self._bufferMode, self._bufferSize = 'none', 0
return false, "Could not set buffer mode"
end
self._bufferMode, self._bufferSize = mode, size
return true
end
function File:getSize()
-- NOTE: The correct way to do this would be a stat() call, which requires a
-- lot more (system-specific) code. This is a shortcut that requires the file
-- to be readable.
local mustOpen = not self:isOpen()
if mustOpen and not self:open('r') then return 0 end
local pos = mustOpen and 0 or self:tell()
C.fseek(self._handle, 0, 2)
local size = self:tell()
if mustOpen then
self:close()
else
self:seek(pos)
end
return size
end
function File:read(containerOrBytes, bytes)
if self._mode ~= 'r' then return nil, 0 end
local container = bytes ~= nil and containerOrBytes or 'string'
if container ~= 'string' and container ~= 'data' then
error("Invalid container type: " .. container)
end
bytes = not bytes and containerOrBytes or 'all'
bytes = bytes == 'all' and self:getSize() - self:tell() or math.min(self:getSize() - self:tell(), bytes)
if bytes <= 0 then
local data = container == 'string' and '' or love.data.newFileData('', self._name)
return data, 0
end
local data = love.data.newByteData(bytes)
local r = tonumber(C.fread(data:getFFIPointer(), 1, bytes, self._handle))
local str = data:getString()
data:release()
data = container == 'data' and love.filesystem.newFileData(str, self._name) or str
return data, r
end
local function lines(file, autoclose)
local BUFFERSIZE = 4096
local buffer, bufferPos = ByteArray(BUFFERSIZE), 0
local bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, file._handle))
local offset = file:tell()
return function()
file:seek(offset)
local line = {}
while bytesRead > 0 do
for i = bufferPos, bytesRead - 1 do
if buffer[i] == 10 then -- end of line
bufferPos = i + 1
return table.concat(line)
end
if buffer[i] ~= 13 then -- ignore CR
table.insert(line, string.char(buffer[i]))
end
end
bytesRead = tonumber(C.fread(buffer, 1, BUFFERSIZE, file._handle))
offset, bufferPos = offset + bytesRead, 0
end
if not line[1] then
if autoclose then file:close() end
return nil
end
return table.concat(line)
end
end
function File:lines()
if self._mode ~= 'r' then error("File is not opened for reading") end
return lines(self)
end
function File:write(data, size)
if self._mode ~= 'w' and self._mode ~= 'a' then
return false, "File " .. self._name .. " not opened for writing"
end
local toWrite, writeSize
if type(data) == 'string' then
writeSize = (size == nil or size == 'all') and #data or size
toWrite = data
else
writeSize = (size == nil or size == 'all') and data:getSize() or size
toWrite = data:getFFIPointer()
end
if tonumber(C.fwrite(toWrite, 1, writeSize, self._handle)) ~= writeSize then
return false, "Could not write data"
end
return true
end
function File:seek(pos)
return self._handle and C.fseek(self._handle, pos, 0) == 0
end
function File:tell()
if not self._handle then return nil, "Invalid position" end
return tonumber(C.ftell(self._handle))
end
function File:flush()
if self._mode ~= 'w' and self._mode ~= 'a' then
return nil, "File is not opened for writing"
end
return C.fflush(self._handle) == 0
end
function File:isEOF()
return not self:isOpen() or C.feof(self._handle) ~= 0 or self:tell() == self:getSize()
end
function File:release()
if self._mode ~= 'c' then self:close() end
self._handle = nil
end
function File:type() return 'File' end
function File:typeOf(t) return t == 'File' end
File.__index = File
-----------------------------------------------------------------------------
local nativefs = {}
local loveC = ffi.os == 'Windows' and ffi.load('love') or C
function nativefs.newFile(name)
if type(name) ~= 'string' then
error("bad argument #1 to 'newFile' (string expected, got " .. type(name) .. ")")
end
return setmetatable({
_name = name,
_mode = 'c',
_handle = nil,
_bufferSize = 0,
_bufferMode = 'none'
}, File)
end
function nativefs.newFileData(filepath)
local f = nativefs.newFile(filepath)
local ok, err = f:open('r')
if not ok then return nil, err end
local data, err = f:read('data', 'all')
f:close()
return data, err
end
function nativefs.mount(archive, mountPoint, appendToPath)
return loveC.PHYSFS_mount(archive, mountPoint, appendToPath and 1 or 0) ~= 0
end
function nativefs.unmount(archive)
return loveC.PHYSFS_unmount(archive) ~= 0
end
function nativefs.read(containerOrName, nameOrSize, sizeOrNil)
local container, name, size
if sizeOrNil then
container, name, size = containerOrName, nameOrSize, sizeOrNil
elseif not nameOrSize then
container, name, size = 'string', containerOrName, 'all'
else
if type(nameOrSize) == 'number' or nameOrSize == 'all' then
container, name, size = 'string', containerOrName, nameOrSize
else
container, name, size = containerOrName, nameOrSize, 'all'
end
end
local file = nativefs.newFile(name)
local ok, err = file:open('r')
if not ok then return nil, err end
local data, size = file:read(container, size)
file:close()
return data, size
end
local function writeFile(mode, name, data, size)
local file = nativefs.newFile(name)
local ok, err = file:open(mode)
if not ok then return nil, err end
ok, err = file:write(data, size or 'all')
file:close()
return ok, err
end
function nativefs.write(name, data, size)
return writeFile('w', name, data, size)
end
function nativefs.append(name, data, size)
return writeFile('a', name, data, size)
end
function nativefs.lines(name)
local f = nativefs.newFile(name)
local ok, err = f:open('r')
if not ok then return nil, err end
return lines(f, true)
end
function nativefs.load(name)
local chunk, err = nativefs.read(name)
if not chunk then return nil, err end
return loadstring(chunk, name)
end
function nativefs.getWorkingDirectory()
return getcwd()
end
function nativefs.setWorkingDirectory(path)
if not chdir(path) then return false, "Could not set working directory" end
return true
end
function nativefs.getDriveList()
if ffi.os ~= 'Windows' then return { '/' } end
local drives, bits = {}, C.GetLogicalDrives()
for i = 0, 25 do
if bit.band(bits, 2 ^ i) > 0 then
table.insert(drives, string.char(65 + i) .. ':/')
end
end
return drives
end
function nativefs.createDirectory(path)
local current = path:sub(1, 1) == '/' and '/' or ''
for dir in path:gmatch('[^/\\]+') do
current = current .. dir .. '/'
local info = nativefs.getInfo(current, 'directory')
if not info and not mkdir(current) then return false, "Could not create directory " .. current end
end
return true
end
function nativefs.remove(name)
local info = nativefs.getInfo(name)
if not info then return false, "Could not remove " .. name end
if info.type == 'directory' then
if not rmdir(name) then return false, "Could not remove directory " .. name end
return true
end
if not unlink(name) then return false, "Could not remove file " .. name end
return true
end
local function withTempMount(dir, fn, ...)
local mountPoint = _ptr(loveC.PHYSFS_getMountPoint(dir))
if mountPoint then return fn(ffi.string(mountPoint), ...) end
if not nativefs.mount(dir, '__nativefs__temp__') then return false, "Could not mount " .. dir end
local a, b = fn('__nativefs__temp__', ...)
nativefs.unmount(dir)
return a, b
end
function nativefs.getDirectoryItems(dir)
if type(dir) ~= "string" then
error("bad argument #1 to 'getDirectoryItems' (string expected, got " .. type(dir) .. ")")
end
local result, err = withTempMount(dir, love.filesystem.getDirectoryItems)
return result or {}
end
local function getDirectoryItemsInfo(path, filtertype)
local items = {}
local files = love.filesystem.getDirectoryItems(path)
for i = 1, #files do
local filepath = string.format('%s/%s', path, files[i])
local info = love.filesystem.getInfo(filepath, filtertype)
if info then
info.name = files[i]
table.insert(items, info)
end
end
return items
end
function nativefs.getDirectoryItemsInfo(path, filtertype)
if type(path) ~= "string" then
error("bad argument #1 to 'getDirectoryItemsInfo' (string expected, got " .. type(path) .. ")")
end
local result, err = withTempMount(path, getDirectoryItemsInfo, filtertype)
return result or {}
end
local function getInfo(path, file, filtertype)
local filepath = string.format('%s/%s', path, file)
return love.filesystem.getInfo(filepath, filtertype)
end
local function leaf(p)
p = p:gsub('\\', '/')
local last, a = p, 1
while a do
a = p:find('/', a + 1)
if a then
last = p:sub(a + 1)
end
end
return last
end
function nativefs.getInfo(path, filtertype)
if type(path) ~= 'string' then
error("bad argument #1 to 'getInfo' (string expected, got " .. type(path) .. ")")
end
local dir = path:match("(.*[\\/]).*$") or './'
local file = leaf(path)
local result, err = withTempMount(dir, getInfo, file, filtertype)
return result or nil
end
-----------------------------------------------------------------------------
MODEMAP = { r = 'rb', w = 'wb', a = 'ab' }
local MAX_PATH = 4096
ffi.cdef([[
int PHYSFS_mount(const char* dir, const char* mountPoint, int appendToPath);
int PHYSFS_unmount(const char* dir);
const char* PHYSFS_getMountPoint(const char* dir);
typedef struct FILE FILE;
FILE* fopen(const char* path, const char* mode);
size_t fread(void* ptr, size_t size, size_t nmemb, FILE* stream);
size_t fwrite(const void* ptr, size_t size, size_t nmemb, FILE* stream);
int fclose(FILE* stream);
int fflush(FILE* stream);
size_t fseek(FILE* stream, size_t offset, int whence);
size_t ftell(FILE* stream);
int setvbuf(FILE* stream, char* buffer, int mode, size_t size);
int feof(FILE* stream);
]])
if ffi.os == 'Windows' then
ffi.cdef([[
int MultiByteToWideChar(unsigned int cp, uint32_t flags, const char* mb, int cmb, const wchar_t* wc, int cwc);
int WideCharToMultiByte(unsigned int cp, uint32_t flags, const wchar_t* wc, int cwc, const char* mb,
int cmb, const char* def, int* used);
int GetLogicalDrives(void);
int CreateDirectoryW(const wchar_t* path, void*);
int _wchdir(const wchar_t* path);
wchar_t* _wgetcwd(wchar_t* buffer, int maxlen);
FILE* _wfopen(const wchar_t* path, const wchar_t* mode);
int _wunlink(const wchar_t* path);
int _wrmdir(const wchar_t* path);
]])
BUFFERMODE = { full = 0, line = 64, none = 4 }
local function towidestring(str)
local size = C.MultiByteToWideChar(65001, 0, str, #str, nil, 0)
local buf = ffi.new('wchar_t[?]', size + 1)
C.MultiByteToWideChar(65001, 0, str, #str, buf, size)
return buf
end
local function toutf8string(wstr)
local size = C.WideCharToMultiByte(65001, 0, wstr, -1, nil, 0, nil, nil)
local buf = ffi.new('char[?]', size + 1)
C.WideCharToMultiByte(65001, 0, wstr, -1, buf, size, nil, nil)
return ffi.string(buf)
end
local nameBuffer = ffi.new('wchar_t[?]', MAX_PATH + 1)
fopen = function(path, mode) return C._wfopen(towidestring(path), towidestring(mode)) end
getcwd = function() return toutf8string(C._wgetcwd(nameBuffer, MAX_PATH)) end
chdir = function(path) return C._wchdir(towidestring(path)) == 0 end
unlink = function(path) return C._wunlink(towidestring(path)) == 0 end
mkdir = function(path) return C.CreateDirectoryW(towidestring(path), nil) ~= 0 end
rmdir = function(path) return C._wrmdir(towidestring(path)) == 0 end
else
BUFFERMODE = { full = 0, line = 1, none = 2 }
ffi.cdef([[
char* getcwd(char *buffer, int maxlen);
int chdir(const char* path);
int unlink(const char* path);
int mkdir(const char* path, int mode);
int rmdir(const char* path);
]])
local nameBuffer = ByteArray(MAX_PATH)
fopen = C.fopen
unlink = function(path) return ffi.C.unlink(path) == 0 end
chdir = function(path) return ffi.C.chdir(path) == 0 end
mkdir = function(path) return ffi.C.mkdir(path, 0x1ed) == 0 end
rmdir = function(path) return ffi.C.rmdir(path) == 0 end
getcwd = function()
local cwd = _ptr(C.getcwd(nameBuffer, MAX_PATH))
return cwd and ffi.string(cwd) or nil
end
end
return nativefs
|
local responses = require "kong.tools.responses"
local utils = require "kong.tools.utils"
local kutils = require ("kong.plugins.keystone.utils")
local policies = require ("kong.plugins.keystone.policies")
local cjson = require 'cjson'
local namespace_id
local function get_group_by_id_or_name(dao_factory, id_or_name)
local group, err = dao_factory.group:find({id = id_or_name})
kutils.assert_dao_error(err, "group find")
if group then return group end
local temp, err = dao_factory.group:find_all ({name = id_or_name, domain_id = namespace_id})
kutils.assert_dao_error(err, "group find all")
if temp[1] then return temp[1] end
responses.send_HTTP_BAD_REQUEST("No group with id "..id_or_name)
end
local function get_user_by_id_or_name (dao_factory, id_or_name)
local user, err = dao_factory.user:find({id = id_or_name})
kutils.assert_dao_error(err, "user find")
if user then return user.id end
local temp, err = dao_factory.local_user:find_all ({name = id_or_name, domain_id = namespace_id})
kutils.assert_dao_error(err, "local user find all")
if temp[1] then return temp[1].user_id end
local temp, err = dao_factory.nonlocal_user:find({ name = id_or_name, domain_id = namespace_id })
kutils.assert_dao_error(err, "nonlocal user find")
if temp then return temp.user_id end
responses.send_HTTP_BAD_REQUEST("No user with id "..id_or_name)
end
local function list_groups(self, dao_factory)
local args = (self.params.name or self.params.domain_id) and {name = self.params.name, domain_id = self.params.domain_id} or nil
local resp = {
links = {
self = self:build_url(self.req.parsed_url.path),
next = cjson.null,
previous = cjson.null
},
groups = {}
}
local groups, err = dao_factory.group:find_all(args)
kutils.assert_dao_error(err, "group:find_all")
resp.groups = groups
for i = 1, kutils.list_limit(#groups) do
resp.groups[i].links = {
self = self:build_url(self.req.parsed_url.path..'/'..groups[i].id)
}
end
return responses.send_HTTP_OK(resp)
end
local function create_group(self, dao_factory)
if not self.params.group or not self.params.group.name then
responses.send_HTTP_BAD_REQUEST("No group object found in request")
end
local group = {
id = utils.uuid(),
description = self.params.group.description,
domain_id = self.params.group.domain_id or 'default',
name = self.params.group.name
}
local temp, err = dao_factory.group:find_all({name = group.name, domain_id = group.domain_id})
kutils.assert_dao_error(err, "group:find_all")
if next(temp) then
return responses.send_HTTP_CONFLICT("Name is already used in domain")
end
local _, err = dao_factory.group:insert(group)
kutils.assert_dao_error(err, "group:insert")
local resp = {
group = group
}
resp.group.links = {
self = self:build_url(self.req.parsed_url.path..'/'..group.id)
}
return responses.send_HTTP_CREATED(resp)
end
local function get_group_info(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local resp = {
group = group
}
resp.group.links = {
self = self:build_url(self.req.parsed_url.path)
}
responses.send_HTTP_OK(resp)
end
local function update_group(self, dao_factory)
if not self.params.group then
return responses.send_HTTP_BAD_REQUEST("No group object found in request")
end
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local ugroup = {
description = self.params.group.description,
domain_id = self.params.group.domain_id,
name = self.params.group.name
}
local temp, err = dao_factory.group:find_all({name = ugroup.name or group.name, domain_id = ugroup.domain_id or group.domain_id})
if next(temp) then
return responses.send_HTTP_CONFLICT("Name is already used in domain")
end
local resp = {
group = {}
}
resp.group, err = dao_factory.group:update(ugroup, {id = group.id})
kutils.assert_dao_error(err, "group:update")
resp.group.links = {
self = self:build_url(self.req.parsed_url.path)
}
responses.send_HTTP_OK(resp)
end
local function delete_group(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local group, err = dao_factory.group:delete({id = group.id})
kutils.assert_dao_error(err, "group delete")
responses.send_HTTP_NO_CONTENT()
end
local function list_group_users(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local user_group, err = dao_factory.user_group_membership:find_all({group_id = group.id})
kutils.assert_dao_error(err, "user_group_membership:find_all")
local resp = {
links = {
self = self:build_url(self.req.parsed_url.path),
next = cjson.null,
previous = cjson.null
},
users = {}
}
local password_expires_at, op = kutils.string_to_time(self.params.password_expires_at)
for _, v in ipairs(user_group) do
local user, err = dao_factory.user:find({id = v.user_id})
kutils.assert_dao_error(err, "user:find")
local uname, exp
local temp, err = dao_factory.local_user:find_all({user_id = user.id})
kutils.assert_dao_error(err, "local_user:find_all")
local loc_user = temp[1]
local fit = true
if loc_user then
uname = loc_user.name
local passwd, err = dao_factory.password:find_all({local_user_id = loc_user.id})
kutils.assert_dao_error(err, "password:find_all")
exp = passwd[1] and passwd[1].expires_at
if password_expires_at then
if not exp or op == 'lt' and exp >= password_expires_at or
op == 'lte' and exp > password_expires_at or
op == 'gt' and exp <= password_expires_at or
op == 'gte' and exp < password_expires_at or
op == 'eq' and exp ~= password_expires_at or
op == 'neq' and exp == password_expires_at then
fit = false
end
end
elseif password_expires_at then
fit = false
else
local temp, err = dao_factory.nonlocal_user:find_all({user_id = user.id})
kutils.assert_dao_error(err, "nonlocal_user:find_all")
if next(temp) then
uname = temp[1].name
end
end
resp.users[#resp.users + 1] = fit and {
domain_id = user.domain_id,
description = user.description,
enabled = kutils.bool(user.enabled),
id = user.id,
name = uname or cjson.null,
links = {
self = self:build_url("/v3/users/"..user.id)
},
password_expires_at = loc_user and kutils.time_to_string(exp)
} or nil
end
responses.send_HTTP_OK(resp)
end
local function add_user_to_group(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local user_id = get_user_by_id_or_name(dao_factory, self.params.user_id)
local _, err = dao_factory.user_group_membership:insert({user_id = user_id, group_id = group.id})
kutils.assert_dao_error(err, "user_group_membership:insert")
return 200
end
local function check_user_in_group(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local user_id = get_user_by_id_or_name(dao_factory, self.params.user_id)
local temp, err = dao_factory.user_group_membership:find({user_id = user_id, group_id = group.id})
kutils.assert_dao_error(err, "user_group_membership:find")
if not temp then
responses.send_HTTP_BAD_REQUEST()
end
responses.send_HTTP_NO_CONTENT()
end
local function remove_user_from_group(self, dao_factory)
local group = get_group_by_id_or_name(dao_factory, self.params.group_id)
local user_id = get_user_by_id_or_name(dao_factory, self.params.user_id)
local temp, err = dao_factory.user_group_membership:delete({user_id = user_id, group_id = group.id})
kutils.assert_dao_error(err, "user_group_membership:delete")
if not temp then
responses.send_HTTP_BAD_REQUEST()
end
responses.send_HTTP_NO_CONTENT()
end
local routes = {
['/v3/groups'] = {
GET = function (self, dao_factory)
policies.check(self.req.headers['X-Auth-Token'], "identity:list_groups", dao_factory, self.params)
list_groups(self, dao_factory)
end,
POST = function (self, dao_factory)
policies.check(self.req.headers['X-Auth-Token'], "identity:create_group", dao_factory, self.params)
create_group(self, dao_factory)
end
},
['/v3/groups/:group_id'] = {
GET = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:get_group", dao_factory, self.params)
get_group_info(self, dao_factory)
end,
PATCH = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:update_group", dao_factory, self.params)
update_group(self, dao_factory)
end,
DELETE = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:delete_group", dao_factory, self.params)
delete_group(self, dao_factory)
end,
},
['/v3/groups/:group_id/users'] = {
GET = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:list_users_in_group", dao_factory, self.params)
list_group_users(self, dao_factory)
end
},
['/v3/groups/:group_id/users/:user_id'] = {
PUT = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:add_user_to_group", dao_factory, self.params)
responses.send(add_user_to_group(self, dao_factory))
end,
HEAD = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:check_user_in_group", dao_factory, self.params)
check_user_in_group(self, dao_factory)
end,
DELETE = function (self, dao_factory)
namespace_id = policies.check(self.req.headers['X-Auth-Token'], "identity:remove_user_from_group", dao_factory, self.params)
remove_user_from_group(self, dao_factory)
end
}
}
return {
routes = routes,
add_member = add_user_to_group
}
|
local Entity = {}
Entity.Position = {X = 0, Y = 0}
Entity.Velocity = {X = 0, Y = 0}
Entity.RotVelocity = 0
Entity.Z = 0
Entity.Rotation = 0
Entity.Scale = 3
Entity.Type = 1
Entity.Visible = true
setmetatable(Entity, {
__call = function(Self, GLib)
GLib.OOPS.Objectify(Self)
return Self
end
})
return Entity
|
-- API
local API = require(script:GetCustomProperty("GameStateAPI"))
local Hideout = script:GetCustomProperty("Hideout"):WaitForObject()
local Level1 = script:GetCustomProperty("Level1"):WaitForObject()
local Level2 = script:GetCustomProperty("Level2"):WaitForObject()
local MainStorage = script:GetCustomProperty("MainStorage")
local Target = nil
local playerListeners = {}
local statTable = {}
local resourceNames = {"gold", "s1", "s2", "s3", "s4", "m1", "m2", "m3", "m4", "f1", "f2", "f3", "f4"}
function Tick(deltaTime)
for _, player in ipairs(Game.GetPlayers()) do
if player.isFlying == false then
player:ActivateFlying()
end
local prevHealth = statTable[player]["prevHealth"]
local rotation = player:GetWorldRotation()
if player.serverUserData.lockedOn == false then
--raycast
local rotation = Quaternion.New(player:GetLookWorldRotation())
--local hitResult = World.Raycast(player:GetWorldPosition() + cameraOffset, player:GetWorldPosition() + rotation:GetForwardVector() * 10000,
local hitResult = World.Raycast(player:GetViewWorldPosition(), player:GetViewWorldPosition() + rotation:GetForwardVector() * 5000,
{ignorePlayers = {player}} --shouldDebugRender = true
)
local other = hitResult and hitResult.other or nil
--print(other)
local gameTarget, trainingTarget = API.ValidTarget(player, other), API.ValidTrainingTarget(player, other)
if gameTarget or trainingTarget then
Target = other
player.serverUserData.target = Target
local position = hitResult:GetImpactPosition()
player.serverUserData.targetPosition = position
player:SetPrivateNetworkedData("Target", other)
player:SetPrivateNetworkedData("TargetPosition", position)
local newHealth = 0
if gameTarget then
newHealth = gameTarget[1] / gameTarget[2]
else
newHealth = trainingTarget[1] / trainingTarget[2]
end
if newHealth ~= prevHealth then
statTable[player]["prevHealth"] = newHealth
player:SetPrivateNetworkedData("targetHealth", newHealth)
end
else
player.serverUserData.target = nil
player.serverUserData.targetPosition = nil
player:SetPrivateNetworkedData("TargetPosition", nil)
player:SetPrivateNetworkedData("Target", nil)
end
else
if not Object.IsValid(Target) then
player.serverUserData.lockedOn = false
player:SetPrivateNetworkedData("LockedOn", false)
player.serverUserData.target = nil
player.serverUserData.targetPosition = nil
player:SetPrivateNetworkedData("Target", nil)
player:SetPrivateNetworkedData("TargetPosition", nil)
player:SetWorldRotation(rotation)
return
end
local distance = (Target:GetWorldPosition() - player:GetWorldPosition()).size
local gameTarget, trainingTarget = API.ValidTarget(player, Target), API.ValidTrainingTarget(player, Target)
if distance > 5500 then
player.serverUserData.lockedOn = false
player:SetPrivateNetworkedData("LockedOn", false)
player.serverUserData.target = nil
player.serverUserData.targetPosition = nil
player:SetPrivateNetworkedData("Target", nil)
player:SetPrivateNetworkedData("TargetPosition", nil)
elseif gameTarget or trainingTarget then
local newHealth = 0
if gameTarget then
newHealth = gameTarget[1] / gameTarget[2]
else
newHealth = trainingTarget[1] / trainingTarget[2]
end
if newHealth ~= prevHealth then
statTable[player]["prevHealth"] = newHealth
player:SetPrivateNetworkedData("targetHealth", newHealth)
end
else
player.serverUserData.lockedOn = false
player:SetPrivateNetworkedData("LockedOn", false)
player.serverUserData.target = nil
player.serverUserData.targetPosition = nil
player:SetPrivateNetworkedData("Target", nil)
player:SetPrivateNetworkedData("TargetPosition", nil)
end
end
player:SetWorldRotation(rotation)
end
end
function UpdateStats()
while true do
for _, player in ipairs(Game.GetPlayers()) do
local stats = statTable[player]
local casting = player.serverUserData.casting
if stats and stats.initialized and player.isDead == false then
if player.hitPoints > 0 then
if stats.stance ~= "Flower" or casting == false then
player.hitPoints = math.min(player.maxHitPoints, player.hitPoints + stats.health2)
end
if stats.stance ~= "Sword" or casting == false then
stats.stamina = math.min(stats.maxStamina, stats.stamina + stats.stamina2)
player.serverUserData.stamina = stats.stamina
player:SetPrivateNetworkedData("stamina", stats.stamina)
end
if stats.stance ~= "Magic" or casting == false then
stats.magic = math.min(stats.maxMagic, stats.magic + stats.magic2)
player.serverUserData.magic = stats.magic
player:SetPrivateNetworkedData("magic", stats.magic)
end
end
end
end
Task.Wait(2)
end
end
function BindingReleased(player, key)
if key == "ability_extra_23" then
local lockedOn = player.serverUserData.lockedOn
local target = player.serverUserData.target
if lockedOn then
player.serverUserData.lockedOn = false
player:SetPrivateNetworkedData("LockedOn", false)
else
if target then
player.serverUserData.lockedOn = true
player:SetPrivateNetworkedData("LockedOn", true)
end
end
end
end
function DataChanged(player, key)
if key == "maxStamina" then
statTable[player]["maxStamina"] = player:GetPrivateNetworkedData(key)
elseif key == "maxMagic" then
statTable[player]["maxMagic"] = player:GetPrivateNetworkedData(key)
elseif key == "stamina2" then
statTable[player]["stamina2"] = player:GetPrivateNetworkedData(key)
elseif key == "magic2" then
statTable[player]["magic2"] = player:GetPrivateNetworkedData(key)
elseif key == "health2" then
statTable[player]["health2"] = player:GetPrivateNetworkedData(key)
elseif key == "stamina" then
player.serverUserData.stamina = player:GetPrivateNetworkedData(key)
statTable[player]["stamina"] = player.serverUserData.stamina
elseif key == "magic" then
player.serverUserData.magic = player:GetPrivateNetworkedData(key)
statTable[player]["magic"] = player.serverUserData.magic
elseif key == "stance" then
player.serverUserData.stance = player:GetPrivateNetworkedData(key)
statTable[player]["stance"] = player.serverUserData.stance
end
end
local changeableParams = {"maxStamina", "maxMagic", "stamina2", "magic2", "health2", "stamina", "magic", "stance"}
-- Equip script happens before other scripts.
function InitializeValues(player)
for _, key in ipairs(changeableParams) do
local val = player:GetPrivateNetworkedData(key)
if val ~= nil then
statTable[player][key] = val
if key == "stamina" or key == "magic" or key == "stance" then
player.serverUserData[key] = val
end
else
player:SetPrivateNetworkedData(key, statTable[player][key])
end
end
end
function PlayerDied(player, dmg)
API.PlayerDied()
for _, ik in ipairs(player:GetIKAnchors()) do
ik:Deactivate()
end
if player.serverUserData.lockedOn then
player.serverUserData.lockedOn = false
player:SetPrivateNetworkedData("LockedOn", false)
end
Task.Spawn(function()
Task.Wait(2)
local values = API.GetSpawn(player)
local spawn = values[1]
local offset = values[2]
player:Spawn({rotation = spawn:GetWorldRotation(),
position = spawn:GetWorldPosition() + Vector3.New(0, offset, 0)
})
end)
end
function PlayerJoined(player)
player:SetPrivateNetworkedData("LockedOn", false)
player:SetPrivateNetworkedData("Target", nil)
player:SetPrivateNetworkedData("targetHealth", 0)
player.serverUserData.lockedOn = false
player.serverUserData.target = nil
player.serverUserData.targetPosition = nil
playerListeners[player] = {}
playerListeners[player]["binding_released"] = player.bindingReleasedEvent:Connect(BindingReleased)
playerListeners[player]["dataChanged"] = player.privateNetworkedDataChangedEvent:Connect(DataChanged)
playerListeners[player]["died"] = player.diedEvent:Connect(PlayerDied)
statTable[player] ={maxStamina = 100, stamina = 100,
maxMagic = 100, magic = 100, stance = "Sword",
stamina2 = 10, magic2 = 10, health2 = 5,
prevHealth = 0, initialized = false}
player.serverUserData.stamina = 100
player.serverUserData.magic = 100
player.serverUserData.stance = "Sword"
player.serverUserData.casting = false
statTable[player]["initialized"] = true
InitializeValues(player)
player:Spawn({position = Hideout:GetWorldPosition() + Vector3.New(0, (#Game.GetPlayers() - 1) * 200, 0), rotation = Hideout:GetWorldRotation()})
-- Resource
-- DEBUG override storage
local persistentTable = Storage.GetSharedPlayerData(MainStorage, player)
--local customTable = { gold = 100000 }
player.serverUserData.resources = {}
for _, key in ipairs(resourceNames) do
local value = persistentTable[key]
--local value = customTable[key]
if key == "gold" then
player:SetPrivateNetworkedData(key, value or 0)
player.serverUserData.resources[key] = value or 0
else
player:SetPrivateNetworkedData(key, value or false)
player.serverUserData.resources[key] = value or false
end
end
API.PlayerJoined(player)
end
function PlayerLeft(player)
API.PlayerLeft(player)
playerListeners[player]["binding_released"]:Disconnect()
playerListeners[player]["dataChanged"]:Disconnect()
playerListeners[player]["died"]:Disconnect()
playerListeners[player] = nil
statTable[player] = nil
for _, eqp in ipairs(player:GetEquipment()) do
eqp:Unequip()
end
local persistentTable = Storage.GetSharedPlayerData(MainStorage, player)
for key, value in pairs(player.serverUserData.resources) do
persistentTable[key] = value
end
Storage.SetSharedPlayerData(MainStorage, player, persistentTable)
end
Task.Spawn(UpdateStats)
Game.playerJoinedEvent:Connect(PlayerJoined)
Game.playerLeftEvent:Connect(PlayerLeft)
|
require 'collision'
require 'input'
require 'lines'
require 'texts'
local ball = require 'ball'
local pad_0 = require 'pad_0'
local pad_1 = require 'pad_1'
function set_bg_color(r, g, b)
bg_color = {r, g, b}
end
function love.load()
bg_color = {0, 0, 0.1}
ball.init_ball()
text_title = love.graphics.setNewFont('fonts/retroFont.ttf', 44)
text_help = love.graphics.setNewFont('fonts/retroFont.ttf', 24)
text_score = love.graphics.setNewFont('fonts/retroFont.ttf', 50)
end
function love.update(dt)
if dt > 0.035 then return end -- pause when hold window
random_number()
if not paused then
pad_0.movements(dt)
pad_1.movements(dt)
ball.movements(dt)
ball.reset_ball()
ball.ball_screen_col()
col_pad0_ball()
col_pad1_ball()
end
end
function love.draw()
love.graphics.setBackgroundColor(bg_color)
if paused then
paused_text()
help()
end
pad_0.draw_paddle_0()
pad_1.draw_paddle_1()
ball.draw_ball()
draw_lines()
current_fps()
score()
end
|
local quests = {
--retrieve alien object
alien = {
infinite = false,
questName = 'Aliens! - Investigate Goat Farm',
questParent = 'telescopejuan',
collect = {name = 'alien_object', type = 'key'},
--prompt: 'You look very busy'
giveQuestSucceed = {
"You will not believe what's been going on lately!",
"Animals have recently been disappearing in the area and I've been seeing these weird alien lights at night!",
"Just last night, I saw a bright object fall out of the sky into the goat farm nearby. {{teal}}Aliens, aliens!{{white}}",
},
successPrompt = "Can you go {{red_light}}investigate the goat farm and retrieve whatever alien object is there?{{white}}",
promptExtra = {
"Excellent! But first, you're gonna need a key to get inside the farm.",
"Talk to Juan with the {{purple}}purple sombrero{{white}}, he owns the goat farm. Maybe you can persuade him to let you in.",
},
completeQuestFail = "The entrance to the goat farm is right beside Juan with the {{purple}}purple sombrero{{white}}. Ask him for the key to get inside!",
completeQuestSucceed = {
"Ooh, this alien thing looks amazing. This is definite proof that aliens are among us!",
"Here's some money for your troubles, thanks again!",
},
completed = "Man, that alien thing was weird!",
reward = {money = 70},
},
}
return quests
|
return {
"Anime",
{
value=200,
typ="text",
puzzle="Er ist eine gelbe Maus",
answer="Was ist Pikachu?"
},
{
value=400,
typ="text",
puzzle="Er hat als erster beim Kacken blonde Haare bekommen",
answer="Wer ist Son Goku?"
},
{
value=600,
typ="text",
puzzle="Er liebt seinen Strohut",
answer="Was ist Monkey D. Luffy (Ruffy)?"
},
{
value=800,
typ="text",
puzzle="Garant für gute Filme",
answer="Was ist Studio Ghibli?"
},
{
value=1000,
typ="text",
puzzle="Sie strahlt wie die Sonne überm Fujiyama",
answer="Wer ist Mila (Superstar)?"
}
}
|
list_of_ids = {
0x40,
0xA8,
0x8F,
0x01
}
song_length_table = {
[0x40] = 10,
[0xA8] = 10,
[0x8F] = 10,
[0x01] = 10
}
song_name_table = {
[0x40] = "some song",
[0xA8] = "some song 2",
[0x8F] = "some song 3",
[0x01] = "some song 4"
}
|
--- Method customization test.
--
-- 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.
--
-- [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
--
local co1 = require("plugin.customobjects1")
local gg = co1.newScopedGroupObject() -- this is a group, but will send a "willDraw" message to all its children, in
-- order, before it draws, and (in reverse) "didDraw" to all of them afterward
local a1 = co1.newPrintObject(gg) -- print objects are display objects in name only: their culling and hit test logic
-- is dummied out, and their "draw" logic involves printing their `drawMessage`, if one
-- was provided...
a1.drawMessage = "a1:draw" -- ...like so
local a2 = co1.newPrintObject(gg)
a2.willDrawMessage = "a2:willDraw" -- they also listen for "willDraw" and "didDraw" messages (as sent by the scoped
-- group object), and will print the corresponding `*Message`, as provided here...
a2.didDrawMessage = "a2:didDraw" -- ...and here
-- (These print objects might have some utility in debugging, but are mostly intended as a very basic demo of the
-- "custom objects" machinery, i.e. being able to invoke plugin-based behavior within the render hierarchy. More
-- sophisticated use cases will be forthcoming as new features roll out.)
local a3 = co1.newPrintObject(gg)
a3.willDrawMessage = "a3:willDraw"
a3.drawMessage = "a3:draw"
local a4 = co1.newPrintObject(gg)
a4.drawMessage = "a4:draw"
a4.didDrawMessage = "a4:didDraw"
local a5 = co1.newPrintObject(gg)
a5.didDrawMessage = "a5:didDraw"
local a6 = co1.newPrintObject(gg)
a6.willDrawMessage = "a6:willDraw"
a6.drawMessage = "a6:draw"
a6.didDrawMessage = "a6:didDraw"
timer.performWithDelay(20, function()
a2.x = math.random(20, 40) -- alter an arbitrary "geometric" property so that the scene "draws" again
end, 0)
|
object_ship_nova_orion_patrol_med_tier5 = object_ship_shared_nova_orion_patrol_med_tier5:new {
}
ObjectTemplates:addTemplate(object_ship_nova_orion_patrol_med_tier5, "object/ship/nova_orion_patrol_med_tier5.iff")
|
if not HpwRewrite then return end
function HpwRewrite:AddSkin(name, tab)
if not tab.Base then
tab.ShouldSay = false
tab.IsSkin = true
tab.OnSelect = function() return false end
tab.OnFire = tab.OnFire or function() return false end
end
self:AddSpell(name, tab)
end
function HpwRewrite:GetSkin(name)
local skin = self:GetSpell(name)
return (skin and skin.IsSkin) and skin or nil
end
function HpwRewrite:GetPlayerSkin(ply, name)
local spell = self:GetPlayerSpell(ply, name)
return (spell and spell.IsSkin) and spell or nil
end
function HpwRewrite:GetNumOfSkins()
return self.NumOfSkins
end
-- Adding skins
HpwRewrite:IncludeFolder("hpwrewrite/skins", true)
|
fx_version "adamant"
rdr3_warning 'I acknowledge that this is a prerelease build of RedM, and I am aware my resources *will* become incompatible once RedM ships.'
game "rdr3"
description 'littlebot'
-- Server
server_scripts {
'@rdx_core/locale.lua',
'locales/en.lua',
'locales/fr.lua',
'config.lua',
'server/main.lua'
}
-- Client
client_scripts {
'@rdx_core/locale.lua',
'locales/en.lua',
'locales/fr.lua',
'client/main.lua'
}
|
object_tangible_loot_creature_loot_collections_broken_lightsaber_hilt_011 = object_tangible_loot_creature_loot_collections_shared_broken_lightsaber_hilt_011:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_broken_lightsaber_hilt_011, "object/tangible/loot/creature/loot/collections/broken_lightsaber_hilt_011.iff")
|
return {
name = "migration",
fields = {
{ name = { type = "string", required = true } },
{
postgres = {
type = "record", required = true,
fields = {
{ up = { type = "string", len_min = 0 } },
{ teardown = { type = "function" } },
},
},
},
{
cassandra = {
type = "record", required = true,
fields = {
{ up = { type = "string", len_min = 0 } },
{ up_f = { type = "function" } },
{ teardown = { type = "function" } },
},
}
},
},
entity_checks = {
{
at_least_one_of = {
"postgres.up", "postgres.teardown",
"cassandra.up", "cassandra.up_f", "cassandra.teardown"
},
},
},
}
|
local QBCore = exports['qb-core']:GetCoreObject()
-- QBCore.Functions.CreateCallback("insidetrack:server:getbalance", function(source, cb)
-- local Player = QBCore.Functions.GetPlayer(source)
-- local Chips = Player.Functions.GetItemByName("whitechip")
-- if Chips ~= nil then
-- Chips = Chips
-- else
-- return TriggerClientEvent('QBCore:client:closeBets', source)
-- end
-- end)
QBCore.Functions.CreateCallback("insidetrack:server:getbalance", function(source, cb)
local source = source
local Player = QBCore.Functions.GetPlayer(source)
local bankBalance = Player.PlayerData.money["bank"]
local MinAmount = 100
if bankBalance >= MinAmount then
else
return TriggerClientEvent('QBCore:client:closeBets', source)
end
end)
RegisterServerEvent("insidetrack:server:placebet")
AddEventHandler("insidetrack:server:placebet", function(bet)
local Player = QBCore.Functions.GetPlayer(source)
if Player ~= nil then
Player.Functions.RemoveMoney("bank", tonumber(bet), "inside-track-bet")
TriggerClientEvent('QBCore:Notify', source, "Du placerede et væddemål på, "..bet.." DKK")
end
end)
RegisterServerEvent("insidetrack:server:winnings")
AddEventHandler("insidetrack:server:winnings", function(amount)
local Player = QBCore.Functions.GetPlayer(source)
if Player ~= nil then
Player.Functions.AddMoney("bank", tonumber(amount), "inside-track-won")
TriggerClientEvent('QBCore:Notify', source, "Du vandt "..amount.." DKK!")
end
end)
|
lure.dom.computedStyleObj = {}
-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
function lure.dom.createComputedStyleObj(pAttachNode)
local self = {}
--===================================================================
-- OBJECT METATABLE =
--===================================================================
local self_mt = {}
---------------------------------------------------------------------
self_mt.__tostring = function(t)
return "[object]:CssRuleStyleObject"
end
---------------------------------------------------------------------
self_mt.__index = function(t,k)
--print(tostring(t) .. "[" .. tostring(k) .. "]")
if k == "styleRefStore" or
k == "specificity" or
k == "getProperty" or
k == "setProperty" or
k == "parent" then
return rawget(t, k)
else
return rawget(self, 'getProperty')(k)
--return lure.dom.computedStyleObj.getProperty(self, k)
end
end
---------------------------------------------------------------------
self_mt.__newindex = function(t,k,v)
if k == "styleRefStore" or
k == "specificity" or
k == "getProperty" or
k == "setProperty" or
k == "parent" then
rawset(t, k, v)
else
return rawget(t, 'setProperty')(k,v)
--return lure.dom.computedStyleObj.setProperty(self,k,v)
end
end
---------------------------------------------------------------------
--===================================================================
-- PROPERTIES =
--===================================================================
self.parent = pAttachNode
---------------------------------------------------------------------
self.specificity = {0, 0, 0, 0}
---------------------------------------------------------------------
self.styleRefStore = {}
---------------------------------------------------------------------
--====================================================================
-- METHODS =
--====================================================================
self.getStyleText = function()
local cssText = ""
for a=1, table.getn(self.styleRefStore) do
cssText = cssText .. self.styleRefStore[a].key .. ":" .. self.styleRefStore[a].value .. ";"
end
return cssText
end
---------------------------------------------------------------------
self.getProperty = function( pPropertyName )
--print("GETTING PROPERTY: " .. pPropertyName)
local isValidPropertyName = false
local cssDef = nil
local returnValue = ""
for k1, v1 in pairs(lure.dom.cssDefs) do
if pPropertyName == lure.dom.cssDefs[k1].cssToStyle then
cssDef = lure.dom.cssDefs[k1]
isValidPropertyName = true
end
end
if isValidPropertyName then
for a=1, table.getn(self.styleRefStore) do
if self.styleRefStore[a].key == pPropertyName then
return self.styleRefStore[a].value
end
end
return cssDef.initial
else
lure.throw(1, "Cannot get unsupported CSS key '".. pPropertyName .."'")
end
end
---------------------------------------------------------------------
self.setProperty = function( pPropertyName, pPropertyValue )
--print("SETTING PROPERTY: " .. tostring(pPropertyName) .. " with value: " .. tostring(pPropertyValue))
local isValidPropertyName = false
local isValidPropertyValue = false
local cssDef = nil
for k1, v1 in pairs(lure.dom.cssDefs) do
if pPropertyName == lure.dom.cssDefs[k1].cssToStyle then
cssDef = lure.dom.cssDefs[k1]
isValidPropertyName = true
end
end
if isValidPropertyName == true then
if cssDef.validateValue(pPropertyValue) == true then
--if style already exists in the reference store, set it
for a=1, table.getn(self.styleRefStore) do
if self.styleRefStore[a].key == pPropertyName then
self.styleRefStore[a].value = lure.trim(pPropertyValue)
return true
end
end
--else create a new entry in the style reference store
newStyleRef = table.insert(self.styleRefStore,
{
key = lure.trim(pPropertyName),
value = lure.trim(pPropertyValue)
})
else
lure.throw(1, "CSS Definition value '".. pPropertyName .. ":" .. pPropertyValue ..";' is malformed or unsupported. Declaration will be dropped")
end
else
lure.throw(1, "Unsupported CSS key '"..pPropertyName.."' Declaration will be dropped.")
end
end
---------------------------------------------------------------------
setmetatable(self, self_mt)
return self
end
-- ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
include( "slimenu/util.lua" )
include( "menu/mount/mount.lua" ) -- workshop
include( "slimenu/bgstuff.lua" )
include( "menu/getmaps.lua" )
include( "slimenu/sv_loadingurl.lua" )
include( "slimenu/mainmenu.lua" )
include( "slimenu/errors.lua" )
include( "menu/video.lua" )
include( "menu/demo_to_video.lua" )
include( "menu/motionsensor.lua" )
--include( "slimenu/menu_save.lua" )
--include( "slimenu/menu_demo.lua" )
--include( "slimenu/menu_addon.lua" )
--include( "slimenu/menu_dupe.lua" )
--gm11 map stuff
include( "slimenu/map_icon.lua" )
include( "slimenu/map_favorites.lua" )
include( "slimenu/map_options.lua" )
include( "slimenu/maplist_iconview.lua" )
include( "slimenu/maplist_listview.lua" )
include( "slimenu/startgame.lua" )
include( "slimenu/playgame.lua" )
include( "slimenu/interstate_gui.lua" )
--helpers
include( "slimenu/luadata.lua" )
include( "slimenu/table_dump.lua" )
--gui.openurl
include( "menu/openurl.lua" )
print "Loaded SliMenu"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.