content stringlengths 5 1.05M |
|---|
function table_to_string(tbl)
local result = "{"
for k, v in pairs(tbl) do
-- Check the key type (ignore any numerical keys - assume its an array)
if type(k) == "string" then
result = result.."[\""..k.."\"]".."="
end
-- Check the value type
if type(v) == "table" then
result = result..table_to_string(v)
elseif type(v) == "boolean" then
result = result..tostring(v)
elseif type(v) == "number" then
result = result..tostring(v)
elseif v == nil then
result = result.."NIL"
else
result = result.."\""..v.."\""
end
result = result..","
end
-- Remove leading commas from the result
if result ~= "" then
result = result:sub(1, result:len()-1)
end
return result.."}"
end
-- print(myself, table_to_string(colors))
local floor = math.floor
function bxor(a, b)
local r = 0
for i = 0, 31 do
local x = a / 2 + b / 2
if x ~= floor(x) then
r = r + 2^i
end
a = floor(a / 2)
b = floor(b / 2)
end
return r
end
x = 0
for i = 1, 13 do
if i ~= myself then
x = x ~ (colors[i] - 1)
end
end
-- print('x', x)
if myself == 13 then
x2 = 0
for i = 0, 11 do
if (x & (1 << i)) ~= 0 then
x2 = 1 - x2
end
end
my_bool = (x2 ~= 0)
else
bit = x & (1 << (myself - 1))
my_bool = (bit ~= 0)
end
-- print('my_bool', my_bool)
hands = raise(my_bool)
-- print(myself, table_to_string(colors), table_to_string(hands))
answer = 0
for i = 1, 12 do
if myself == i then
else
h = 0
if hands[i] then
h = 1 << (i - 1)
end
a = (x ~ h ~ (colors[i] - 1)) & (1 << (i - 1))
answer = answer | a
end
end
-- print("answer1", answer)
if myself ~= 13 then
a = x ~ (colors[13] - 1) ~ answer
count = 0
for i = 1, 12 do
if (a & (1 << (i - 1))) ~= 0 then
count = 1 - count
end
end
h = 0
if hands[13] then
h = 1
end
if count ~= h then
answer = answer | (1 << (myself - 1))
end
end
answer = answer + 1
-- print("answer2", answer)
|
mPlayers.gui.Stats = {}
mPlayers.gui.Stats.player = nil
function mPlayers.gui.Stats.init()
mPlayers.gui.Stats.window = guiCreateWindow(nil, nil, nil, nil, "Player stats")
local mainVlo = guiCreateVerticalLayout(nil, GS.mrg2 + GS.mrgT, nil, nil, GS.mrg3, false, mPlayers.gui.Stats.window)
guiVerticalLayoutSetHorizontalAlign(mainVlo, "center")
local mainHlo = guiCreateHorizontalLayout(nil, nil, nil, nil, nil, nil, mainVlo)
local vlo = guiCreateVerticalLayout(nil, nil, nil, nil, nil, nil, mainHlo)
guiVerticalLayoutSetHorizontalAlign(vlo, "right")
mPlayers.gui.Stats.statLbls = {}
for i, id in ipairs(getValidPedStatsByGroup("weapon")) do
_, mPlayers.gui.Stats.statLbls[id] =
guiCreateKeyValueLabels(nil, nil, nil, nil, nil, getPedStatShortName(id)..":", nil, nil, vlo)
guiLabelSetClickableStyle(mPlayers.gui.Stats.statLbls[id], true)
guiSetData(mPlayers.gui.Stats.statLbls[id], "stat", id)
end
guiCreateHorizontalSeparator(nil, nil, nil, nil, vlo)
local hlo = guiCreateHorizontalLayout(nil, nil, nil, nil, nil, nil, vlo)
local lbl = guiCreateLabel(nil, nil, nil, nil, "All:", nil, hlo)
guiLabelSetHorizontalAlign(lbl, "right")
mPlayers.gui.Stats.weaponZeroBtn = guiCreateButton(nil, nil, GS.w, nil, "Zero", nil, hlo, "command.setplayerweaponstats")
mPlayers.gui.Stats.weaponFullBtn = guiCreateButton(nil, nil, GS.w, nil, "Full", nil, hlo, "command.setplayerweaponstats")
local vlo = guiCreateVerticalLayout(nil, nil, nil, nil, nil, nil, mainHlo)
for i, id in ipairs(getValidPedStatsByGroup("body")) do
_, mPlayers.gui.Stats.statLbls[id] =
guiCreateKeyValueLabels(nil, nil, nil, GS.w3, nil, getPedStatShortName(id)..":", nil, nil, vlo)
guiLabelSetClickableStyle(mPlayers.gui.Stats.statLbls[id], true)
guiSetData(mPlayers.gui.Stats.statLbls[id], "stat", id)
end
guiCreateHorizontalSeparator(nil, nil, nil, nil, vlo)
for i, id in ipairs(getValidPedStatsByGroup("driving")) do
_, mPlayers.gui.Stats.statLbls[id] =
guiCreateKeyValueLabels(nil, nil, nil, GS.w3, nil, getPedStatShortName(id)..":", nil, nil, vlo)
guiLabelSetClickableStyle(mPlayers.gui.Stats.statLbls[id], true)
guiSetData(mPlayers.gui.Stats.statLbls[id], "stat", id)
end
guiCreateHorizontalSeparator(nil, nil, nil, nil, vlo)
local fightingVlo = guiCreateVerticalLayout(nil, nil, nil, nil, nil, nil, vlo)
guiVerticalLayoutSetHorizontalAlign(fightingVlo, "right")
mPlayers.gui.Stats.fightingLbl, mPlayers.gui.Stats.fightingVLbl =
guiCreateKeyValueLabels(nil, nil, nil, GS.w3, nil, "Fighting:", nil, false, fightingVlo)
mPlayers.gui.Stats.fightingBtn = guiCreateButton(nil, nil, GS.w3, nil, "Set", false, fightingVlo, "command.setplayerfighting")
mPlayers.gui.Stats.fightingList = guiButtonAddComboBox(mPlayers.gui.Stats.fightingBtn)
for i, id in ipairs(getValidFightingStyles()) do
local row = guiGridListAddRow(mPlayers.gui.Stats.fightingList, getFightingStyleName(id))
guiGridListSetItemData(mPlayers.gui.Stats.fightingList, row, 1, id)
end
guiGridListSetSelectedItem(mPlayers.gui.Stats.fightingList, 0)
guiGridListAdjustHeight(mPlayers.gui.Stats.fightingList, 10)
local walkingVlo = guiCreateVerticalLayout(nil, nil, nil, nil, nil, nil, vlo)
guiVerticalLayoutSetHorizontalAlign(walkingVlo, "right")
mPlayers.gui.Stats.walkingLbl, mPlayers.gui.Stats.walkingVLbl =
guiCreateKeyValueLabels(nil, nil, nil, GS.w3, nil, "Walking:", nil, false, walkingVlo)
mPlayers.gui.Stats.walkingBtn = guiCreateButton(nil, nil, GS.w3, nil, "Set", false, walkingVlo, "command.setplayerwalking")
mPlayers.gui.Stats.walkingList = guiButtonAddComboBox(mPlayers.gui.Stats.walkingBtn)
for i, id in ipairs(getValidWalkingStyles()) do
local row = guiGridListAddRow(mPlayers.gui.Stats.walkingList, getWalkingStyleName(id))
guiGridListSetItemData(mPlayers.gui.Stats.walkingList, row, 1, id)
end
guiGridListSetSelectedItem(mPlayers.gui.Stats.walkingList, 0)
guiGridListAdjustHeight(mPlayers.gui.Stats.walkingList, 10)
guiGridListSetAutoSearchEdit(mPlayers.gui.Stats.walkingList, guiGridListCreateSearchEdit(mPlayers.gui.Stats.walkingList))
hlo = guiCreateHorizontalLayout(nil, nil, nil, nil, nil, nil, mainVlo)
mPlayers.gui.Stats.okBtn = guiCreateButton(nil, nil, nil, nil, "Ok", nil, hlo)
guiRebuildLayouts(mPlayers.gui.Stats.window)
local w, h = guiGetSize(mainVlo, false)
guiSetSize(mPlayers.gui.Stats.window, w + GS.mrg2*2, h + GS.mrg2*2 + GS.mrgT, false)
guiCenter(mPlayers.gui.Stats.window)
----------------------------------------------
addEventHandler("onClientPlayerQuit", root, mPlayers.gui.Stats.onQuit)
addEventHandler("onClientGUIRender", mPlayers.gui.Stats.window, mPlayers.gui.Stats.refresh, false)
addEventHandler("onClientGUILeftClick", mPlayers.gui.Stats.window, mPlayers.gui.Stats.onClick)
return true
end
function mPlayers.gui.Stats.term()
removeEventHandler("onClientPlayerQuit", root, mPlayers.gui.Stats.onQuit)
destroyElement(mPlayers.gui.Stats.window)
return true
end
function mPlayers.gui.Stats.show(player)
mPlayers.gui.Stats.player = player
guiSetText(mPlayers.gui.Stats.window, getPlayerName(player, true).."'s stats")
mPlayers.gui.Stats.refresh()
return guiSetVisible(mPlayers.gui.Stats.window, true, true)
end
function mPlayers.gui.Stats.hide()
return guiSetVisible(mPlayers.gui.Stats.window, false)
end
function mPlayers.gui.Stats.onQuit()
if source ~= mPlayers.gui.Stats.player then return end
if not guiGetVisible(mPlayers.gui.Stats.window) then return end
mPlayers.gui.Stats.hide()
guiShowMessageDialog("Player leave the game", nil, MD_OK, MD_INFO)
end
function mPlayers.gui.Stats.onClick()
if source == mPlayers.gui.Stats.okBtn then
return mPlayers.gui.Stats.hide()
elseif source == mPlayers.gui.Stats.fightingBtn then
return cCommands.execute("setplayerfighting", mPlayers.gui.Stats.player, guiGridListGetSelectedItemData(mPlayers.gui.Stats.fightingList))
elseif source == mPlayers.gui.Stats.walkingBtn then
return cCommands.execute("setplayerwalking", mPlayers.gui.Stats.player, guiGridListGetSelectedItemData(mPlayers.gui.Stats.walkingList))
elseif source == mPlayers.gui.Stats.weaponZeroBtn then
return cCommands.execute("setplayerweaponstats", mPlayers.gui.Stats.player, 0)
elseif source == mPlayers.gui.Stats.weaponFullBtn then
return cCommands.execute("setplayerweaponstats", mPlayers.gui.Stats.player, 1000)
end
local id = guiGetData(source, "stat")
if not id then return end
local value = guiShowInputDialog("Set health", "Enter the health value", guiGetText(source), guiGetInputNumericParser(true, 0, 1000), false, guiGetInputNumericMatcher(true, 0, 1000))
if not value then return end
cCommands.execute("setplayerstat", mPlayers.gui.Stats.player, id, value)
end
function mPlayers.gui.Stats.refresh()
for stat, label in pairs(mPlayers.gui.Stats.statLbls) do
guiSetText(label, getPedStat(mPlayers.gui.Stats.player, stat))
end
local fighting = getPedFightingStyle(mPlayers.gui.Stats.player)
guiSetText(mPlayers.gui.Stats.fightingVLbl, formatNameID(getFightingStyleName(fighting), fighting))
local walking = getPedWalkingStyle(mPlayers.gui.Stats.player)
guiSetText(mPlayers.gui.Stats.walkingVLbl, formatNameID(getWalkingStyleName(walking), walking))
return true
end |
function VolumeToVectorFunc(property)
local vm = require("VolumeToVector")()
vm:DivideNumber(property.divideNum[1], property.divideNum[2], property.divideNum[3])
vm:Create(property.srcvolume)
return vm
end
|
local old_NAD_init = UpgradesTweakData._init_pd2_values
function UpgradesTweakData:_init_pd2_values(tweak_data)
old_NAD_init(self, tweak_data)
self.values.player.body_armor = {
armor = {
15,
15,
15,
15,
15,
15,
15
},
movement = {
1.05,
1.05,
1.05,
1.05,
1.05,
1.05,
1.05
},
concealment = {
30,
26,
23,
21,
18,
12,
1
},
dodge = {
10000,
10000,
10000,
10000,
10000,
10000,
10000
},
damage_shake = {
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5
},
stamina = {
1.025,
1.025,
1.025,
1.025,
1.025,
1.025,
1.025
},
skill_ammo_mul = {
1,
1.02,
1.04,
1.06,
1.8,
1.1,
1.12
}
}
end
|
ModLoader.SetupFileHook( "lua/Utility.lua", "lua/ThirdPerson/Utility.lua", "post" )
ModLoader.SetupFileHook( "lua/Globals.lua", "lua/ThirdPerson/Globals.lua", "post" )
ModLoader.SetupFileHook( "lua/Alien.lua", "lua/ThirdPerson/Alien.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/BiteLeap.lua", "lua/ThirdPerson/BiteLeap.lua", "post" )
ModLoader.SetupFileHook( "lua/Skulk.lua", "lua/ThirdPerson/Skulk.lua", "post" )
ModLoader.SetupFileHook( "lua/Gorge.lua", "lua/ThirdPerson/Gorge.lua", "post" )
ModLoader.SetupFileHook( "lua/Babbler.lua", "lua/ThirdPerson/Babbler.lua", "post" )
ModLoader.SetupFileHook( "lua/Lerk.lua", "lua/ThirdPerson/Lerk.lua", "post" )
ModLoader.SetupFileHook( "lua/Fade.lua", "lua/ThirdPerson/Fade.lua", "post" )
ModLoader.SetupFileHook( "lua/Onos.lua", "lua/ThirdPerson/Onos.lua", "post" )
ModLoader.SetupFileHook( "lua/Onos_Client.lua", "lua/ThirdPerson/Onos_Client.lua", "post" )
ModLoader.SetupFileHook( "lua/Player.lua", "lua/ThirdPerson/Player.lua", "post" )
ModLoader.SetupFileHook( "lua/Player_Client.lua", "lua/ThirdPerson/Player_Client.lua", "post" )
ModLoader.SetupFileHook( "lua/GUICrosshair.lua", "lua/ThirdPerson/GUICrosshair.lua", "post" )
ModLoader.SetupFileHook( "lua/GUIAlienHUD.lua", "lua/ThirdPerson/GUIAlienHUD.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/SpitSpray.lua", "lua/ThirdPerson/SpitSpray.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/SpikesMixin.lua", "lua/ThirdPerson/SpikesMixin.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/Parasite.lua", "lua/ThirdPerson/Parasite.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/BileBomb.lua", "lua/ThirdPerson/BileBomb.lua", "post" )
ModLoader.SetupFileHook( "lua/Weapons/Alien/Blink.lua", "lua/ThirdPerson/Blink.lua", "post" )
|
--
-- Pauser class.
--
-- @filename LgPauser.lua
-- @copyright Copyright (c) 2015 Yaukey/yaukeywang/WangYaoqi (yaukeywang@gmail.com) all rights reserved.
-- @license The MIT License (MIT)
-- @author Yaukey
-- @date 2015-09-01
--
local DLog = YwDebug.Log
local DLogWarn = YwDebug.LogWarning
local DLogError = YwDebug.LogError
local Time = Time
local Input = Input
local KeyCode = KeyCode
-- Register new class LgPauser.
local strClassName = "LgPauser"
local LgPauser = YwDeclare(strClassName, YwClass(strClassName, YwMonoBehaviour))
-- Member variables.
-- Pause or not.
LgPauser.m_bPaused = false
-- Awake method.
function LgPauser:Awake()
--print("LgPauser:Awake")
end
-- Virtual.
-- Update.
function LgPauser:Update()
--print("LgPauser:Update")
if Input.GetKeyUp(KeyCode.P) then
self.m_bPaused = not self.m_bPaused
end
if self.m_bPaused then
Time.timeScale = 0
else
Time.timeScale = 1
end
end
-- Return this class.
return LgPauser
|
require 'nn'
local GaussianCriterion, parent = torch.class('nn.GaussianCriterion', 'nn.Criterion')
function GaussianCriterion:updateOutput(input, target)
-- negative LL, so sign is flipped
-- log(sigma) + 0.5 *(2pi)) + 0.5 * (x - mu)^2/sigma^2
-- input[1] = mu
-- input[2] = log(sigma^2)
local Gelement = torch.mul(input[2],0.5):add(0.5 * math.log(2 * math.pi))
Gelement:add(torch.add(target,-1,input[1]):pow(2):cdiv(torch.exp(input[2])):mul(0.5))
self.output = torch.sum(Gelement)
return self.output
end
function GaussianCriterion:updateGradInput(input, target)
self.gradInput = {}
-- - (x - mu) / sigma^2 --> (1 / sigma^2 = exp(-log(sigma^2)) )
self.gradInput[1] = torch.exp(-input[2]):cmul(torch.add(target,-1,input[1])):mul(-1)
-- 0.5 - 0.5 * (x - mu)^2 / sigma^2
self.gradInput[2] = torch.exp(-input[2]):cmul(torch.add(target,-1,input[1]):pow(2)):mul(-0.5):add(0.5)
return self.gradInput
end |
local make
make = function()
local grid = {
tile_scale = 24
}
grid.draw = function(self)
do
local _with_0 = game.camera
love.graphics.setLineWidth(1 / _with_0.sx)
love.graphics.setColor(0, 0, 0)
local offset = _with_0:left() % game.tile_scale
for i = 0, _with_0:width() / game.tile_scale do
local x1, y1 = _with_0:left() - offset + i * game.tile_scale, _with_0:top()
local x2, y2 = x1, _with_0:bot()
love.graphics.line(x1, y1, x2, y2)
end
offset = _with_0:top() % game.tile_scale
for i = 0, _with_0:height() / game.tile_scale do
local x1, y1 = _with_0:left(), _with_0:top() - offset + i * game.tile_scale
local x2, y2 = _with_0:right(), y1
love.graphics.line(x1, y1, x2, y2)
end
return _with_0
end
end
grid.draw_highlight = function(self)
if game.bar.current then
do
local _with_0 = love.graphics
_with_0.setColor(1, 1, 1)
local mouse_x = game.camera:left() + love.mouse.getX() / game.camera.sx
local mouse_y = game.camera:top() + love.mouse.getY() / game.camera.sy
_with_0.draw(game.bar.current.sprite, mouse_x - mouse_x % self.tile_scale, mouse_y - mouse_y % self.tile_scale)
return _with_0
end
end
end
return grid
end
return {
make = make
}
|
local generator = require "zenbones.specs"
local bg = vim.opt.background:get()
local p = require("zenwritten.palette")[bg]
return generator.generate(p, bg, generator.get_global_config("zenwritten", bg))
|
-- WRAPPER FUNCTION FOR REQUIRE [BEGIN] --------------------------------------
return function(global)
print "[LOAD] -> shared/Helpers/Logger"
-- PRIVATE DATA AND HELPER FUNCTIONS [BEGIN] ---------------------------------
local Assert = global.Assert
local ERR_INVALID_SELF = "Class method was invoked as a function"
local LOG_LEVEL = {
NONE = 0,
FATAL = 1,
CRITICAL = 2,
ERROR = 3,
WARN = 4,
INFO = 5,
VERBOSE = 6,
DEBUG = 7,
}
local PREFIX = {
[LOG_LEVEL.FATAL] = 'FATAL',
[LOG_LEVEL.CRITICAL] = 'CRITICAL',
[LOG_LEVEL.ERROR] = 'ERROR',
[LOG_LEVEL.WARN] = 'WARN',
[LOG_LEVEL.INFO] = 'INFO',
[LOG_LEVEL.VERBOSE] = 'INFO+',
[LOG_LEVEL.DEBUG] = 'DEBUG',
}
local fnNoOp = function() end
local function getDefaultLogLevel()
local defaults = global.defaults or {}
local level = defaults.logLevel
if type(level) == 'string' then
level = LOG_LEVEL[string.upper(level)]
end
return level or LOG_LEVEL.ERROR
end
local function getLogLevel(level)
if type(level) == 'string' then
level = LOG_LEVEL[string.upper(level)]
end
return level
end
local function defaultLogFn(level, isWarn, ...)
if isWarn then
warn(...)
else
print(...)
end
end
local function getPrefixForLevel(level, isWarn)
local prefix = PREFIX[level]
if isWarn and level ~= LOG_LEVEL.WARN then
prefix = prefix .. "(WARN)"
end
return prefix or ""
end
local function log(self, msgLevel, isWarn, ...)
local triggerLevel = not isWarn and self.level or
math.max(self.level, self.warnLevel)
msgLevel = msgLevel == nil and LOG_LEVEL.NONE or
math.min(msgLevel, LOG_LEVEL.DEBUG)
if msgLevel <= LOG_LEVEL.NONE or msgLevel > triggerLevel then
return
end
local name = self.name and ("{" .. self.name .. "}: ") or ""
local prefix = "[" .. getPrefixForLevel(msgLevel, isWarn) .. "] "
self.logFn(msgLevel, isWarn, prefix .. name, ...)
end
-- PRIVATE DATA AND HELPER FUNCTIONS [END] -----------------------------------
-- CLASS DEFINITION [BEGIN] --------------------------------------------------
local class = {
NONE = LOG_LEVEL.NONE,
FATAL = LOG_LEVEL.FATAL,
CRITICAL = LOG_LEVEL.CRITICAL,
ERROR = LOG_LEVEL.ERROR,
INFO = LOG_LEVEL.INFO,
VERBOSE = LOG_LEVEL.VERBOSE,
DEBUG = LOG_LEVEL.DEBUG,
}
function isClass(self)
return self and self._class and self._class == class or false
end
function class.getNullLogger()
return {
fatal = fnNoOp,
critical = fnNoOp,
error = fnNoOp,
warn = fnNoOp,
info = fnNoOp,
verbose = fnNoOp,
debug = fnNoOp,
}
end
function class:critical(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.CRITICAL, true, ...)
end
function class:debug(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.DEBUG, false, ...)
end
function class:error(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.ERROR, true, ...)
end
function class:fatal(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.FATAL, true, ...)
end
function class:info(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.INFO, false, ...)
end
function class:verbose(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.VERBOSE, false, ...)
end
function class:warn(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.WARN, true, ...)
end
function class:warnDebug(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.DEBUG, true, ...)
end
function class:warnInfo(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.INFO, true, ...)
end
function class:warnVerbose(...)
Assert(isClass(self), ERR_INVALID_SELF, 2)
log(self, LOG_LEVEL.VERBOSE, true, ...)
end
function class:new(config)
Assert(self == class, ERR_INVALID_SELF, 2)
local obj = { _class = class }
setmetatable(obj, self)
self.__index = self
config = config or {}
obj.level = getLogLevel(config.level) or getDefaultLogLevel()
obj.warnLevel = getLogLevel(config.warnLevel) or obj.level
obj.logFn = config.logFn or defaultLogFn
obj.name = config.name
return obj
end
print "[LOAD] <- shared/Helpers/Logger"
return class
-- CLASS DEFINITION [END] ----------------------------------------------------
end
-- WRAPPER FUNCTION FOR REQUIRE [END] ---------------------------------------- |
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2014, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { popen = io.popen }
local setmetatable = setmetatable
local string = { match = string.match }
-- }}}
-- nvsmi: provides GPU information from nvidia SMI
-- vicious.contrib.nvsmi
local nvsmi_all = {}
-- {{{ GPU Information widget type
local function worker(format, warg)
-- Fallback to querying first device
if not warg then warg = "0" end
-- Get data from smi
-- * Todo: support more; MEMORY,UTILIZATION,ECC,POWER,CLOCK,COMPUTE,PIDS,PERFORMANCE
local f = io.popen("nvidia-smi -q -d TEMPERATURE -i " .. warg)
local smi = f:read("*all")
f:close()
-- Not installed
if smi == nil then return {0} end
-- Get temperature information
local _thermal = string.match(smi, "Gpu[%s]+:[%s]([%d]+)[%s]C")
-- Handle devices without data
if _thermal == nil then return {0} end
return {tonumber(_thermal)}
end
-- }}}
return setmetatable(nvsmi_all, { __call = function(_, ...) return worker(...) end })
|
local s = require 'string'
function handle_simple(r)
-- r:addoutputfilter("wombathood")
r:puts("added wombathood")
end |
function init()
reset()
end
function step()
-- increase counter
counter = counter + 1
-- for counter < 50, just go straight with gripper locked
-- this way, as soon as you get the cylinder, it sticks to the gripper
-- the object is actually reached after 32 steps, so initially the robot pushes the object forwards
-- when 50 <= counter < 100 go backwards while gripping the cylinder
-- when counter >= 100 release the object and keep going backwards
if counter == 50 then
robot.wheels.set_velocity(-5, -5)
elseif counter == 100 then
robot.gripper.unlock()
end
end
function reset()
counter = 0
robot.gripper.lock_positive()
robot.wheels.set_velocity(5, 5)
end
function destroy()
end
|
local cfg = {}
cfg.lang = "da"
-- define customization parts
local parts = {
["Ansigt"] = -1,
["Pletter"] = 0,
["Skæg"] = 1,
["Øjenbryn"] = 2,
["Alderdom"] = 3,
["Makeup"] = 4,
["Blush"] = 5,
["Hudfarve"] = 6,
["Hud"] = 7,
["Læbestift"] = 8,
["Fregner"] = 9,
["Brysthår"] = 10,
["Kropspletter"] = 11,
["Hår"] = 12
}
-- changes prices (any change to the character parts add amount to the total price)
cfg.drawable_change_price = 20
cfg.texture_change_price = 5
cfg.barbershops_title = "Barbershop"
-- skinshops list {parts,x,y,z}
cfg.barbershops = {
{parts,-815.59008789063,-182.16806030273,37.568920135498},
--{parts,449.88708496094,-993.13946533203,30.689584732056},
{parts,139.21583557129,-1708.9689941406,29.301620483398},
{parts,-1281.9802246094,-1119.6861572266,7.0001249313354},
{parts,1934.115234375,3730.7399902344,32.854434967041},
{parts,1211.0759277344,-475.00064086914,66.218032836914},
{parts,-34.97777557373,-150.9037322998,57.086517333984},
{parts,-280.37301635742,6227.017578125,31.705526351929}
}
return cfg
|
-- LCD
--
-- LICENCE: http://opensource.org/licenses/MIT
-- 2016-10-27 tschaban https://github.com/tschaban
local module = {}
disp = nil
local function writeToLCD(l)
disp:setFont(u8g.font_6x10)
disp:drawStr(0, 10, l[1])
disp:drawStr(2, 24, l[2])
disp:drawStr(2, 34, l[3])
disp:drawStr(2, 34, l[4])
disp:setFont(u8g.font_chikita)
disp:drawLine(0, 47, 128, 47)
disp:drawStr(0, 55, l[5])
disp:drawStr(0, 55, l[6])
end
function module.display(t)
disp:firstPage()
repeat
writeToLCD(t)
until disp:nextPage() == false
end
function module.start()
i2c.setup(0, config.SDA, config.SCL, i2c.SLOW)
disp = u8g.ssd1306_128x64_i2c(0x3c)
end
return module |
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
ZO_SharedSmithingResearch = ZO_Object:Subclass()
function ZO_SharedSmithingResearch:New(...)
local smithingResearch = ZO_Object.New(self)
smithingResearch:Initialize(...)
return smithingResearch
end
function ZO_SharedSmithingResearch:Initialize(control, owner, slotContainerName)
self.control = control
self.owner = owner
self.timer = ZO_TimerBar:New(control:GetNamedChild("TimerBar"))
self.timer:SetDirection(TIMER_BAR_COUNTS_DOWN)
self.timer:SetTimeFormatParameters(TIME_FORMAT_STYLE_COLONS, TIME_FORMAT_PRECISION_TWELVE_HOUR)
self.slotPool = ZO_ControlPool:New(slotContainerName, self.control)
local function HandleDirtyEvent()
self:HandleDirtyEvent()
end
local function OnResearchComplete(eventId, craftingType, researchLineIndex, traitIndex)
local cancelDialog = ZO_Dialogs_FindDialog("CONFIRM_CANCEL_RESEARCH")
if cancelDialog then
local data = cancelDialog.data
if data.craftingType == craftingType and data.researchLineIndex == researchLineIndex and data.traitIndex == traitIndex then
ZO_Dialogs_ReleaseDialog("CONFIRM_CANCEL_RESEARCH")
end
end
self:HandleDirtyEvent()
end
self.control:RegisterForEvent(EVENT_SMITHING_TRAIT_RESEARCH_COMPLETED, OnResearchComplete)
self.control:RegisterForEvent(EVENT_SMITHING_TRAIT_RESEARCH_CANCELED, HandleDirtyEvent)
self.dirty = true
end
function ZO_SharedSmithingResearch:SetSavedVars(savedVars)
self.savedVars = savedVars
end
function ZO_SharedSmithingResearch:ChangeTypeFilter(filterData)
self.typeFilter = filterData.descriptor
self:HandleDirtyEvent()
end
function ZO_SharedSmithingResearch:SetCraftingType(craftingType, oldCraftingType, isCraftingTypeDifferent)
if isCraftingTypeDifferent or not self.typeFilter then
self:RefreshAvailableFilters()
end
end
local MIN_SCALE = .6
local MAX_SCALE = 1.0
local BASE_NUM_ITEMS_IN_LIST = 5
function ZO_SharedSmithingResearch:InitializeResearchLineList(scollListClass, listSlotContainerName)
local listContainer = self.control:GetNamedChild("ResearchLineList")
listContainer.titleLabel:SetText(GetString(SI_SMITHING_RESEARCH_LINE_HEADER))
listContainer.selectedLabel:SetColor(ZO_SELECTED_TEXT:UnpackRGBA())
listContainer.extraInfoLabel:SetColor(self:GetExtraInfoColor())
local function CountNumResearchableTraits(data)
if not data.researchingTraitIndex and data.itemTraitCounts and not data.areAllTraitsKnown then
local researchableCount = 0
for traitIndex in pairs(data.itemTraitCounts) do
researchableCount = researchableCount + 1
end
return researchableCount
end
return 0
end
local function SetupFunction(control, data, selected, selectedDuringRebuild)
control.timerIcon:SetHidden(selected or not data.researchingTraitIndex)
local researchableCount = CountNumResearchableTraits(data)
if selected then
self.traitLineText = zo_strformat(SI_SMITHING_RESEARCH_TRAIT_NAME_FORMAT, data.name)
listContainer.selectedLabel:SetText(self.traitLineText)
self.isResearchingTrait = false
self:ShowTraitsFor(data)
if data.researchingTraitIndex then
local durationSecs, timeRemainingSecs = GetSmithingResearchLineTraitTimes(data.craftingType, data.researchLineIndex, data.researchingTraitIndex)
if durationSecs and timeRemainingSecs then
local now = GetFrameTimeSeconds()
local timeElapsed = durationSecs - timeRemainingSecs
self.timer:Start(now - timeElapsed, now + timeRemainingSecs)
listContainer.extraInfoLabel:SetHidden(true)
end
else
self.timer:Stop()
listContainer.extraInfoLabel:SetHidden(false)
if data.areAllTraitsKnown then
listContainer.extraInfoLabel:SetText(GetString(SI_SMITHING_RESEARCH_ALL_RESEARCHED))
else
if researchableCount > 0 then
listContainer.extraInfoLabel:SetText(self:GetResearchTimeString(researchableCount, ZO_FormatTime(data.timeRequiredForNextResearchSecs, TIME_FORMAT_STYLE_COLONS, TIME_FORMAT_PRECISION_TWELVE_HOUR)))
else
listContainer.extraInfoLabel:SetText(GetString(SI_SMITHING_RESEARCH_NO_TRAITS_RESEARCHABLE))
end
end
end
end
ZO_ItemSlot_SetAlwaysShowStackCount(control, researchableCount > 0)
ZO_ItemSlot_SetupSlot(control, researchableCount, data.icon)
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
end
local function EqualityFunction(leftData, rightData)
return leftData.craftingType == rightData.craftingType and leftData.researchLineIndex == rightData.researchLineIndex
end
self.researchLineList = scollListClass:New(listContainer.listControl, listSlotContainerName, BASE_NUM_ITEMS_IN_LIST, SetupFunction, EqualityFunction)
listContainer:RegisterForEvent(EVENT_SMITHING_TRAIT_RESEARCH_TIMES_UPDATED, function() self.researchLineList:RefreshVisible() end)
local highlightTexture = listContainer.highlightTexture
self.researchLineList:SetSelectionHighlightInfo(highlightTexture, highlightTexture and highlightTexture.pulseAnimation)
self.researchLineList:SetScaleExtents(MIN_SCALE, MAX_SCALE)
ZO_CraftingUtils_ConnectHorizontalScrollListToCraftingProcess(self.researchLineList)
end
function ZO_SharedSmithingResearch:OnControlsAcquired()
-- Subclasses must implement this function if needed.
self.owner:OnResearchSlotChanged()
end
function ZO_SharedSmithingResearch:HandleDirtyEvent()
if self.control:IsHidden() then
self.dirty = true
else
self:Refresh()
end
end
local function GetTraitIndexForItem(bagId, slotIndex, craftingType, researchLineIndex, numTraits)
for traitIndex = 1, numTraits do
if CanItemBeSmithingTraitResearched(bagId, slotIndex, craftingType, researchLineIndex, traitIndex) then
return traitIndex
end
end
return nil
end
function ZO_SharedSmithingResearch:GenerateResearchTraitCounts(virtualInventoryList, craftingType, researchLineIndex, numTraits)
local counts
for itemId, itemInfo in pairs(virtualInventoryList) do
local traitIndex = GetTraitIndexForItem(itemInfo.bag, itemInfo.index, craftingType, researchLineIndex, numTraits)
if traitIndex then
counts = counts or {}
counts[traitIndex] = (counts[traitIndex] or 0) + 1
end
end
return counts
end
function ZO_SharedSmithingResearch:FindResearchingTraitIndex(craftingType, researchLineIndex, numTraits)
local areAllTraitsKnown = true
for traitIndex = 1, numTraits do
local traitType, _, known = GetSmithingResearchLineTraitInfo(craftingType, researchLineIndex, traitIndex)
if not known then
areAllTraitsKnown = false
local durationSecs = GetSmithingResearchLineTraitTimes(craftingType, researchLineIndex, traitIndex)
if durationSecs then
return traitIndex, areAllTraitsKnown
end
end
end
return nil, areAllTraitsKnown
end
do
local function DoesNotBlockResearch(bagId, slotIndex)
return not IsItemPlayerLocked(bagId, slotIndex) and GetItemTraitInformation(bagId, slotIndex) ~= ITEM_TRAIT_INFORMATION_RETRAITED and GetItemTraitInformation(bagId, slotIndex) ~= ITEM_TRAIT_INFORMATION_RECONSTRUCTED
end
function ZO_SharedSmithingResearch.IsResearchableItem(bagId, slotIndex, craftingType, researchLineIndex, traitIndex)
return CanItemBeSmithingTraitResearched(bagId, slotIndex, craftingType, researchLineIndex, traitIndex)
and DoesNotBlockResearch(bagId, slotIndex)
end
function ZO_SharedSmithingResearch:Refresh()
self.dirty = false
self.researchLineList:Clear()
local craftingType = GetCraftingInteractionType()
local numCurrentlyResearching = 0
local virtualInventoryList = PLAYER_INVENTORY:GenerateListOfVirtualStackedItems(INVENTORY_BACKPACK, DoesNotBlockResearch)
if self.savedVars.includeBankedItemsChecked then
PLAYER_INVENTORY:GenerateListOfVirtualStackedItems(INVENTORY_BANK, DoesNotBlockResearch, virtualInventoryList)
end
for researchLineIndex = 1, GetNumSmithingResearchLines(craftingType) do
local name, icon, numTraits, timeRequiredForNextResearchSecs = GetSmithingResearchLineInfo(craftingType, researchLineIndex)
if numTraits > 0 then
local researchingTraitIndex, areAllTraitsKnown = self:FindResearchingTraitIndex(craftingType, researchLineIndex, numTraits)
if researchingTraitIndex then
numCurrentlyResearching = numCurrentlyResearching + 1
end
local expectedTypeFilter = ZO_CraftingUtils_GetSmithingFilterFromTrait(GetSmithingResearchLineTraitInfo(craftingType, researchLineIndex, 1))
if expectedTypeFilter == self.typeFilter then
local itemTraitCounts = self:GenerateResearchTraitCounts(virtualInventoryList, craftingType, researchLineIndex, numTraits)
local data = { craftingType = craftingType, researchLineIndex = researchLineIndex, name = name, icon = icon, numTraits = numTraits, timeRequiredForNextResearchSecs = timeRequiredForNextResearchSecs, researchingTraitIndex = researchingTraitIndex, areAllTraitsKnown = areAllTraitsKnown, itemTraitCounts = itemTraitCounts }
self.researchLineList:AddEntry(data)
end
end
end
self.researchLineList:Commit()
local maxResearchable = GetMaxSimultaneousSmithingResearch(craftingType)
if numCurrentlyResearching >= maxResearchable then
self.atMaxResearchLimit = true
else
self.atMaxResearchLimit = false
end
self:RefreshCurrentResearchStatusDisplay(numCurrentlyResearching, maxResearchable)
if self.activeRow then
self:OnResearchRowActivate(self.activeRow)
end
end
end
function ZO_SharedSmithingResearch:RefreshCurrentResearchStatusDisplay(currentlyResearching, maxResearchable)
--Overridden in derived classes
end
function ZO_SharedSmithingResearch:ShowTraitsFor(data)
self.slotPool:ReleaseAllObjects()
local craftingType, researchLineIndex, numTraits = data.craftingType, data.researchLineIndex, data.numTraits
-- store these to get access to them on refresh()
self.craftingType = craftingType
self.researchLineIndex = researchLineIndex
self.numTraits = numTraits
local currentAnchor = ZO_Anchor:New(TOPLEFT, self.control:GetNamedChild("TraitContainer"))
local stride = 1
local OFFSET_Y = 2
for traitIndex = 1, numTraits do
local traitType, _, known = GetSmithingResearchLineTraitInfo(craftingType, researchLineIndex, traitIndex)
local durationSecs, timeRemainingSecs = GetSmithingResearchLineTraitTimes(craftingType, researchLineIndex, traitIndex)
local slotControl = self.slotPool:AcquireObject()
slotControl.owner = self
slotControl.craftingType = craftingType
slotControl.researchLineIndex = researchLineIndex
slotControl.traitIndex = traitIndex
slotControl.researchable = false
slotControl.nameLabel:SetText(GetString("SI_ITEMTRAITTYPE", traitType))
slotControl.traitType = traitType
slotControl.traitDescription, slotControl.traitResearchSourceDescription, slotControl.traitMaterialSourceDescription = GetSmithingResearchLineTraitDescriptions(craftingType, researchLineIndex, traitIndex)
if slotControl.traitResearchSourceDescription == "" then
slotControl.traitResearchSourceDescription = nil
slotControl.traitMaterialSourceDescription = nil
end
local icon = select(3, GetSmithingTraitItemInfo(traitType + 1))
ZO_ItemSlot_SetupSlot(slotControl, 1, icon)
self:SetupTraitDisplay(slotControl, data, known, durationSecs, traitIndex)
ZO_Anchor_BoxLayout(currentAnchor, slotControl, traitIndex - 1, stride, 0, OFFSET_Y, slotControl:GetWidth(), slotControl:GetHeight(), 0, 0)
end
-- Let any subclasses know that slotpool controls have been released/acquired.
self:OnControlsAcquired()
end
function ZO_SharedSmithingResearch:ActivateHighlight(row)
if not row.fadeAnimation then
row.fadeAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("ShowOnMouseOverLabelAnimation", row:GetNamedChild("Highlight"))
row.scaleAnimation = ANIMATION_MANAGER:CreateTimelineFromVirtual("IconSlotMouseOverAnimation", row.icon)
end
row.fadeAnimation:PlayForward()
row.scaleAnimation:PlayForward()
end
function ZO_SharedSmithingResearch:DeactivateHighlight(row)
if row.fadeAnimation then
row.fadeAnimation:PlayBackward()
row.scaleAnimation:PlayBackward()
end
end
function ZO_SharedSmithingResearch:OnResearchRowActivate(row)
self:SetupTooltip(row)
self.activeRow = row
if self.keybindStripDescriptor then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
else
self.owner:OnResearchSlotChanged()
end
end
function ZO_SharedSmithingResearch:OnResearchRowDeactivate(row)
self:ClearTooltip(row)
self.activeRow = nil
if self.keybindStripDescriptor then
KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
else
self.owner:OnResearchSlotChanged()
end
end
function ZO_SharedSmithingResearch:IsResearchable()
return (self.activeRow ~= nil) and self.activeRow.researchable and self:CanResearchCurrentTraitLine()
end
function ZO_SharedSmithingResearch:IsResearching()
if self.activeRow then
local activeRow = self.activeRow
local durationSecs, timeRemainingSecs = GetSmithingResearchLineTraitTimes(activeRow.craftingType, activeRow.researchLineIndex, activeRow.traitIndex)
return durationSecs ~= nil
end
return false
end
function ZO_SharedSmithingResearch:GetSelectedData()
return self.researchLineList:GetSelectedData()
end
ZO_SharedSmithingResearchSelect = ZO_Object:Subclass()
function ZO_SharedSmithingResearchSelect:New(...)
local researchSelect = ZO_Object.New(self)
researchSelect:Initialize(...)
return researchSelect
end
function ZO_SharedSmithingResearchSelect:Initialize(control)
self.control = control
end
function ZO_SharedSmithingResearch:CanResearchCurrentTraitLine()
local canResearchCurrentTraitLine = true
for traitIndex = 1, self.numTraits do
local durationSecs, timeRemainingSecs = GetSmithingResearchLineTraitTimes(self.craftingType, self.researchLineIndex, traitIndex)
if durationSecs then
canResearchCurrentTraitLine = false
break
end
end
return canResearchCurrentTraitLine
end
function ZO_SharedSmithingResearch:CanCancelResearch()
return self.numTraits and not self:CanResearchCurrentTraitLine()
end
function ZO_SharedSmithingResearch:CancelResearch()
local dialogData = {}
dialogData.craftingType = self.craftingType
dialogData.researchLineIndex = self.researchLineIndex
local dialogParams = {}
local researchingTrait = self:FindResearchingTraitIndex(self.craftingType, self.researchLineIndex, self.numTraits)
local traitType, _, known = GetSmithingResearchLineTraitInfo(self.craftingType, self.researchLineIndex, researchingTrait)
local researchLineName = GetSmithingResearchLineInfo(self.craftingType, self.researchLineIndex)
dialogData.traitIndex = researchingTrait
dialogParams.mainTextParams = { researchLineName, GetString("SI_ITEMTRAITTYPE", traitType), GetString(SI_PERFORM_ACTION_CONFIRMATION) }
local dialogName = IsInGamepadPreferredMode() and ZO_GAMEPAD_CONFIRM_CANCEL_RESEARCH_DIALOG or "CONFIRM_CANCEL_RESEARCH"
ZO_Dialogs_ShowPlatformDialog(dialogName, dialogData, dialogParams)
end |
local MainTable = { }
local bug = {}
local myBitch = {}
blips = {}
local localTexts = {
{ "Don't shoot me, just get what you need!" },
{ "Please dont kill me i have kids" },
{ "I'm begging you leave me alone" },
{ "Calm down dude!!" },
{ "Take the money and leave!!" },
{ "No problem take the cash and leave" },
{ "I won't call cops just leave!" },
}
addEvent("syncPeds", true)
function setPeds ( peds )
for i, v in ipairs ( peds ) do
addEventHandler("onClientPedDamage", v, function () cancelEvent() end )
end
end
addEventHandler("syncPeds", root, setPeds)
addEventHandler( "onClientProjectileCreation", root,
function ( creator )
if ( getElementData ( localPlayer, "isPlayerRobbingStore" ) ) then
if ( getProjectileType( source ) == 16 ) or ( getProjectileType( source ) == 17 ) or ( getProjectileType( source ) == 18 ) or ( getProjectileType( source ) == 39 ) then
if ( creator == localPlayer ) then
exports.NGCdxmsg:createNewDxMessage("You can't use explosions while you are robbing store",255,0,0)
end
destroyElement( source )
end
end
end
)
addEventHandler("onClientExplosion", root,
function(x, y, z, theType)
if (getElementData(localPlayer, "isPlayerRobbingStore")) then
cancelEvent()
end
end)
addEvent("synceStoresBlips",true)
addEventHandler("synceStoresBlips",root,function(x,y,v,types)
if types == "robbed" then
if blips[v] then
exports.customblips:destroyCustomBlip(blips[v])
blips[v] = nil
end
if blips[v] == nil or blips[v] == false then
blips[v] = exports.customblips:createCustomBlip( x,y,18,18,"robbed.png",1000)
end
else
if blips[v] then
exports.customblips:destroyCustomBlip(blips[v])
blips[v] = nil
end
if blips[v] == nil or blips[v] == false then
blips[v] = exports.customblips:createCustomBlip( x,y,18,18,"norobbed.png",1000)
end
end
end)
addEvent("addServerMsg", true)
function msg(player,msg)
if player == localPlayer then
exports.NGCdxmsg:createNewDxMessage( msg,255,255,0)
end
end
addEventHandler("addServerMsg", root, msg)
addEvent("checkForPlayerAim", true)
function checkAim ( actionType, ped )
if ( source ~= localPlayer ) then return end
if exports.DENlaw:isLaw(localPlayer) then return end
if not ( isPedAiming ( source ) ) then return end
if ( actionType == "newRob" ) then
triggerServerEvent( "startStoreRob", localPlayer, ped )
elseif ( actionType == "joinRob" ) then
triggerServerEvent( "addPlayerToStoreRob", localPlayer, ped )
end
end
addEventHandler("checkForPlayerAim", root, checkAim)
addEvent("startStoreRob", true)
function startStoreRob ( player, ped )
-- Tell the player he started a store rob
myBitch = ped
if ( localPlayer == player ) then
exports.NGCdxmsg:createNewDxMessage( "Watch out police found you, hurry up",255,255,0)
end
-- Warn the police -- law check
if exports.DENlaw:isLaw(localPlayer) then
local zone = getElementData(player,"shopName") or "Unknown"
exports.killMessages:outputMessage( "(Robbery:["..getPlayerName(player).."]) is robbing a store in ["..zone.."] Please respond!" , 0, 100, 200,"default-bold" )
end
MainTable [#MainTable +1 ] = { ped, math.random ( #localTexts ) }
setHandsUpAnimation ( ped )
addEventHandler( "onClientElementStreamIn", ped, setHandsUpAnimation )
setTimer ( function () setCoverAnimation(ped) removeEventHandler( "onClientElementStreamIn", ped, setHandsUpAnimation ) addEventHandler( "onClientElementStreamIn", ped, setCoverAnimation ) end, 60000, 1)
setTimer( function () removeEventHandler( "onClientElementStreamIn", ped, setCoverAnimation ) setPedAnimation ( ped ) MainTable[#MainTable] = nil end, 90000, 1)
--[[bug[player] = setTimer(function(player,ped)
if player == localPlayer then
if getElementData(localPlayer,"isPlayerArrested") or getElementData(localPlayer,"isPlayerJailed") then
triggerServerEvent("abortStoreRobbery",player,ped)
setPedAnimation ( ped )
MainTable[#MainTable] = nil
end
end
end,5000,0,player,ped)]]
end
addEventHandler("startStoreRob", root, startStoreRob)
addEventHandler("onClientPlayerQuit",localPlayer,function()
if myBitch then
if getElementType(myBitch) == "ped" then
triggerServerEvent("abortStoreRobbery",localPlayer,myBitch)
setPedAnimation ( myBitch )
MainTable[#MainTable] = nil
end
end
end)
addEvent("endTheRobbery",true)
addEventHandler("endTheRobbery",root,function(gay)
--[[if isTimer(bug[gay]) then
killTimer(bug[gay])
end
setPedAnimation ( myBitch )
MainTable[#MainTable] = nil]]
end)
addEvent("addPlayerToStoreRob", true)
function addPlayerToStoreRob ( player, ped )
if ( player == localPlayer ) then
exports.NGCdxmsg:createNewDxMessage( "You have joined the robbery!",255,255,0)
exports.NGCdxmsg:createNewDxMessage( "Watch out police found you, hurry up",255,255,0)
end
end
addEventHandler("addPlayerToStoreRob", root, addPlayerToStoreRob)
function setHandsUpAnimation ( ped )
if ( ped ) then
setPedAnimation( ped, "ped", "handsup", -1, false, true, false )
else
setPedAnimation( source, "ped", "handsup", -1, false, true, false )
end
end
function setCoverAnimation ( ped )
if ( ped ) then
setPedAnimation( ped, "ped", "cower", -1, false, false, false )
else
setPedAnimation( source, "ped", "cower", -1, false, false, false )
end
end
function drawTextBubble ()
for i=1, #MainTable do
drawText (MainTable[i][1], localTexts[MainTable[i][2]][1] )
end
end
addEventHandler( "onClientRender", root, drawTextBubble )
function drawText (ped, text) --- local chat for ped
if ( isElement( ped ) ) then
local camPosXl, camPosYl, camPosZl = getPedBonePosition (ped, 6)
local camPosXr, camPosYr, camPosZr = getPedBonePosition (ped, 7)
local x,y,z = (camPosXl + camPosXr) / 2, (camPosYl + camPosYr) / 2, (camPosZl + camPosZr) / 2
local cx,cy,cz = getCameraMatrix()
local px,py,pz = getElementPosition(ped)
local distance = getDistanceBetweenPoints3D(cx,cy,cz,px,py,pz)
local posx,posy = getScreenFromWorldPosition(x,y,z+0.020*distance+0.10)
local elementtoignore1 = getPedOccupiedVehicle(localPlayer) or localPlayer
local elementtoignore2 = getPedOccupiedVehicle(ped) or ped
if posx and distance <= 10 then --and ( isLineOfSightClear(cx,cy,cz,px,py,pz,true,true,false,true,false,true,true,elementtoignore1) or isLineOfSightClear(cx,cy,cz,px,py,pz,true,true,false,true,false,true,true,elementtoignore2) ) then -- change this when multiple ignored elements can be specified
local width = dxGetTextWidth(text,1,"default-bold")
dxDrawRectangle(posx - (3 + (0.5 * width)),posy - (2 + (0 * 20)),width + 5,19,tocolor(0,0,0,180))
dxDrawRectangle(posx - (6 + (0.5 * width)),posy - (2 + (0 * 20)),width + 11,19,tocolor(0,0,0,0))
dxDrawRectangle(posx - (8 + (0.5 * width)),posy - (1 + (0 * 20)),width + 15,17,tocolor(0,0,0,180))
dxDrawRectangle(posx - (10 + (0.5 * width)),posy - (1 + (0 * 20)),width + 19,17,tocolor(0,0,0,0))
dxDrawRectangle(posx - (10 + (0.5 * width)),posy - (0 * 20) + 1,width + 19,13,tocolor(0,0,0,180))
dxDrawRectangle(posx - (12 + (0.5 * width)),posy - (0 * 20) + 1,width + 23,13,tocolor(0,0,0,0))
dxDrawRectangle(posx - (12 + (0.5 * width)),posy - (0 * 20) + 4,width + 23,7,tocolor(0,0,0,180))
local r,g,b = 255, 255, 255
dxDrawText(text,posx - (0.5 * width),posy - (0 * 20),posx - (0.5 * width),posy - (0 * 20),tocolor(r,g,b,255),1,"default","left","top",false,false,false)
end
end
end
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 createObjectXD(id,x,y,z,r1,r2,r3)
ob = createObject(id,x+50,y-1280,z-70,r1,r2,r3)
end
electronic = {
createObjectXD(14665,1008.4794922,52.2343750,56.3064880,0.0000000,0.0000000,0.0000000),
createObjectXD(1885,1004.6247559,50.3856125,54.2721100,0.0000000,0.0000000,0.0000000),
createObjectXD(1984,1006.7548218,54.0209923,54.2971115,0.0000000,0.0000000,179.1900024),
createObjectXD(2362,1006.3051758,54.2991333,55.2432251,0.0000000,0.0000000,0.0000000),
createObjectXD(2412,1004.0183716,53.5260582,54.3039436,0.0000000,0.0000000,270.6749878),
createObjectXD(2412,1004.0288086,50.2197037,54.3039436,0.0000000,0.0000000,270.6701660),
createObjectXD(2413,1013.7285156,56.2158203,54.3221130,0.0000000,0.0000000,270.3570557),
createObjectXD(2413,1013.7324219,54.6181641,54.3221130,0.0000000,0.0000000,270.3515625),
createObjectXD(2413,1013.7228394,53.0205879,54.3221130,0.0000000,0.0000000,270.3570557),
createObjectXD(2413,1013.7186890,51.3954086,54.3221130,0.0000000,0.0000000,270.3570557),
createObjectXD(2434,1010.0641479,46.3796768,54.3221130,0.0000000,0.0000000,0.0000000),
createObjectXD(2434,1010.2570190,47.4814415,54.3221130,0.0000000,0.0000000,87.3400269),
createObjectXD(2435,1009.1736450,46.3890839,54.3221130,0.0000000,0.0000000,359.8650208),
createObjectXD(2435,1009.1673584,47.6749496,54.3221130,0.0000000,0.0000000,180.6350098),
createObjectXD(2434,1008.2761230,47.6777840,54.3221130,0.0000000,0.0000000,178.6458740),
createObjectXD(2434,1008.0795288,46.5666695,54.3221130,0.0000000,0.0000000,269.9531250),
createObjectXD(2403,1008.9747925,46.5289078,54.2776146,0.0000000,0.0000000,274.6449890),
createObjectXD(2403,1008.9617920,46.5310745,55.4526863,0.0000000,0.0000000,274.6417236),
createObjectXD(2403,1008.3417969,46.3994408,55.4526863,0.0000000,0.0000000,183.3318481),
createObjectXD(2403,1008.3327637,46.3761139,54.2776146,0.0000000,0.0000000,183.3288574),
createObjectXD(2125,1004.6339722,55.0986481,54.6319885,0.0000000,0.0000000,0.0000000),
createObjectXD(1954,1013.5696411,51.3743973,54.6597404,0.0000000,0.0000000,90.0000000),
createObjectXD(1954,1013.5821533,53.9690971,54.6459961,0.0000000,0.0000000,89.5499878),
createObjectXD(3031,1012.8862915,62.2839432,55.8758659,0.0000000,0.0000000,246.2249756),
createObjectXD(1958,1013.5943604,51.5306091,55.3887711,0.0000000,0.0000000,0.0000000),
createObjectXD(1429,1013.6365967,46.3349495,56.3798904,0.0000000,0.0000000,260.7498779),
createObjectXD(1429,1006.4923706,42.1512146,56.3798904,0.0000000,0.0000000,157.5299072),
createObjectXD(2199,1013.8822632,48.2886086,54.3003883,0.0000000,0.0000000,270.6750488),
createObjectXD(2606,1013.8779297,53.5292969,56.6978226,0.0000000,0.0000000,270.6701660),
createObjectXD(5061,1003.0541382,57.7564011,56.2347412,0.0000000,0.0000000,0.0000000),
createObjectXD(5061,1003.0595703,62.0073624,56.2347412,0.0000000,0.0000000,0.0000000),
createObjectXD(5061,1003.0671997,46.8307076,55.9383430,0.0000000,0.0000000,0.0000000),
createObjectXD(1500,1003.0399780,52.2242203,54.3221130,0.0000000,0.0000000,270.6750488),
createObjectXD(1500,1003.0323486,53.7181969,54.3221130,0.0000000,0.0000000,270.6701660),
createObjectXD(1717,1009.8856201,48.0408173,54.8026466,0.0000000,0.0000000,131.1450195),
createObjectXD(1718,1013.6285400,55.5106926,55.3983002,0.0000000,0.0000000,272.6599731),
createObjectXD(1719,1013.2874146,55.9926186,54.7288246,0.0000000,0.0000000,270.6749878),
createObjectXD(1747,1007.8092651,41.5473137,54.9531212,0.0000000,0.0000000,175.3549805),
createObjectXD(1747,1012.5316772,43.2827911,54.9531212,0.0000000,0.0000000,230.9328003),
createObjectXD(1748,1005.0981445,42.7660332,56.1534081,0.0000000,0.0000000,143.4600220),
createObjectXD(1749,1009.3641357,46.6539764,55.3776817,0.0000000,0.0000000,0.0000000),
createObjectXD(1750,1011.2998047,42.4236717,56.1682625,0.0000000,0.0000000,208.5999756),
createObjectXD(1750,1009.8143921,41.7151947,54.9431877,0.0000000,0.0000000,194.7023926),
createObjectXD(1752,1009.9076538,41.7565651,56.1142426,0.0000000,0.0000000,190.5999908),
createObjectXD(1782,1012.4247437,43.6100502,55.9046211,0.0000000,0.0000000,224.6599731),
createObjectXD(1785,1005.3237305,43.0170898,55.6203232,0.0000000,0.0000000,318.3150024),
createObjectXD(1786,1004.1694336,43.9782066,56.1349716,0.0000000,0.0000000,119.4600220),
createObjectXD(1786,1013.5067749,44.8412704,56.1099701,0.0000000,0.0000000,246.8598633),
createObjectXD(1787,1013.1893311,44.8238487,55.9302940,0.0000000,0.0000000,248.3450012),
createObjectXD(1788,1006.5707397,42.2083511,55.0128174,0.0000000,0.0000000,157.4000244),
createObjectXD(1791,1004.1968994,44.1510811,54.9364395,0.0000000,0.0000000,121.4450073),
createObjectXD(1792,1012.7001343,43.3814087,56.0590973,358.0149841,0.0000000,226.5549927),
createObjectXD(1792,1008.0020142,41.5137100,56.0590973,358.0114746,0.0000000,172.9595337),
createObjectXD(1809,1008.0253296,47.1051102,55.3776817,0.0000000,0.0000000,272.3450012),
createObjectXD(1839,1010.1583252,47.1698723,55.3776817,0.0000000,0.0000000,180.5849915),
createObjectXD(1840,1013.4704590,46.4118309,54.9729385,0.0000000,0.0000000,0.0000000),
createObjectXD(1840,1013.4637451,45.9141388,54.9729385,0.0000000,0.0000000,346.1050110),
createObjectXD(2028,1013.5832520,56.2304077,55.4471893,0.0000000,0.0000000,270.3150635),
createObjectXD(2099,1003.3759766,47.4767799,54.3221130,0.0000000,0.0000000,91.6700134),
createObjectXD(2101,1003.8056030,45.6420326,56.0989380,0.0000000,0.0000000,105.5650024),
createObjectXD(2102,1013.6087646,52.6799202,55.3638573,0.0000000,0.0000000,270.3150024),
createObjectXD(2103,1013.5890503,54.3064728,55.3388557,0.0000000,0.0000000,270.4949951),
createObjectXD(2104,1014.0087280,49.2585297,54.3221130,0.0000000,0.0000000,270.3150024),
createObjectXD(2190,1013.8237305,50.5631752,55.3501701,0.0000000,0.0000000,268.5100098),
createObjectXD(2224,1004.1817627,48.3079109,54.3221130,0.0000000,0.0000000,43.6700134),
createObjectXD(2226,1013.4945679,52.7093544,54.5289917,0.0000000,0.0000000,270.6749878),
createObjectXD(2229,1013.7427979,58.6054649,54.3291931,0.0000000,0.0000000,266.7049866),
createObjectXD(2230,1013.7711792,59.1908340,54.2721100,0.0000000,0.0000000,270.6749878),
createObjectXD(2231,1013.7285156,59.8327141,54.2971115,0.0000000,0.0000000,270.4949951),
createObjectXD(2232,1013.5407715,60.8724823,54.8949890,0.0000000,0.0000000,268.4199829),
createObjectXD(2344,1008.5733032,47.8057442,55.3877602,0.0000000,0.0000000,0.0000000),
createObjectXD(2596,1003.5746460,53.8849106,57.2668457,0.0000000,0.0000000,91.5350037),
createObjectXD(14391,1006.7827148,62.3941193,55.2571945,0.0000000,0.0000000,268.5100098),
createObjectXD(14604,1010.7539673,61.8809052,55.3027573,0.0000000,0.0000000,179.2800293),
createObjectXD(16377,1011.8562012,61.8767014,55.2774429,0.0000000,0.0000000,179.3699951),
createObjectXD(1208,1003.6091309,59.8825073,54.3221130,0.0000000,0.0000000,270.4500122),
createObjectXD(16779,1009.0192261,56.2055931,58.4543648,0.0000000,0.0000000,0.0000000),
createObjectXD(16779,1008.6109619,50.1057396,58.4543648,0.0000000,0.0000000,0.0000000),
createObjectXD(2413,1003.5005493,58.2491875,54.3221130,0.0000000,0.0000000,89.5411377),
createObjectXD(2413,1003.5000000,56.6432648,54.3221130,0.0000000,0.0000000,89.5385742),
createObjectXD(2413,1013.7235107,57.8048553,54.3221130,0.0000000,0.0000000,270.3570557),
createObjectXD(2966,1003.6441040,58.0296898,54.9149132,0.0000000,0.0000000,91.3100281),
createObjectXD(2966,1003.6490479,56.6213989,54.9149132,0.0000000,0.0000000,91.3073730),
createObjectXD(2966,1003.6578369,59.1584167,54.9149132,0.0000000,0.0000000,91.3073730),
createObjectXD(2967,1003.5950928,58.5664291,54.8752518,0.0000000,0.0000000,87.3400269),
createObjectXD(2967,1003.5338745,56.9595757,54.8752518,0.0000000,0.0000000,87.3358154),
createObjectXD(2967,1003.5602417,57.3573494,54.8752518,0.0000000,0.0000000,87.3358154),
createObjectXD(2422,1005.6001587,54.3313026,55.2182236,0.0000000,0.0000000,17.8649902),
createObjectXD(2495,1006.1470947,53.5040398,55.0382385,0.0000000,0.0000000,0.0000000),
createObjectXD(2593,1006.7326660,53.9906158,56.0951347,0.0000000,0.0000000,0.0000000),
createObjectXD(2506,1006.8340454,53.7432518,56.2746773,0.0000000,0.0000000,0.0000000),
createObjectXD(2506,1006.6600952,54.2892380,56.2746773,0.0000000,0.0000000,179.1900024),
createObjectXD(2506,1007.0347900,54.1379623,56.2746773,0.0000000,0.0000000,95.2800293),
createObjectXD(2506,1006.4329834,53.9479752,56.2746773,0.0000000,0.0000000,270.6749878),
}
----***
-- 1302,-1180,-58
function createShopObject(id,x,y,z,r1,r2,r3)
obs = createObject(id,x-1500,y-3800,z-70,r1,r2,r3)
setElementDoubleSided(obs,true)
end
realstickshop = {
createShopObject(18030,2802.109,2620.933,12.193,0.0,0.0,0.0),
createShopObject(18070,2782.433,2619.959,10.325,0.0,0.0,90.000),
createShopObject(1514,2784.205,2618.506,11.101,0.0,0.0,90.000),
createShopObject(2579,2813.864,2619.096,10.953,0.0,0.0,-90.000),
createShopObject(2578,2813.864,2620.404,10.946,0.0,0.0,-90.000),
createShopObject(2698,2794.642,2624.052,10.771,0.0,0.0,0.0),
createShopObject(18092,2813.760,2623.897,10.325,0.0,0.0,90.000),
createShopObject(2752,2813.365,2626.209,10.826,0.0,0.0,-56.250),
createShopObject(2752,2813.355,2625.763,10.801,0.0,0.0,-23.591),
createShopObject(2751,2813.435,2625.262,10.872,0.0,0.0,-67.500),
createShopObject(2750,2813.275,2624.915,10.812,-79.068,0.0,-112.500),
createShopObject(2750,2813.252,2624.369,10.812,-79.068,0.0,-112.500),
createShopObject(2749,2813.543,2623.558,10.826,0.0,0.0,-225.000),
createShopObject(2624,2782.408,2632.253,11.501,0.0,0.0,89.218),
createShopObject(2381,2789.293,2634.478,10.514,0.0,0.0,0.0),
createShopObject(2372,2788.668,2634.309,9.802,0.0,0.0,-90.000),
createShopObject(2372,2791.298,2634.305,9.834,0.0,0.0,-90.000),
createShopObject(2382,2791.454,2634.488,10.528,0.0,0.0,-87.344),
createShopObject(2382,2792.436,2634.435,10.556,0.0,0.0,-87.344),
createShopObject(2389,2798.351,2634.687,11.424,0.0,0.0,0.0),
createShopObject(2389,2797.760,2634.705,11.453,0.0,0.0,0.0),
createShopObject(2383,2797.061,2634.687,11.455,0.0,0.0,-90.000),
createShopObject(2374,2796.229,2634.761,11.467,0.0,0.0,0.0),
createShopObject(2394,2801.087,2634.500,10.558,0.0,0.0,0.0),
createShopObject(2372,2800.499,2634.344,9.827,0.0,0.0,-90.000),
createShopObject(2054,2813.380,2621.793,10.839,0.0,0.0,-135.000),
createShopObject(2053,2813.422,2622.325,10.885,0.0,0.0,0.0),
createShopObject(2500,2780.632,2622.895,10.833,0.0,0.0,180.000),
createShopObject(18092,2813.731,2611.334,10.283,0.0,0.0,90.963),
createShopObject(2486,2813.443,2613.482,10.799,0.0,0.0,-78.750),
createShopObject(2484,2813.426,2609.906,11.468,0.0,0.0,-90.000),
createShopObject(2485,2813.427,2611.003,10.829,0.0,0.0,-101.250),
createShopObject(2460,2796.372,2616.617,9.620,0.0,0.0,0.0),
createShopObject(2460,2796.527,2625.963,9.820,0.0,0.0,0.0),
createShopObject(2496,2795.111,2616.116,11.886,0.0,0.0,0.0),
createShopObject(2494,2799.085,2616.103,11.781,0.0,0.0,0.0),
createShopObject(2507,2813.838,2611.735,11.565,0.0,0.0,-90.000),
createShopObject(1852,2796.399,2616.529,10.892,0.0,0.0,0.0),
createShopObject(1853,2797.176,2616.550,10.735,0.0,0.0,0.0),
createShopObject(1859,2797.778,2616.592,10.713,0.0,0.0,0.0),
createShopObject(18092,2780.474,2611.100,10.325,0.0,0.0,270.585),
createShopObject(18553,2796.982,2607.354,11.118,0.0,0.0,-90.000),
createShopObject(1518,2780.753,2609.161,11.081,0.0,0.0,112.500),
createShopObject(1719,2780.762,2609.968,10.880,0.0,0.0,-270.000),
createShopObject(1782,2780.749,2610.767,10.909,0.0,0.0,90.000),
createShopObject(1786,2780.373,2611.882,10.818,0.0,0.0,90.000),
createShopObject(1840,2782.079,2607.623,10.823,0.0,0.0,-128.675),
createShopObject(18092,2784.307,2607.711,10.325,0.0,0.0,0.826),
createShopObject(1839,2782.792,2607.733,10.823,0.0,0.0,-90.000),
createShopObject(2028,2783.587,2607.949,10.909,0.0,0.0,-180.000),
createShopObject(2101,2780.717,2613.090,10.829,0.0,0.0,-270.000),
createShopObject(2226,2784.421,2607.981,10.824,0.0,0.0,-180.000),
createShopObject(2232,2787.407,2608.714,10.423,0.0,0.0,-180.000),
createShopObject(2628,2808.064,2633.255,9.820,0.0,0.0,0.0),
createShopObject(2627,2809.884,2633.294,9.826,0.0,0.0,0.0),
createShopObject(2630,2811.249,2633.407,9.820,0.0,0.0,0.0),
createShopObject(2718,2818.470,2617.595,12.199,0.0,0.0,-93.679),
createShopObject(2826,2784.324,2622.709,10.836,0.0,0.0,-213.750),
createShopObject(2824,2784.394,2621.642,10.835,0.0,0.0,78.750),
createShopObject(2855,2783.716,2623.164,10.836,0.0,0.0,168.750),
createShopObject(1778,2818.348,2612.063,10.043,0.0,0.0,0.0),
createShopObject(2192,2813.100,2623.047,10.775,0.0,0.0,-247.500),
createShopObject(1433,2816.833,2620.150,10.174,0.0,0.0,0.0),
createShopObject(1663,2817.900,2620.258,10.505,0.0,0.0,-90.000),
createShopObject(1491,2816.293,2618.467,9.915,0.0,0.0,0.0),
}
function createDSObject(id,x,y,z,r1,r2,r3)
obs2 = createObject(id,x+2810,y-4000,z-70,r1,r2,r3)
setElementDoubleSided(obs2,true)
end
ds = {
createDSObject ( 14665, -1946.5, 2378, 9.8, 0, 0, 22 ),
createDSObject ( 1491, -1950.80005, 2374.59009, 7.8, 0, 0, 114 ),
createDSObject ( 1491, -1952, 2377.36963, 7.8, 0, 0, 291.995 ),
createDSObject ( 2367, -1949.09998, 2388.3999, 7.8, 0, 0, 21.995 ),
createDSObject ( 2367, -1953.30005, 2386.69995, 7.8, 0, 0, 21.995 ),
createDSObject ( 2367, -1944.59998, 2387.30005, 7.8, 0, 0, 293.995 ),
createDSObject ( 2367, -1942.69995, 2382.6001, 7.8, 0, 0, 291.995 ),
createDSObject ( 2367, -1940.90002, 2378, 7.8, 0, 0, 291.995 ),
createDSObject ( 2367, -1939.19995, 2373.80005, 7.8, 0, 0, 291.995 ),
createDSObject ( 2367, -1939.59998, 2369.30005, 7.8, 0, 0, 201.995 ),
createDSObject ( 2367, -1943.59998, 2367.69995, 7.8, 0, 0, 203.99 ),
createDSObject ( 1313, -1952.59998, 2386.5, 8.25, 0, 0, 22 ),
createDSObject ( 1575, -1953.09973, 2386.51953, 8.7, 0, 0, 22 ),
createDSObject ( 1575, -1952.20044, 2386.88989, 8.66, 0, 0, 22 ),
createDSObject ( 1314, -1948.30005, 2388.19995, 8.2, 0, 0, 22 ),
createDSObject ( 1254, -1944.40002, 2367.8999, 8.3, 0, 0, 30 ),
createDSObject ( 1241, -1940.30005, 2369.5, 8.24, 0, 0, 26 ),
createDSObject ( 1240, -1939.40002, 2373.1001, 8.301, 0, 0, 300 ),
createDSObject ( 1248, -1941.19995, 2377.30005, 8.27, 0, 0, 292 ),
createDSObject ( 1318, -1944.80005, 2386.57007, 8.28, 0, 0, 24 ),
createDSObject ( 2891, -1942.88, 2382.50098, 8.62, 0, 0, 18 ),
createDSObject ( 2891, -1942.40637, 2381.48486, 8.65, 0, 0, 22 ),
createDSObject ( 1279, -1946, 2389.30005, 7.9, 0, 0, 22 ),
createDSObject ( 1279, -1937.80005, 2370.1001, 7.901 ),
createDSObject ( 1279, -1945.59998, 2388.6001, 7.9 ),
createDSObject ( 1576, -1948.92432, 2388.30103, 8.63598, 0, 0, 20 ),
createDSObject ( 1576, -1947.97559, 2388.67993, 8.63598, 0, 0, 22 ),
createDSObject ( 1577, -1944.73755, 2387.10522, 8.63598, 0, 0, 290 ),
createDSObject ( 1577, -1944.29956, 2386.20996, 8.63598, 0, 0, 112 ),
createDSObject ( 1241, -1942.94995, 2381.8999, 8.2, 0, 0, 122 ),
createDSObject ( 1578, -1939.36951, 2373.69019, 8.63598, 0, 0, 114 ),
createDSObject ( 1578, -1939, 2372.68994, 8.63598, 0, 0, 112 ),
createDSObject ( 1579, -1941.05005, 2377.82983, 8.63598, 0, 0, 114 ),
createDSObject ( 1579, -1940.66003, 2376.89014, 8.63598, 0, 0, 112 ),
createDSObject ( 1580, -1939.77002, 2369.39941, 8.63598, 0, 0, 18 ),
createDSObject ( 1580, -1940.79004, 2369.00488, 8.63598, 0, 0, 22 ),
createDSObject ( 1575, -1943.80005, 2367.90967, 8.63598, 0, 0, 22 ),
createDSObject ( 1575, -1944.69946, 2367.51001, 8.63598, 0, 0, 12 ),
createDSObject ( 1279, -1943.5, 2384.3999, 7.89, 0, 0, 314 ),
createDSObject ( 1279, -1950.5, 2387.69995, 7.89 ),
createDSObject ( 1279, -1942.09998, 2380.5, 7.9, 0, 0, 158 ),
createDSObject ( 1279, -1941.5, 2378.8999, 7.89, 0, 0, 311.995 ),
createDSObject ( 1279, -1939.90002, 2375.3999, 7.89, 0, 0, 99 ),
createDSObject ( 1279, -1938.19995, 2371.19995, 7.89, 0, 0, 98.998 ),
createDSObject ( 1279, -1942.19995, 2368.5, 7.89 ),
createDSObject ( 1279, -1946.19995, 2366.8999, 7.9 ),
createDSObject ( 3383, -1944.5, 2373.80005, 7.6, 0, 0, 112 ),
createDSObject ( 3383, -1947.80005, 2381.6001, 7.6, 0, 0, 111.995 ),
createDSObject ( 1279, -1948.19995, 2382.69995, 8.7 ),
createDSObject ( 1279, -1947.59998, 2381.8999, 8.7, 0, 0, 298 ),
createDSObject ( 1575, -1948.40002, 2381.69995, 8.7, 0, 0, 355.995 ),
createDSObject ( 1577, -1947.90002, 2380.80005, 8.7, 0, 0, 273 ),
createDSObject ( 1279, -1944, 2372.30005, 8.7, 0, 0, 207.999 ),
createDSObject ( 1575, -1945, 2375.1001, 8.7 ),
createDSObject ( 1579, -1944.59998, 2374.19995, 8.7, 0, 0, 111.995 ),
createDSObject ( 1578, -1944.19995, 2373.3999, 8.7, 0, 0, 97.995 ),
createDSObject ( 2891, -1944.90002, 2373.69995, 8.7, 0, 0, 21.995 ),
}
function dxDrawBorderedText( text, x, y, w, h, color, scale, font, alignX, alignY, clip, wordBreak, postGUI )
dxDrawText ( text, x - 1, y - 1, w - 1, h - 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false ) -- black
dxDrawText ( text, x + 1, y - 1, w + 1, h - 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x - 1, y + 1, w - 1, h + 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x + 1, y + 1, w + 1, h + 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x - 1, y, w - 1, h, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x + 1, y, w + 1, h, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x, y - 1, w, h - 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x, y + 1, w, h + 1, tocolor ( 0, 0, 0, 255 ), scale, font, alignX, alignY, clip, wordBreak, false )
dxDrawText ( text, x, y, w, h, color, scale, font, alignX, alignY, clip, wordBreak, postGUI )
end
tick = 0
addEventHandler("onClientRender",getRootElement(),function ()
for i,v in ipairs(getElementsByType("marker",resourceRoot)) do
if getElementDimension(localPlayer) == 0 then
local name = getElementData(v,"shopName")
if name then
local x,y,z = getElementPosition(v)
local x2,y2,z2 = getElementPosition(localPlayer)
local cx,cy,cz = getCameraMatrix()
if getDistanceBetweenPoints3D(cx,cy,cz,x,y,z) <= 25 then
local px,py = getScreenFromWorldPosition(x,y,z+1.3,0.06)
if px then
if z2 <= z+4 then
local width = dxGetTextWidth(name,1,"sans")
local r,g,b = getMarkerColor(v)
-- tick = tick + 1
dxDrawBorderedText("Store Robbery\n"..name, px, py, px, py, tocolor(255, 255, 255, 255), 2, "sans", "center", "center", false, false)
if r == 255 then
setMarkerColor(v,0,100,200,150)
else
setMarkerColor(v,255,0,0,150)
end
end
end
end
end
end
end
end)
|
local patch_id = "ON_CARD_PREUPGRADE"
if rawget(_G, patch_id) then
return
end
rawset(_G, patch_id, true)
print("Loaded patch:"..patch_id)
local old_fn = CardEngine.Card.UpgradeCard
function CardEngine.Card:UpgradeCard(...)
if not self.engine then
TheGame:BroadcastEvent("on_pre_card_upgrade", self, ...)
end
return old_fn(self, ...)
end
|
-- @docclass table
function table.dump(t, depth)
if not depth then depth = 0 end
for k, v in pairs(t) do
str = (' '):rep(depth * 2) .. k .. ': '
if type(v) ~= 'table' then
print(str .. tostring(v))
else
print(str)
table.dump(v, depth + 1)
end
end
end
function table.clear(t) for k, v in pairs(t) do t[k] = nil end end
function table.copy(t)
local res = {}
for k, v in pairs(t) do res[k] = v end
return res
end
function table.recursivecopy(t)
local res = {}
for k, v in pairs(t) do
if type(v) == 'table' then
res[k] = table.recursivecopy(v)
else
res[k] = v
end
end
return res
end
function table.selectivecopy(t, keys)
local res = {}
for i, v in ipairs(keys) do res[v] = t[v] end
return res
end
function table.merge(t, src) for k, v in pairs(src) do t[k] = v end end
function table.find(t, value, lowercase)
for k, v in pairs(t) do
if lowercase and type(value) == 'string' and type(v) == 'string' then
if v:lower() == value:lower() then return k end
end
if v == value then return k end
end
end
function table.findbykey(t, key, lowercase)
for k, v in pairs(t) do
if lowercase and type(key) == 'string' and type(k) == 'string' then
if k:lower() == key:lower() then return v end
end
if k == key then return v end
end
end
function table.contains(t, value, lowercase) return table.find(t, value, lowercase) ~= nil end
function table.findkey(t, key)
if t and type(t) == 'table' then for k, v in pairs(t) do if k == key then return k end end end
end
function table.haskey(t, key) return table.findkey(t, key) ~= nil end
function table.removevalue(t, value)
for k, v in pairs(t) do
if v == value then
table.remove(t, k)
return true
end
end
return false
end
function table.popvalue(value)
local index = nil
for k, v in pairs(t) do if v == value or not value then index = k end end
if index then
table.remove(t, index)
return true
end
return false
end
function table.compare(t, other)
if #t ~= #other then return false end
for k, v in pairs(t) do if v ~= other[k] then return false end end
return true
end
function table.empty(t)
if t and type(t) == 'table' then return next(t) == nil end
return true
end
function table.permute(t, n, count)
n = n or #t
for i = 1, count or n do
local j = math.random(i, n)
t[i], t[j] = t[j], t[i]
end
return t
end
function table.findbyfield(t, fieldname, fieldvalue)
for _i, subt in pairs(t) do if subt[fieldname] == fieldvalue then return subt end end
return nil
end
function table.size(t)
local size = 0
for i, n in pairs(t) do size = size + 1 end
return size
end
function table.tostring(t)
local maxn = #t
local str = ''
for k, v in pairs(t) do
v = tostring(v)
if k == maxn and k ~= 1 then
str = str .. ' and ' .. v
elseif maxn > 1 and k ~= 1 then
str = str .. ', ' .. v
else
str = str .. ' ' .. v
end
end
return str
end
function table.collect(t, func)
local res = {}
for k, v in pairs(t) do
local a, b = func(k, v)
if a and b then
res[a] = b
elseif a ~= nil then
table.insert(res, a)
end
end
return res
end
function table.equals(t, comp)
if type(t) == 'table' and type(comp) == 'table' then
for k, v in pairs(t) do if v ~= comp[k] then return false end end
end
return true
end
|
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/UnrestrictedGrabSpace.lua#1 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/UnrestrictedGrabSpace.lua $
--
-- Original Author: James Yarrow
--
-- $Author: Andre_Arsenault $
--
-- $Change: 37816 $
--
-- $DateTime: 2006/02/15 15:33:33 $
--
-- $Revision: #1 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
--A plan to rapidly grab space control that bypasses timing restrictions on AI attacks.
require("pgtaskforce")
-- Tell the script pooling system to pre-cache this number of scripts.
ScriptPoolCount = 4
function Definitions()
MinContrastScale = 1.1
MaxContrastScale = 1.25
Category = "Unrestricted_Grab_Space"
TaskForce = {
{
"MainForce"
, "Fighter | Bomber | Corvette | Frigate | Super | Capital = 100%"
}
}
end
function MainForce_Thread()
-- Since we're using plan failure to adjust contrast, we're
-- only concerned with failures in battle. Default the
-- plan to successful and then
-- only on the event of our task force being killed is the
-- plan set to a failed state.
MainForce.Set_Plan_Result(true)
--For fast execution, build and attack in one plan rather than having the first few iterations
--feed the freestore
AssembleForce(MainForce)
BlockOnCommand(MainForce.Move_To(Target))
if MainForce.Get_Force_Count() == 0 then
MainForce.Set_Plan_Result(false)
ScriptExit()
end
--Sit and blockade the planet
Sleep(300)
ScriptExit()
end
function MainForce_Production_Failed(failed_object_type)
ScriptExit()
end
function MainForce_Original_Target_Owner_Changed(tf, old_owner, new_owner)
--If we take control of this planet than we'll release our blockading units
if new_owner == PlayerObject then
ScriptExit()
end
end |
CloneClass( PlayerInventory )
function PlayerInventory.add_unit_by_factory_name(self, factory_name, equip, instant, blueprint, cosmetics, texture_switches)
self.orig.add_unit_by_factory_name(self, factory_name, equip, instant, blueprint, cosmetics, texture_switches)
end
Hooks:RegisterHook("PlayerInventoryOnPlaceSelection")
function PlayerInventory._place_selection(self, selection_index, is_equip)
self.orig._place_selection(self, selection_index, is_equip)
Hooks:Call("PlayerInventoryOnPlaceSelection", self, selection_index, is_equip)
end
Hooks:RegisterHook("PlayerInventoryOnUpdate")
function PlayerInventory.update(self, unit, t, dt)
Hooks:Call("PlayerInventoryOnUpdate", self, unit, t, dt)
end
|
local base_ui = require"module/gui/component/base_ui"
local rectangle = require"module/graphics/rectangle"
local button = require"module/gui/component/button"
local slide = class("slide",base_ui){
max = 10,
value = 0,
add_value = 0,
slide_button = nil,
is_draw_value = false,
}
function slide:__init(mode,x,y,w,h,max,style)
base_ui.__init(self,x,y,w,h)
self.max = max or 10
self:_init_style(mode,style)
self:set_max(max)
:set_depth(self.y)
self:connect(self,"mouse_exit","__mouse_exit__")
self:connect(self.slide_button,"sliding","__btn_sliding__")
self:signal("drag")
end
function slide:__btn_sliding__()
local v = self:get_value()
self:release("drag",v)
end
function slide:_init_style(mode,style)
local sdb_w = self.width / 10
local sdb_h = self.height
style = style or {}
style.button = style.button or {}
self.style.button = {}
self.mode = mode or "H" --H :horizontal V:vertical
if mode == "V" then
sdb_w = self.width
sdb_h = self.height / 10
end
self.sdb_w = sdb_w
self.sdb_h = sdb_h
local r = rectangle("fill",sdb_w,sdb_h,{210,70,0,255})
self.style.font = style.font
self.style.font_color = style.font_color or {226,101,11,255}
self.style.box = style.box or rectangle("line",self.width,self.height,{226,101,11,255})
self.style.bg = style.bg or rectangle("fill",self.width,self.height,{255,215,155,255})
self.style.button.default = style.button.default or r
self.style.button.hover = style.button.hover or r
self.style.button.hit = style.button.hit or r
self.slide_button = button("",0,0,sdb_w,sdb_h,{
default = self.style.button.default,
hover = self.style.button.hover,
hit = self.style.button.hit
})
:set_drag(true)
:set_root(self)
if mode == "V" then
function self.slide_button:drag_move()
local mox,moy = love.mouse.getPosition()
local root = self.root
local rx,ry = root:get_pos()
local y = ry + moy - self._drag_ofs.y
if y >= 0 and y > ry - 1 and y < ry + root.height - self.height + 1 then
self.y = moy - self._drag_ofs.y
end
end
else
function self.slide_button:drag_move()
local mox,moy = love.mouse.getPosition()
local root = self.root
local rx,ry = root:get_pos()
local x = rx + mox - self._drag_ofs.x
if x >= 0 and x > rx - 1 and x < rx + root.width - self.width + 1 then
self.x = mox - self._drag_ofs.x
end
end
end
end
function slide:set_max(max)
self.max = max or self.max
if self.mode == "V" then
self.add_value = self.max / (self.height - self.sdb_h)
else
self.add_value = self.max / (self.width - self.sdb_w)
end
return self
end
function slide:__mouse_exit__()
self.locking = false
end
function slide:set_draw_value(bool)
self.is_draw_value = bool
return self
end
function slide:set_value(v)
if v >= 0 and v <= self.max then
if self.mode == "V" then
self.slide_button.y = v
else
self.slide_button.x = v / self.add_value
end
end
end
function slide:get_value()
if self.mode == "V" then
return math.min(math.max(self.slide_button.y * self.add_value,0),self.max)
end
return math.min(math.max(self.slide_button.x * self.add_value,0),self.max)
end
function slide:wheelmoved(x,y)
local sdb = self.slide_button
local sdtx,sdty = sdb:get_pos()
local sex,sey = self:get_pos()
if self.mode == "V" then
y = -y * (self.height / 30)
local mvy = sdty + y
if mvy > sey - 1 and mvy < sey + self.height - sdb.height + 1 then
sdb.y = sdb.y + y
end
else
y = -y * (self.width / 30)
local mvx = sdtx + y
if mvx > sex - 1 and mvx < sex + self.width - sdb.width + 1 then
sdb.x = sdb.x + y
end
end
local v = self:get_value()
self:release("drag",v)
self.locking = true
end
function slide:update(dt)
local sd = self.slide_button
sd.__is_select = sd:is_hover()
sd:update(dt)
base_ui.update(self,dt)
end
function slide:mousepressed(mox,moy)
local sd = self.slide_button
if sd.__is_select then
sd:mousepressed(mox,moy)
end
base_ui.mousepressed(self,mox,moy)
self.locking = true
end
function slide:mousereleased()
local sd = self.slide_button
sd:mousereleased()
base_ui.mousereleased(self)
self.locking = false
end
function slide:draw_value(x,y)
local self_font = self.style.font
local font = self_font or ling.font.default
local value = string.format("%.0f",self:get_value())
if self_font then
love.graphics.setFont(font)
end
love.graphics.setColor(unpack(self.style.font_color))
if self.mode == "V" then
love.graphics.print(value,x + self.width / 2 + font:getHeight() / 2,y + self.height + 2,math.rad(90))
else
love.graphics.print(value,x + self.width + 2,y + (self.height / 2 - font:getHeight() / 2))
end
love.graphics.setColor(255,255,255,255)
if self_font then
love.graphics.setFont(ling.default_font)
end
end
function slide:draw()
local x,y = self:get_pos()
self.style.bg:draw(x,y)
self.style.box:draw(x,y)
self.slide_button:draw()
if self.is_draw_value then
self:draw_value(x,y)
end
end
return slide
|
--[[
The Adventures of Bat
Author: Aniruddha Pai
aniruddh.g.pai@gmail.com
agpai2@illinois.edu
]]
GameObject = Class{}
function GameObject:init(def)
self.x = def.x
self.y = def.y
self.width = def.width
self.height = def.height
self.animations = self:createAnimations(def.animations)
self.remove = false
end
function GameObject:createAnimations(animations)
local animationsReturned = {}
for k, animationDef in pairs(animations) do
animationsReturned[k] = Animation {
texture = animationDef.texture or 'entities',
frames = animationDef.frames,
interval = animationDef.interval
}
end
return animationsReturned
end
function GameObject:changeAnimation(name)
self.currentAnimation = self.animations[name]
end
function GameObject:collides(target)
-- AABB collision
return not (self.x + self.width < target.x or self.x > target.x + target.width or
self.y + self.height < target.y or self.y > target.y + target.height)
end
function GameObject:update(dt)
if self.x > -self.width then
self.x = self.x - BACKGROUND_SCROLL_SPEED * dt
else
self.remove = true
end
if self.currentAnimation then
self.currentAnimation:update(dt)
end
end
function GameObject:render()
local animation = self.currentAnimation
love.graphics.draw(gTextures[animation.texture],
gFrames[animation.texture][animation:getCurrentFrame()], self.x, self.y)
-- used for debugging
-- hit/hurt box of the object
-- love.graphics.rectangle('line', self.x, self.y, self.width, self.height)
end
|
object_tangible_tcg_series3_decorative_mustafar_travel_advertisement = object_tangible_tcg_series3_shared_decorative_mustafar_travel_advertisement:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series3_decorative_mustafar_travel_advertisement, "object/tangible/tcg/series3/decorative_mustafar_travel_advertisement.iff") |
-- ----------------------------------------------------------------------------
--
-- main - driver for the translator
--
-- ----------------------------------------------------------------------------
package.path = package.path .. ";?.lua;"
local translate = require "transcode" -- conversion processor
require "extrastr" -- extra string processor
local _format = string.format
local _endwipe = string.endwipe
-- ----------------------------------------------------------------------------
--
local function FileExists(inFilename)
local fhSrc = io.open(inFilename, "r")
if not fhSrc then return false end
fhSrc:close()
return true
end
-- ----------------------------------------------------------------------------
-- expect arguments:
-- 1> input filename
-- 2> output filename
-- 3> Codepage label (ISO, OEM, Windows)
-- 4> Codepage identification
--
local function driver(...)
local inFilename, outFilename, sCodepage, iPageId = ...
if not FileExists(inFilename) then io.write("Input file not found\n") return end
-- note that the Codepage function wants a table as parameter
--
local codepage = translate.Codepage({sCodepage, iPageId})
if not codepage then io.write("Codepage requested not found\n") return end
-- read all lines (with newline)
--
local tLines = { }
for sLine in io.lines(inFilename, "*L") do
-- convert each line
--
tLines[#tLines + 1] = translate.Processor(sLine, codepage)
end
-- write all lines to output file
--
local fhTgt = io.open(outFilename, "w")
for _, sLine in ipairs(tLines) do
fhTgt:write(sLine)
end
fhTgt:close()
io.write("Translation completed\n")
end
-- ----------------------------------------------------------------------------
-- expect arguments:
-- 1> input filename
-- 2> output filename
--
local function cleaner(inDirectory)
local tFileList = { }
-- ----------------------------------
-- enumerate files in given directory
--
local function EnumFiles(inDirectory)
local sPOpenCmd = 'chcp 1252 | dir /B /O:N /S /A:-D '
local sCommand = sPOpenCmd .. '"' .. inDirectory .. '"'
local fhSrc = io.popen(sCommand, "r")
for sFilename in fhSrc:lines() do
tFileList[#tFileList + 1] = sFilename
end
-- return count of files
--
return #tFileList
end
-- ------------------------------
-- do a cleanup of selected file
-- return the total bytes removed
--
local function ProcessFile(inFilename)
if not FileExists(inFilename) then io.write("Input file not found\n") return 0 end
-- read all lines (with newline)
--
local tLines = { }
local iTotal = 0 -- total removed
local iSkipped -- partial removed
for sLine in io.lines(inFilename, "*L") do
-- convert each line
--
iSkipped, tLines[#tLines + 1] = _endwipe(sLine)
iTotal = iTotal + iSkipped
end
-- (over)write all lines to output file
--
local fhTgt = io.open(inFilename, "w")
for _, sLine in ipairs(tLines) do
fhTgt:write(sLine)
end
fhTgt:close()
return iTotal
end
-- -----------------
-- start of function
--
local iCount = EnumFiles(inDirectory)
if 0 == iCount then
io.write("No file found\n")
return
end
local iRemoved
for _, sFilename in ipairs(tFileList) do
io.write(_format("Cleaning [%s]\n", sFilename))
iRemoved = ProcessFile(sFilename)
io.write(_format("Cleaned [%s]\tremoved [%d]\n", sFilename, iRemoved))
end
io.write("Cleanup completed\n")
end
-- ----------------------------------------------------------------------------
-- run it
--
driver("Test\\Pres.txt", "Test\\Pres_out.txt", "OEM", 437)
driver("Test\\LiesMich.txt", "Test\\LiesMich_out.txt", "Windows", 1252)
cleaner("Test")
-- ----------------------------------------------------------------------------
-- ----------------------------------------------------------------------------
|
local PartyMember = Class()
function PartyMember:init()
-- Display name
self.name = "Player"
-- Actor (handles overworld/battle sprites)
self.actor = nil
-- Light World Actor (handles overworld/battle sprites in light world maps) (optional)
self.lw_actor = nil
-- Default title / class (saved to the save file)
self.title = "Player"
-- Display level (saved to the save file)
self.level = 1
-- Light world LV (saved to the save file)
self.lw_lv = 1
-- Light world EXP (saved to the save file)
self.lw_exp = 0
-- Determines which character the soul comes from (higher number = higher priority)
self.soul_priority = 2
-- The color of this character's soul (optional, defaults to red)
self.soul_color = {1, 0, 0}
-- Whether the party member can act / use spells
self.has_act = true
self.has_spells = false
-- Whether the party member can use their X-Action
self.has_xact = true
-- X-Action name (displayed in this character's spell menu)
self.xact_name = "?-Action"
-- Spells
self.spells = {}
-- Current health (saved to the save file)
self.health = 100
-- Current light world health (saved to the save file)
self.lw_health = 20
-- Base stats (saved to the save file)
self.stats = {
health = 100,
attack = 10,
defense = 2,
magic = 0
}
-- Max stats from level-ups
self.max_stats = {}
-- Light world stats (saved to the save file)
self.lw_stats = {
health = 20,
attack = 10,
defense = 0
}
-- Weapon icon in equip menu
self.weapon_icon = "ui/menu/equip/sword"
-- Equipment (saved to the save file)
self.equipped = {
weapon = nil,
armor = {}
}
-- Default light world equipment item IDs (saves current equipment)
self.lw_weapon_default = "light/pencil"
self.lw_armor_default = "light/bandage"
-- Character color (for action box outline and hp bar)
self.color = {1, 1, 1}
-- Damage color (for the number when attacking enemies) (defaults to the main color)
self.dmg_color = nil
-- Attack bar color (for the target bar used in attack mode) (defaults to the main color)
self.attack_bar_color = nil
-- Attack box color (for the attack area in attack mode) (defaults to darkened main color)
self.attack_box_color = nil
-- X-Action color (for the color of X-Action menu items) (defaults to the main color)
self.xact_color = nil
-- Head icon in the equip / power menu
self.menu_icon = "party/kris/head"
-- Path to head icons used in battle
self.head_icons = "party/kris/icon"
-- Name sprite (optional)
self.name_sprite = nil
-- Effect shown above enemy after attacking it
self.attack_sprite = "effects/attack/cut"
-- Sound played when this character attacks
self.attack_sound = "laz_c"
-- Pitch of the attack sound
self.attack_pitch = 1
-- Battle position offset (optional)
self.battle_offset = nil
-- Head icon position offset (optional)
self.head_icon_offset = nil
-- Menu icon position offset (optional)
self.menu_icon_offset = nil
-- Message shown on gameover (optional)
self.gameover_message = nil
-- Character flags (saved to the save file)
self.flags = {}
-- Temporary stat buffs in battles
self.stat_buffs = {}
-- Light world EXP requirements
self.lw_exp_needed = {
[ 1] = 0,
[ 2] = 10,
[ 3] = 30,
[ 4] = 70,
[ 5] = 120,
[ 6] = 200,
[ 7] = 300,
[ 8] = 500,
[ 9] = 800,
[10] = 1200,
[11] = 1700,
[12] = 2500,
[13] = 3500,
[14] = 5000,
[15] = 7000,
[16] = 10000,
[17] = 15000,
[18] = 25000,
[19] = 50000,
[20] = 99999
}
end
-- Callbacks
function PartyMember:onAttackHit(enemy, damage) end
function PartyMember:onTurnStart(battler) end
function PartyMember:onLevelUp(level) end
function PartyMember:onPowerSelect(menu) end
function PartyMember:onPowerDeselect(menu) end
function PartyMember:drawPowerStat(index, x, y, menu) end
function PartyMember:onSave(data) end
function PartyMember:onLoad(data) end
function PartyMember:onEquip(item, item2) return true end
function PartyMember:onUnequip(item, item2) return true end
-- Getters
function PartyMember:getName() return self.name end
function PartyMember:getTitle() return "LV"..self:getLevel().." "..self.title end
function PartyMember:getLevel() return self.level end
function PartyMember:getLightLV() return self.lw_lv end
function PartyMember:getLightEXP() return self.lw_exp end
function PartyMember:getLightEXPNeeded(lv) return self.lw_exp_needed[lv] or 0 end
function PartyMember:getSoulPriority() return self.soul_priority end
function PartyMember:getSoulColor() return Utils.unpackColor(self.soul_color or {1, 0, 0}) end
function PartyMember:hasAct() return self.has_act end
function PartyMember:hasSpells() return self.has_spells end
function PartyMember:hasXAct() return self.has_xact end
function PartyMember:getXActName() return self.xact_name end
function PartyMember:getWeaponIcon() return self.weapon_icon end
function PartyMember:getHealth() return Game:isLight() and self.lw_health or self.health end
function PartyMember:getBaseStats(light)
if light or (light == nil and Game:isLight()) then
return self.lw_stats
else
return self.stats
end
end
function PartyMember:getMaxStats() return self.max_stats end
function PartyMember:getMaxStat(stat)
local max_stats = self:getMaxStats()
return max_stats[stat]
end
function PartyMember:getColor() return Utils.unpackColor(self.color) end
function PartyMember:getDamageColor()
if self.dmg_color then
return Utils.unpackColor(self.dmg_color)
else
return self:getColor()
end
end
function PartyMember:getAttackBarColor()
if self.attack_bar_color then
return Utils.unpackColor(self.attack_bar_color)
else
return self:getColor()
end
end
function PartyMember:getAttackBoxColor()
if self.attack_box_color then
return Utils.unpackColor(self.attack_box_color)
else
local r, g, b, a = self:getColor()
return r * 0.5, g * 0.5, b * 0.5, a
end
end
function PartyMember:getXActColor()
if self.xact_color then
return Utils.unpackColor(self.xact_color)
else
return self:getColor()
end
end
function PartyMember:getMenuIcon() return self.menu_icon end
function PartyMember:getHeadIcons() return self.head_icons end
function PartyMember:getNameSprite() return self.name_sprite end
function PartyMember:getAttackSprite() return self.attack_sprite end
function PartyMember:getAttackSound() return self.attack_sound end
function PartyMember:getAttackPitch() return self.attack_pitch end
function PartyMember:getBattleOffset() return unpack(self.battle_offset or {0, 0}) end
function PartyMember:getHeadIconOffset() return unpack(self.head_icon_offset or {0, 0}) end
function PartyMember:getMenuIconOffset() return unpack(self.menu_icon_offset or {0, 0}) end
function PartyMember:getGameOverMessage() return self.gameover_message end
-- Functions / Getters & Setters
function PartyMember:heal(amount, playsound)
if playsound == nil or playsound then
Assets.playSound("power")
end
self:setHealth(math.min(self:getStat("health"), self:getHealth() + amount))
return self:getStat("health") == self:getHealth()
end
function PartyMember:setHealth(health)
if Game:isLight() then
self.lw_health = health
else
self.health = health
end
end
function PartyMember:increaseStat(stat, amount, max)
local base_stats = self:getBaseStats()
base_stats[stat] = (base_stats[stat] or 0) + amount
max = max or self:getMaxStat(stat)
if max and base_stats[stat] > max then
base_stats[stat] = max
end
if stat == "health" then
self:setHealth(math.min(self:getHealth() + amount, base_stats[stat]))
end
end
function PartyMember:getReaction(item, user)
if item then
return item:getReaction(user.id, self.id)
end
end
function PartyMember:getActor(light)
if light == nil then
light = Game.light
end
if light then
return self.lw_actor or self.actor
else
return self.actor
end
end
function PartyMember:setActor(actor)
if type(actor) == "string" then
actor = Registry.createActor(actor)
end
self.actor = actor
end
function PartyMember:setLightActor(actor)
if type(actor) == "string" then
actor = Registry.createActor(actor)
end
self.lw_actor = actor
end
function PartyMember:getSpells()
return self.spells
end
function PartyMember:addSpell(spell)
if type(spell) == "string" then
spell = Registry.createSpell(spell)
end
table.insert(self.spells, spell)
end
function PartyMember:removeSpell(spell)
for i,v in ipairs(self.spells) do
if v == spell or (type(spell) == "string" and v.id == spell) then
table.remove(self.spells, i)
return
end
end
end
function PartyMember:getEquipment()
local result = {}
if self.equipped.weapon then
table.insert(result, self.equipped.weapon)
end
for i = 1, 2 do
if self.equipped.armor[i] then
table.insert(result, self.equipped.armor[i])
end
end
return result
end
function PartyMember:getWeapon()
return self.equipped.weapon
end
function PartyMember:getArmor(i)
return self.equipped.armor[i]
end
function PartyMember:setWeapon(item)
if type(item) == "string" then
item = Registry.createItem(item)
end
self.equipped.weapon = item
end
function PartyMember:setArmor(i, item)
if type(item) == "string" then
item = Registry.createItem(item)
end
self.equipped.armor[i] = item
end
function PartyMember:checkWeapon(id)
return self:getWeapon() and self:getWeapon().id == id or false
end
function PartyMember:checkArmor(id)
local result, count = false, 0
for i = 1, 2 do
if self:getArmor(i) and self:getArmor(i).id == id then
result = true
count = count + 1
end
end
return result, count
end
function PartyMember:canEquip(item, slot_type, slot_index)
if item then
return item:canEquip(self, slot_type, slot_index)
else
return slot_type ~= "weapon"
end
end
function PartyMember:getEquipmentBonus(stat)
local total = 0
for _,item in ipairs(self:getEquipment()) do
total = total + item:getStatBonus(stat)
end
return total
end
function PartyMember:getStats(light)
local stats = Utils.copy(self:getBaseStats(light))
for _,item in ipairs(self:getEquipment()) do
for stat,amount in pairs(item:getStatBonuses()) do
if stats[stat] then
stats[stat] = stats[stat] + amount
else
stats[stat] = amount
end
end
end
return stats
end
function PartyMember:getStat(name, default, light)
return (self:getBaseStats(light)[name] or (default or 0)) + self:getEquipmentBonus(name)
end
function PartyMember:getFlag(name, default)
local result = self.flags[name]
if result == nil then
return default
else
return result
end
end
function PartyMember:setFlag(name, value)
self.flags[name] = value
end
function PartyMember:addFlag(name, amount)
self.flags[name] = (self.flags[name] or 0) + (amount or 1)
end
function PartyMember:convertToLight()
local last_weapon = self:getWeapon()
local last_armors = {self:getArmor(1), self:getArmor(2)}
self.equipped = {weapon = nil, armor = {}}
if last_weapon then
local result = last_weapon:convertToLightEquip(self)
if result then
if type(result) == "string" then
result = Registry.createItem(result)
end
if isClass(result) then
self.equipped.weapon = result
end
end
end
for i = 1, 2 do
if last_armors[i] then
local result = last_armors[i]:convertToLightEquip(self)
if result then
if type(result) == "string" then
result = Registry.createItem(result)
end
if isClass(result) then
self.equipped.armor[1] = result
end
break
end
end
end
if not self.equipped.weapon then
self.equipped.weapon = Registry.createItem(self.lw_weapon_default)
end
if not self.equipped.armor[1] then
self.equipped.armor[1] = Registry.createItem(self.lw_armor_default)
end
self.equipped.weapon.dark_item = last_weapon
self.equipped.armor[1]:setFlag("dark_armors", {
["1"] = last_armors[1] and last_armors[1]:save(),
["2"] = last_armors[2] and last_armors[2]:save()
})
-- For deltarune accuracy, you heal here, bc health conversion code is broken
self.lw_health = self:getStat("health")
end
function PartyMember:convertToDark()
local last_weapon = self:getWeapon()
local last_armor = self:getArmor(1)
self.equipped = {weapon = nil, armor = {}}
if last_weapon then
local result = last_weapon:convertToDarkEquip(self)
if result then
if type(result) == "string" then
result = Registry.createItem(result)
end
if isClass(result) then
self.equipped.weapon = result
end
end
end
if last_armor then
local result = last_armor:convertToDarkEquip(self)
if result then
if type(result) == "string" then
result = Registry.createItem(result)
end
if isClass(result) then
self.equipped.armor[1] = result
end
end
end
end
-- Saving & Loading
function PartyMember:saveEquipment()
local result = {weapon = nil, armor = {}}
if self.equipped.weapon then
result.weapon = self.equipped.weapon:save()
end
for i = 1, 2 do
if self.equipped.armor[i] then
result.armor[tostring(i)] = self.equipped.armor[i]:save()
end
end
return result
end
function PartyMember:loadEquipment(data)
if type(data.weapon) == "table" then
local weapon = Registry.createItem(data.weapon.id)
weapon:load(data.weapon)
self:setWeapon(weapon)
else
self:setWeapon(data.weapon)
end
for i = 1, 2 do
self:setArmor(i, nil)
end
if data.armor then
for k,v in pairs(data.armor) do
if type(v) == "table" then
local armor = Registry.createItem(v.id)
armor:load(v)
self:setArmor(tonumber(k), armor)
else
self:setArmor(tonumber(k), v)
end
end
end
end
function PartyMember:saveSpells()
local result = {}
for _,v in pairs(self.spells) do
table.insert(result, v.id)
end
return result
end
function PartyMember:loadSpells(data)
self.spells = {}
for _,v in ipairs(data) do
self:addSpell(v)
end
end
function PartyMember:save()
local data = {
id = self.id,
title = self.title,
level = self.level,
health = self.health,
stats = self.stats,
lw_lv = self.lw_lv,
lw_exp = self.lw_exp,
lw_health = self.lw_health,
lw_stats = self.lw_stats,
spells = self:saveSpells(),
equipped = self:saveEquipment(),
flags = self.flags
}
self:onSave(data)
return data
end
function PartyMember:load(data)
self.title = data.title or self.title
self.level = data.level or self.level
self.stats = data.stats or self.stats
self.lw_lv = data.lw_lv or self.lw_lv
self.lw_exp = data.lw_exp or self.lw_exp
self.lw_stats = data.lw_stats or self.lw_stats
if data.spells then
self:loadSpells(data.spells)
end
if data.equipped then
self:loadEquipment(data.equipped)
end
self.flags = data.flags or self.flags
self.health = data.health or self:getStat("health", 0, false)
self.lw_health = data.lw_health or self:getStat("health", 0, true)
self:onLoad(data)
end
function PartyMember:canDeepCopy()
return false
end
return PartyMember |
local Modules = script.Parent.Parent.Parent.Parent
local Roact = require(Modules.Roact)
local StudioComponents = require(Modules.StudioComponents)
local BaseProperty = require(script.Parent.BaseProperty)
local function StringInput(props)
return Roact.createElement(BaseProperty, {
Text = props.Key,
}, {
Container = Roact.createElement("Frame", {
[Roact.Ref] = props._FieldRef,
Size = UDim2.new(1, 0, 0, 21),
BackgroundTransparency = 1,
BorderSizePixel = 0,
AnchorPoint = Vector2.new(0, 0.5),
Position = UDim2.new(0, 0, 0.5, 0),
}, {
StringInput = Roact.createElement(StudioComponents.TextInput, {
BorderSizePixel = 0,
OnFocused = props.OnFocused,
OnFocusLost = props.OnChanged,
OnChanged = function() end,
Text = props.Value,
ClearTextOnFocus = false,
}),
}),
})
end
return StringInput
|
local assets=
{
Asset("ANIM", "anim/worm_light.zip"),
}
local function item_oneaten(inst, eater)
if eater.wormlight then
eater.wormlight.components.spell.lifetime = 0
eater.wormlight.components.spell:ResumeSpell()
else
local light = SpawnPrefab("wormlight_light")
light.components.spell:SetTarget(eater)
if not light.components.spell.target then
light:Remove()
end
light.components.spell:StartSpell()
end
end
local function itemfn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.AnimState:SetBank("worm_light")
inst.AnimState:SetBuild("worm_light")
inst.AnimState:PlayAnimation("idle")
MakeInventoryPhysics(inst)
inst:AddComponent("inspectable")
inst:AddComponent("inventoryitem")
inst:AddComponent("tradable")
inst:AddComponent("edible")
inst.components.edible.foodtype = "VEGGIE"
inst.components.edible.healthvalue = TUNING.HEALING_MEDSMALL + TUNING.HEALING_SMALL
inst.components.edible.hungervalue = TUNING.CALORIES_MED
inst.components.edible.sanityvalue = -TUNING.SANITY_SMALL
inst.components.edible:SetOnEatenFn(item_oneaten)
inst:AddComponent("perishable")
inst.components.perishable:SetPerishTime(TUNING.PERISH_MED)
inst.components.perishable:StartPerishing()
inst.components.perishable.onperishreplacement = "spoiled_food"
inst:AddComponent("fuel")
inst.components.fuel.fuelvalue = TUNING.LARGE_FUEL * 1.33
inst.components.fuel.fueltype = "MOLEHAT"
inst:AddComponent("stackable")
inst.components.stackable.maxsize = TUNING.STACK_SIZE_LARGEITEM
local light = inst.entity:AddLight()
light:SetFalloff(0.7)
light:SetIntensity(.5)
light:SetRadius(0.5)
light:SetColour(169/255, 231/255, 245/255)
light:Enable(true)
inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
return inst
end
local function light_resume(inst, time)
local percent = time/inst.components.spell.duration
local var = inst.components.spell.variables
if percent and time > 0 then
--Snap light to value
inst.components.lighttweener:StartTween(inst.light, Lerp(0, var.radius, percent), 0.8, 0.5, {1,1,1}, 0)
--resume tween with time left
inst.components.lighttweener:StartTween(nil, 0, nil, nil, nil, time)
end
end
local function light_onsave(inst, data)
data.timealive = inst:GetTimeAlive()
end
local function light_onload(inst, data)
if data and data.timealive then
light_resume(inst, data.timealive)
end
end
local function light_spellfn(inst, target, variables)
if target then
inst.Transform:SetPosition(target:GetPosition():Get())
end
end
local function light_start(inst)
local spell = inst.components.spell
inst.components.lighttweener:StartTween(inst.light, spell.variables.radius, 0.8, 0.5, {169/255,231/255,245/255}, 0)
inst.components.lighttweener:StartTween(nil, 0, nil, nil, nil, spell.duration)
end
local function light_ontarget(inst, target)
if not target then return end
target.wormlight = inst
target:AddTag(inst.components.spell.spellname)
target.AnimState:SetBloomEffectHandle("shaders/anim.ksh")
end
local function light_onfinish(inst)
if not inst.components.spell.target then
return
end
inst.components.spell.target.wormlight = nil
inst.components.spell.target.AnimState:ClearBloomEffectHandle()
end
local light_variables = {
radius = TUNING.WORMLIGHT_RADIUS,
}
local function lightfn()
local inst = CreateEntity()
inst.entity:AddTransform()
inst:AddComponent("lighttweener")
inst.light = inst.entity:AddLight()
inst.light:Enable(true)
inst:AddTag("FX")
inst:AddTag("NOCLICK")
local spell = inst:AddComponent("spell")
inst.components.spell.spellname = "wormlight"
inst.components.spell:SetVariables(light_variables)
inst.components.spell.duration = TUNING.WORMLIGHT_DURATION
inst.components.spell.ontargetfn = light_ontarget
inst.components.spell.onstartfn = light_start
inst.components.spell.onfinishfn = light_onfinish
inst.components.spell.fn = light_spellfn
inst.components.spell.resumefn = light_resume
inst.components.spell.removeonfinish = true
return inst
end
return Prefab( "common/inventory/wormlight", itemfn, assets),
Prefab("common/inventory/wormlight_light", lightfn) |
local files_updates = 0
local restart_packages = {}
function string:split(sep) -- http://lua-users.org/wiki/SplitJoin
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
function check_if_restart()
if files_updates==0 then
if restart_packages[1] == nil then
ServerExit("Applying update for autoupdater")
else
auto_updater_log("Applying updates")
for i,v in ipairs(restart_packages) do
StopPackage(v)
Delay(500, function()
StartPackage(v)
end)
end
end
end
end
function auto_updater_log(msg,ply)
print(msg)
if ply then
AddPlayerChat(ply,msg)
end
local logfile = io.open("auto_updater_logs.txt", 'r')
local logs = nil
if logfile then
logs = logfile:read("*a")
io.close(logfile)
end
local lfilew = io.open("auto_updater_logs.txt", 'w')
local date = os.date()
local strtowrite = ""
if not logs then
strtowrite = date .. " / " .. msg .. "\n"
else
strtowrite = logs .. date .. " / " .. msg .. "\n"
end
lfilew:write(strtowrite)
io.close(lfilew)
end
function get_latest_commit(link,packagename,print_ply)
local linksplit = link:split("://")
local protocol = linksplit[1]
local linksplit2 = link:split("/")
local gitname = ""
local reponame = ""
for i,v in ipairs(linksplit2) do
if (i ~= 1 and i ~= 2) then
if gitname == "" then
gitname=v
elseif reponame == "" then
reponame=v
end
end
end
if (gitname~="" and reponame~="") then
local r = http_create()
http_set_resolver_protocol(r, "any")
http_set_protocol(r, protocol)
http_set_host(r, "api.github.com")
http_set_port(r, 443)
http_set_verifymode(r, "verify_peer")
http_set_target(r, "/repos/"..gitname.."/"..reponame.."/commits")
http_set_verb(r, "get")
http_set_timeout(r, 30000)
http_set_version(r, 11)
http_set_keepalive(r, false)
http_set_field(r, "user-agent", "Onset Server "..GetGameVersionString())
if http_send(r, OnGetCompletecommits, "Str L", 88.88, 1337,r,packagename,print_ply) == false then
auto_updater_log("Url " .. link .. " not found",print_ply)
http_destroy(r)
end
else
auto_updater_log("Can't find the latest commit for " .. link,print_ply)
end
end
function auto_updater_http(link,isjson,packagename,path,isjsonautoupdater,needtorestart,reinstall,print_ply)
local linksplit = link:split("://")
local protocol = linksplit[1]
local linksplit2 = link:split("/")
local target = ""
for i,v in ipairs(linksplit2) do
if (i ~= 1 and i ~= 2) then
target=target.."/"..v
end
end
local r = http_create()
http_set_resolver_protocol(r, "any")
http_set_protocol(r, protocol)
http_set_host(r, "raw.githubusercontent.com")
http_set_port(r, 443)
http_set_verifymode(r, "verify_peer")
http_set_target(r, target)
http_set_verb(r, "get")
http_set_timeout(r, 30000)
http_set_version(r, 11)
http_set_keepalive(r, false)
http_set_field(r, "user-agent", "Onset Server "..GetGameVersionString())
if not isjsonautoupdater then
if isjson then
if http_send(r, OnGetCompletejson, "Str L", 88.88, 1337,r,packagename,needtorestart,reinstall,link,print_ply) == false then
auto_updater_log("Url " .. link .. " not found",print_ply)
http_destroy(r)
if needtorestart then
files_updates=files_updates-1
end
end
else
if http_send(r, OnGetCompletefile, "Str L", 88.88, 1337,r,packagename,path,needtorestart,reinstall,print_ply) == false then
auto_updater_log("Url " .. link .. " not found , update for this file failed",print_ply)
http_destroy(r)
if needtorestart then
files_updates=files_updates-1
end
end
end
else
if http_send(r, OnGetCompleteautoupdater, "Str L", 88.88, 1337,r,packagename) == false then
auto_updater_log("Url " .. link .. " not found , update for the autoupdater failed")
http_destroy(r)
files_updates=0
searchupdatesallpackages(true,false)
end
end
end
function OnGetCompletejson(a, b, c,http,packagename,needtorestart,reinstall,link,print_ply)
if (http_is_error(http) or http_result_body(http)=="400: Invalid request\n" or http_result_body(http)=="404: Not Found\n") then
auto_updater_log("Invalid link for " .. packagename,print_ply)
files_updates=files_updates-1
else
local body = http_result_body(http)
local httppackage = json_decode(body)
local package = io.open("packages/"..packagename.."/package.json", 'r')
if (package) then
local contents = package:read("*a")
local pack_tbl = json_decode(contents);
io.close(package)
if needtorestart then
files_updates=files_updates-1
end
if (pack_tbl.version ~= httppackage.version or reinstall) then
if not reinstall then
auto_updater_log("Updating " .. packagename .. " " .. pack_tbl.version .. " ---> " .. httppackage.version,print_ply)
else
auto_updater_log("Reinstalling " .. packagename .. " " .. httppackage.version,print_ply)
end
table.insert(restart_packages,packagename)
if httppackage.auto_updater then
local writejson = io.open("packages/"..packagename.."/package.json", 'w')
if writejson then
writejson:write(body)
auto_updater_log("file package.json updated",print_ply)
io.close(writejson)
end
if httppackage.server_scripts then
for i,v in pairs(httppackage.server_scripts) do
if httppackage.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
if httppackage.client_scripts then
for i,v in pairs(httppackage.client_scripts) do
if httppackage.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
if httppackage.files then
for i,v in pairs(httppackage.files) do
if httppackage.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
else
auto_updater_log("The auto updater support is not on github , update of " .. packagename .. " update will perform with the local package.json",print_ply)
local writejson = io.open("packages/"..packagename.."/package.json", 'w')
if writejson then
pack_tbl.version = httppackage.version
writejson:write(json_encode(pack_tbl))
io.close(writejson)
auto_updater_log("changed version in package.json",print_ply)
end
if pack_tbl.server_scripts then
for i,v in pairs(pack_tbl.server_scripts) do
if pack_tbl.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(pack_tbl.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
if pack_tbl.client_scripts then
for i,v in pairs(pack_tbl.client_scripts) do
if pack_tbl.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(pack_tbl.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
if pack_tbl.files then
for i,v in pairs(pack_tbl.files) do
if pack_tbl.auto_updater[v] then
if needtorestart then
files_updates=files_updates+1
end
auto_updater_http(pack_tbl.auto_updater[v],false,packagename,v,nil,needtorestart,reinstall,print_ply)
end
end
end
end
get_latest_commit(link,packagename,print_ply)
else
auto_updater_log("No updates for " .. packagename,print_ply)
end
end
end
http_destroy(http)
end
function OnGetCompletefile(a, b, c,http,packagename,path,needtorestart,reinstall,print_ply)
if (http_is_error(http) or http_result_body(http)=="400: Invalid request\n" or http_result_body(http)=="404: Not Found\n") then
auto_updater_log("Invalid link for " .. packagename,print_ply)
if needtorestart then
files_updates=files_updates-1
check_if_restart()
end
else
local body = http_result_body(http)
local pathsplit = path:split(".")
local lasti = 0
for i,v in ipairs(pathsplit) do
lasti=i
end
if (pathsplit[lasti] == "png" or pathsplit[lasti] == "jpg" or pathsplit[lasti] == "jpeg" or pathsplit[lasti] == "gif" or pathsplit[lasti] == "wav" or pathsplit[lasti] == "mp3" or pathsplit[lasti] == "ogg" or pathsplit[lasti] == "oga" or pathsplit[lasti] == "flac" or pathsplit[lasti] == "ttf" or pathsplit[lasti] == "woff2" or pathsplit[lasti] == "pak") then
auto_updater_log("file " .. path .. " : unsupported format",print_ply)
else
local file = io.open("packages/"..packagename.."/" .. path, 'w')
if file then
file:write(body)
if not reinstall then
auto_updater_log("file " .. path .. " updated",print_ply)
else
auto_updater_log("file " .. path .. " reinstalled",print_ply)
end
io.close(file)
if needtorestart then
files_updates=files_updates-1
check_if_restart()
end
else
local path_bef = 'packages/'..packagename..'/' .. path
local splited_path = path_bef:split("/")
local r_path = ""
for i,v in ipairs(splited_path) do
if i < #splited_path then
if i == 1 then
r_path = v
else
r_path = r_path .. "/" .. v
end
end
end
auto_updater_log(r_path .. " CREATING THE PATH",print_ply)
local path_ = '"' .. r_path .. '"'
os.execute("mkdir " .. path_)
OnGetCompletefile(a, b, c,http,packagename,path,needtorestart,reinstall,print_ply)
end
end
end
http_destroy(http)
end
function OnGetCompleteautoupdater(a, b, c,http,packagename)
if (http_is_error(http) or http_result_body(http)=="400: Invalid request\n" or http_result_body(http)=="404: Not Found\n") then
files_updates=files_updates-1
auto_updater_log("Invalid link for " .. packagename)
searchupdatesallpackages(true,false)
else
local body = http_result_body(http)
local httppackage = json_decode(body)
local file = io.open("packages/"..packagename.."/package.json", 'r')
if file then
local contents = file:read("*a")
local pack_tbl = json_decode(contents);
io.close(file)
files_updates=files_updates-1
if pack_tbl.version ~= httppackage.version then
auto_updater_log("Updating " .. packagename .. " " .. pack_tbl.version .. " ---> " .. httppackage.version)
local writejson = io.open("packages/"..packagename.."/package.json", 'w')
if writejson then
writejson:write(body)
auto_updater_log("file package.json updated")
io.close(writejson)
end
if httppackage.server_scripts then
for i,v in pairs(httppackage.server_scripts) do
if httppackage.auto_updater[v] then
files_updates=files_updates+1
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,false,true,false)
end
end
end
if httppackage.client_scripts then
for i,v in pairs(httppackage.client_scripts) do
if httppackage.auto_updater[v] then
files_updates=files_updates+1
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,false,true,false)
end
end
end
if httppackage.files then
for i,v in pairs(httppackage.files) do
if httppackage.auto_updater[v] then
files_updates=files_updates+1
auto_updater_http(httppackage.auto_updater[v],false,packagename,v,false,true,false)
end
end
end
else
searchupdatesallpackages(true,false)
end
else
files_updates=files_updates-1
auto_updater_log("INVALID AUTO_UPDATER PATH")
end
end
http_destroy(http)
end
function OnGetCompletecommits(a,b,c,http,packagename,print_ply)
local body = http_result_body(http)
local httppackage = json_decode(body)
if (http_is_error(http) or httppackage.message == "Not Found") then
auto_updater_log("Can't find the latest commit",print_ply)
else
if httppackage[1].commit.message then
auto_updater_log("Last commit message for " .. packagename .. " is " .. httppackage[1].commit.message,print_ply)
end
end
http_destroy(http)
end
function searchupdatesallpackages(needtorestart,reinstall,print_ply)
local file = io.open("server_config.json", 'r')
if (file) then
local contents = file:read("*a")
local server_tbl = json_decode(contents);
io.close(file)
local packages_tbl = server_tbl.packages
for k,v in pairs(packages_tbl) do
local package = io.open("packages/"..v.."/package.json", 'r')
if (package) then
local contents = package:read("*a")
local pack_tbl = json_decode(contents);
io.close(package)
if pack_tbl.auto_updater then
if pack_tbl.auto_updater["package.json"] then
files_updates=files_updates+1
auto_updater_http(pack_tbl.auto_updater["package.json"],true,v,nil,nil,needtorestart,reinstall,print_ply)
end
end
end
end
end
end
AddEvent("OnPackageStart",function()
local package = io.open("packages/"..GetPackageName().."/package.json", 'r')
if (package) then
local contents = package:read("*a")
local pack_tbl = json_decode(contents);
io.close(package)
if pack_tbl.auto_updater then
if pack_tbl.auto_updater["package.json"] then
files_updates=files_updates+1
auto_updater_http(pack_tbl.auto_updater["package.json"],false,GetPackageName(),nil,true)
end
end
else
auto_updater_log("Critical error , can't find the package.json of the autoupdater")
end
end)
function searchraws_http(link,isfirstcheck,ply,packagefile,host,path,packjsonpath,ispredicted)
local linksplit = link:split("://")
local protocol = linksplit[1]
local linksplit2 = link:split("/")
local target = ""
local gitname = ""
local reponame = ""
for i,v in ipairs(linksplit2) do
if (i ~= 1 and i ~= 2) then
target=target.."/"..v
if gitname == "" then
gitname=v
elseif reponame == "" then
reponame=v
end
end
end
if (reponame~= nil and gitname~=nil and reponame~= "" and gitname~="" and reponame~= " " and gitname~=" ") then
local r = http_create()
http_set_resolver_protocol(r, "any")
http_set_protocol(r, protocol)
http_set_host(r, host)
http_set_port(r, 443)
http_set_verifymode(r, "verify_peer")
http_set_target(r, target)
http_set_verb(r, "get")
http_set_timeout(r, 30000)
http_set_version(r, 11)
http_set_keepalive(r, false)
http_set_field(r, "user-agent", "Onset Server "..GetGameVersionString())
if isfirstcheck then
if http_send(r, OnGetCompletecheck, "Str L", 88.88, 1337,r,gitname,reponame,ply,packagefile,protocol,packjsonpath,ispredicted) == false then
auto_updater_log("Url " .. link .. " not found")
http_destroy(r)
end
else
if http_send(r, OnGetCompletenewraw, "Str L", 88.88, 1337,r,ply,path,link,packjsonpath,ispredicted) == false then
auto_updater_log("Url " .. link .. " not found")
http_destroy(r)
end
end
else
auto_updater_log("Invalid link",ply)
end
end
function makelink(path,gitname,reponame,ply,protocol,packjsonpath,ispredicted)
local link = protocol.."://".."raw.githubusercontent.com".."/"..gitname.."/"..reponame.."/master/"..path
searchraws_http(link,false,ply,nil,"raw.githubusercontent.com",path,packjsonpath,ispredicted)
end
function OnGetCompletecheck(a,b,c,http,gitname,reponame,ply,packagefile,protocol,packjsonpath,ispredicted)
if (http_is_error(http) or http_result_body(http)=="400: Invalid request\n" or http_result_body(http)=="404: Not Found\n") then
auto_updater_log("Invalid link",ply)
else
makelink("package.json",gitname,reponame,ply,protocol,packjsonpath,ispredicted)
if packagefile.server_scripts then
for i,v in pairs(packagefile.server_scripts) do
makelink(v,gitname,reponame,ply,protocol,packjsonpath,ispredicted)
end
end
if packagefile.client_scripts then
for i,v in pairs(packagefile.client_scripts) do
makelink(v,gitname,reponame,ply,protocol,packjsonpath,ispredicted)
end
end
if packagefile.files then
for i,v in pairs(packagefile.files) do
local pathsplit = v:split(".")
local lasti = 0
for i,v in ipairs(pathsplit) do
lasti=i
end
if (pathsplit[lasti] == "html" or pathsplit[lasti] == "htm" or pathsplit[lasti] == "css" or pathsplit[lasti] == "js") then
makelink(v,gitname,reponame,ply,protocol,packjsonpath,ispredicted)
end
end
end
end
http_destroy(http)
end
function OnGetCompletenewraw(a,b,c,http,ply,path,link,packjsonpath,ispredicted)
local canpass = false
if ispredicted then
canpass = true
else
if (http_is_error(http) or http_result_body(http)=="400: Invalid request\n" or http_result_body(http)=="404: Not Found\n") then
auto_updater_log("Error link " .. link,ply)
else
canpass = true
end
end
if canpass then
local packagefilee = io.open(packjsonpath, 'r') -- reopen it every time to load changes
if packagefilee then
local contents = packagefilee:read("*a")
local packagefile = json_decode(contents);
io.close(packagefilee)
if packagefile.auto_updater then
packagefile.auto_updater[path] = link
else
packagefile.auto_updater = {}
packagefile.auto_updater[path] = link
end
local file = io.open(packjsonpath, 'w')
if file then
local contents = json_encode(packagefile)
file:write(contents)
auto_updater_log("Saved auto_updater support path : " .. path.." ".." link found : ".. link .. " restart to check updates",ply)
io.close(file)
end
end
end
http_destroy(http)
end
function checkadmin(ply)
local file = io.open("packages/"..GetPackageName().."/admins.json", 'r')
if (file) then
local contents = file:read("*a")
local admins_tbl = json_decode(contents);
io.close(file)
local isadmin = false
for i,v in ipairs(admins_tbl) do
if v == tostring(GetPlayerSteamId(ply)) then
isadmin=true
return true
end
end
if isadmin == false then
return false
end
else
local tbltoencode = {
"steamid"
}
local file = io.open("packages/"..GetPackageName().."/admins.json", 'w')
if file then
local contents = json_encode(tbltoencode)
file:write(contents)
auto_updater_log("admin.json file created in " .. "packages/"..GetPackageName().." please add admins restart the server and retry the command",ply)
io.close(file)
end
return nil
end
end
function addraws_cmd(ply,package,repolink,cmdname,ispredicted)
if (package~=nil and repolink~=nil and package~="" and repolink~="" and package~=" " and repolink~=" ") then
local isadmin = checkadmin(ply)
if (isadmin == false or isadmin == nil) then
auto_updater_log("You are not admin",ply)
else
local packagefilee = io.open("packages/"..package.."/package.json", 'r')
if packagefilee then
local contents = packagefilee:read("*a")
local packagefile = json_decode(contents);
io.close(packagefilee)
if packagefile.auto_updater then
auto_updater_log("Removed last auto updater support",ply)
packagefile.auto_updater = nil
end
searchraws_http(repolink,true,ply,packagefile,"github.com",nil,"packages/"..package.."/package.json",ispredicted)
else
auto_updater_log("Package not found",ply)
end
end
else
auto_updater_log("/ ".. cmdname .. " <packagename> <repolink>",ply)
end
end
AddCommand("searchraws",function(ply,package,repolink)
addraws_cmd(ply,package,repolink,"searchraws",false)
end)
AddCommand("predictraws",function(ply,package,repolink)
addraws_cmd(ply,package,repolink,"predictraws",true)
end)
AddCommand("reinstall",function(ply,packagename)
local isadmin = checkadmin(ply)
if (isadmin == false or isadmin == nil) then
auto_updater_log("You are not admin",ply)
else
if (packagename ~= nil and packagename ~= "" and packagename ~= " ") then
local package = io.open("packages/"..packagename.."/package.json", 'r')
if (package) then
local contents = package:read("*a")
local pack_tbl = json_decode(contents);
io.close(package)
if pack_tbl.auto_updater then
if pack_tbl.auto_updater["package.json"] then
auto_updater_log("Please restart the server after that to apply changes (if files were updated)",ply)
auto_updater_http(pack_tbl.auto_updater["package.json"],true,packagename,nil,false,false,true,ply)
end
else
auto_updater_log("This package does not support auto_updater",ply)
end
else
auto_updater_log("Package not found")
end
else
auto_updater_log("Please restart the server after that to apply changes (if files were updated)",ply)
searchupdatesallpackages(false,true,ply)
end
end
end)
AddCommand("searchupdates",function(ply,packagename)
local isadmin = checkadmin(ply)
if (isadmin == false or isadmin == nil) then
auto_updater_log("You are not admin",ply)
else
if (packagename ~= nil and packagename ~= "" and packagename ~= " ") then
local package = io.open("packages/"..packagename.."/package.json", 'r')
if (package) then
local contents = package:read("*a")
local pack_tbl = json_decode(contents);
io.close(package)
if pack_tbl.auto_updater then
if pack_tbl.auto_updater["package.json"] then
auto_updater_log("Please restart the server after that to apply changes (if files were updated)",ply)
auto_updater_http(pack_tbl.auto_updater["package.json"],true,packagename,nil,false,false,false,ply)
end
else
auto_updater_log("This package does not support auto_updater",ply)
end
else
auto_updater_log("Package not found",ply)
end
else
auto_updater_log("Please restart the server after that to apply changes (if files were updated)",ply)
searchupdatesallpackages(false,false,ply)
end
end
end) |
--cheerup the fortress. For when parties don't seem to be cutting it. awww.
--pieces of siren.lua and fixnaked.lua
--From siren.lua
function add_thought(unit, emotion, thought)
unit.status.current_soul.personality.emotions:insert('#', { new = true,
type = emotion,
unk2=1,
strength=1,
thought=thought,
subthought=0,
severity=0,
flags=nil,
unk7=0,
year=df.global.cur_year,
year_tick=df.global.cur_year_tick})
end
for unitcount,unit in ipairs(df.global.world.units.active) do
if unit.civ_id == df.global.ui.civ_id then
-- really wanna put this junk back in but I'm botching something somewhere. And while I'll run this 12 times... siren ... not so enjoyable for the fortress.
-- add_thought(unit, df.emotion_type.Admiration, df.unit_thought_type.Waterfall)
-- add_thought(unit, df.emotion_type.Admiration, df.unit_thought_type.Waterfall)
-- add_thought(unit, df.emotion_type.Admiration, df.unit_thought_type.Waterfall)
-- add_thought(unit, df.emotion_type.Relief, df.unit_thought_type.Rescued)
-- This have been moved or destroyed.
-- unit.status.happiness = 4000
unit.status.current_soul.personality.stress_level = -40000
end
end
announcement_flags = {
D_DISPLAY = true,
PAUSE = true,
}
--Weird having to format the announcement for my screen size... which will not match someone's out there. 1080p here.
dfhack.gui.showAnnouncement('What a sight those steam rockets were huh?! Doesn\'t the mist just cheer you up? AAAAAND Boom! The rockets shred their weak selves. No fuss no muss. What? You were worried about debris! Ha! ANOTHER VOLLEY! Come On! Give us another volley!',COLOR_MAGENTA, true)
|
local ffi = require("ffi")
local string,table,math,java,loadstring,tostring,tonumber=string,table,math,java,loadstring,tostring,tonumber
local ipairs,pairs,type=ipairs,pairs,type
function string.initcap(v)
return (' '..v):lower():gsub("([^%w])(%w)",function(a,b) return a..b:upper() end):sub(2)
end
function os.shell(cmd,args)
io.popen('"'..cmd..(args and (" "..args) or "")..'"')
end
function os.find_extension(exe,ignore_errors)
local exes=type(exe)=='string' and {exe} or exe
local err='Cannot find executable "'..exes[1]..'" in the default path, please add it into EXT_PATH of file data'..env.PATH_DEL..(env.IS_WINDOWS and 'init.cfg' or 'init.conf')
for _,exe in ipairs(exes) do
if exe:find('[\\/]') then
local type,file=os.exists(exe)
if not ignore_errors then env.checkerr(type,err) end
return file
end
exe='"'..env.join_path(exe):trim('"')..'"'
local nul=env.IS_WINDOWS and "NUL" or "/dev/null"
local cmd=string.format("%s %s 2>%s", env.IS_WINDOWS and "where " or "which ",exe,nul)
local f=io.popen(cmd)
local path
for file in f:lines() do
path=file
break
end
if path then return path end
end
env.checkerr(ignore_errors,err)
end
--Continus sep would return empty element
function string.split (s, sep, plain,occurrence,case_insensitive)
local r={}
for v in s:gsplit(sep,plain,occurrence,case_insensitive) do
r[#r+1]=v
end
return r
end
function string.replace(s,sep,txt,plain,occurrence,case_insensitive)
if not sep or s=='' then return s end
local r=s:split(sep,plain,occurrence,case_insensitive)
return table.concat(r,txt),#r-1
end
function string.escape(s, mode)
s = s:gsub('([%^%$%(%)%.%[%]%*%+%-%?%%])', '%%%1')
if mode == '*i' then s = s:case_insensitive_pattern() end
return s
end
function string.gsplit(s, sep, plain,occurrence,case_insensitive)
local start = 1
local counter=0
local done = false
local s1=case_insensitive==true and s:lower() or s
local sep1=case_insensitive==true and sep:lower() or sep
local function pass(i, j)
if i and ((not occurrence) or counter<occurrence) then
local seg = i>1 and s:sub(start, i - 1) or ""
start = j + 1
counter=counter+1
return seg, s:sub(i,j),counter,i,j
else
done = true
return s:sub(start),"",counter+1
end
end
return function()
if done then return end
if sep1 == '' then done = true;return s end
return pass(s1:find(sep1, start, plain))
end
end
function string.case_insensitive_pattern(pattern)
-- find an optional '%' (group 1) followed by any character (group 2)
local p = pattern:gsub("(%%?)(.)",
function(percent, letter)
if percent ~= "" or not letter:match("%a") then
-- if the '%' matched, or `letter` is not a letter, return "as is"
return percent .. letter
else
-- else, return a case-insensitive character class of the matched letter
return string.format("[%s%s]", letter:lower(), letter:upper())
end
end)
return p
end
local spaces={}
local s=' \t\n\v\f\r\0'
for i=1,#s do spaces[s:byte(i)]=true end
local ext_spaces={}
local function exp_pattern(sep)
local ary
if sep then
if not ext_spaces[sep] then
ext_spaces[sep]={}
for i=1,#sep do ext_spaces[sep][sep:byte(i)]=true end
end
ary=ext_spaces[sep]
end
return ary
end
local function rtrim(s,sep)
local ary=exp_pattern(sep)
if type(s)=='string' then
local len=#s
for i=len,1,-1 do
local p=s:byte(i)
if not spaces[p] and not (ary and ary[p]) then
return i==len and s or s:sub(1,i)
elseif i==1 then
return ''
end
end
end
return s
end
local function ltrim(s,sep)
local ary=exp_pattern(sep)
if type(s)=='string' then
local len=#s
for i=1,len do
local p=s:byte(i)
if not spaces[p] and not (ary and ary[p]) then
return i==1 and s or s:sub(i)
elseif i==len then
return ''
end
end
end
return s
end
string.ltrim,string.rtrim=ltrim,rtrim
function string.trim(s,sep)
return rtrim(ltrim(s,sep),sep)
end
String=java.require("java.lang.String")
local String=String
--this function only support %s
function string.fmt(base,...)
local args = {...}
for k,v in ipairs(args) do
if type(v)~="string" then
args[k]=tostring(v)
end
end
return String:format(base,table.unpack(args))
end
function string.format_number(base,s,cast)
if not tonumber(s) then return s end
return String:format(base,java.cast(tonumber(s),cast or 'double'))
end
function string.lpad(str, len, char)
str=tostring(str) or str
return (str and ((char or ' '):rep(len - #str)..str):sub(-len)) or str
end
function string.rpad(str, len, char)
str=tostring(str) or str
return (str and (str..(char or ' '):rep(len - #str)):sub(1,len)) or str
end
function string.cpad(str, len, char,func)
if not str then return str end
str,char=tostring(str) or str,char or ' '
str=str:sub(1,len)
local left=char:rep(math.floor((len-#str)/2))
local right=char:rep(len-#left-#str)
return type(func)~="function" and ("%s%s%s"):format(left,str,right) or func(left,str,right)
end
if not table.unpack then table.unpack=function(tab) return unpack(tab) end end
local system=java.system
local clocker=system.currentTimeMillis
function os.timer()
return clocker()/1000
end
function string.from(v)
local path=_G.WORK_DIR
path=path and #path or 0
if type(v) == "function" then
local d=debug.getinfo(v)
local src=d.source:gsub("^@+","",1):split(path,true)
if src and src~='' then
return 'function('..src[#src]:gsub('%.lua$','#'..d.linedefined)..')'
end
elseif type(v) == "string" then
return ("%q"):format(v:gsub("\t"," "))
end
return tostring(v)
end
local weekmeta={__mode='k'}
local globalweek=setmetatable({},weekmeta)
function table.weak(reuse)
return reuse and globalweek or setmetatable({},weekmeta)
end
function table.append(tab,...)
for i=1,select('#',...) do
tab[#tab+1]=select(i,...)
end
end
local json=json
if json.use_lpeg then json.use_lpeg () end
function table.totable(str)
local txt,err,done=loadstring('return '..str)
if not txt then
done,txt=pcall(json.decode,str)
else
done,txt=pcall(txt)
end
if not done then
local idx=0
str=('\n'..str):gsub('\n',function(s) idx=idx+1;return string.format('\n%4d',idx) end)
env.raise('Error while parsing text into Lua table:' ..(err or tostring(txt) or '')..str)
end
return txt
end
local function compare(a,b)
local t1,t2=type(a[1]),type(b[1])
if t1==t2 and t1~='table' and t1~='function' and t1~='userdata' and t1~='thread' then return a[1]<b[1] end
if t1=="number" then return true end
if t2=="number" then return false end
return tostring(a[1])<tostring(b[1])
end
function math.round(exact, quantum)
if type(exact)~='number' then return exact end
quantum = quantum and 10^quantum or 1
local quant,frac = math.modf(exact*quantum)
return (quant + (frac > 0.5 and 1 or 0))/quantum
end
function table.clone (t,depth) -- deep-copy a table
if type(t) ~= "table" or (depth or 1)<=0 then return t end
local meta = getmetatable(t)
local target = {}
for k, v in pairs(t) do
if type(v) == "table" then
target[k] = table.clone(v,(tonumber(depth) or 99)-1)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
function table.week(typ,gc)
return setmetatable({},{__mode=typ or 'k'})
end
function table.strong(tab)
return setmetatable(tab or {},{__gc=function(self) print('table is gc.') end})
end
function table.avgsum(t)
local sum = 0
local count= 0
for k,v in pairs(t) do
if type(v) == 'number' then
sum = sum + v
count = count + 1
end
end
return (sum / count),sum,count
end
-- Get the mode of a table. Returns a table of values.
-- Works on anything (not just numbers).
function table.mode( t )
local counts={}
for k, v in pairs( t ) do
if counts[v] == nil then
counts[v] = 1
else
counts[v] = counts[v] + 1
end
end
local biggestCount = 0
for k, v in pairs( counts ) do
if v > biggestCount then
biggestCount = v
end
end
local temp={}
for k,v in pairs( counts ) do
if v == biggestCount then
table.insert( temp, k )
end
end
return temp
end
-- Get the median of a table.
function table.median( t )
local temp={}
-- deep copy table so that when we sort it, the original is unchanged
-- also weed out any non numbers
for k,v in pairs(t) do
if type(v) == 'number' then
table.insert( temp, v )
end
end
table.sort( temp )
-- If we have an even number of table elements or odd.
if math.fmod(#temp,2) == 0 then
-- return mean value of middle two elements
return ( temp[#temp/2] + temp[(#temp/2)+1] ) / 2
else
-- return middle element
return temp[math.ceil(#temp/2)]
end
end
-- Get the standard deviation of a table
function table.stddev( t )
local m
local vm
local sum = 0
local count = 0
local result
m = table.avgsum( t )
for k,v in pairs(t) do
if type(v) == 'number' then
vm = v - m
sum = sum + (vm * vm)
count = count + 1
end
end
result = math.sqrt(sum / (count-1))
return result
end
-- Get the max and min for a table
function table.maxmin( t )
local max = -math.huge
local min = math.huge
for k,v in pairs( t ) do
if type(v) == 'number' then
max = math.max( max, v )
min = math.min( min, v )
end
end
return max, min
end
function table.dump(tbl,indent,maxdep,tabs)
maxdep=tonumber(maxdep) or 9
if maxdep<=1 then
return tostring(tbl)
end
if tabs==nil then
tabs={}
end
if not indent then indent = '' end
indent=string.rep(' ',type(indent)=="number" and indent or #indent)
local ind = 0
local pad=indent..' '
local maxlen=0
local keys={}
local fmtfun=string.format
for k,_ in pairs(tbl) do
local k1=k
if type(k)=="string" and not k:match("^[%w_]+$") then k1=string.format("[%q]",k) end
keys[#keys+1]={k,k1}
if maxlen<#tostring(k1) then maxlen=#tostring(k1) end
if maxlen>99 then
fmtfun=string.fmt
end
end
table.sort(keys,compare)
local rs=""
for v, k in ipairs(keys) do
v,k=tbl[k[1]],k[2]
local fmt =(ind==0 and "{ " or pad) .. fmtfun('%-'..maxlen..'s%s' ,tostring(k),'= ')
local margin=(ind==0 and indent or '')..fmt
rs=rs..fmt
if type(v) == "table" then
if k=='root' then
rs=rs..'<<Bypass root>>'
elseif tabs then
if not tabs[v] then
local c=tabs.__current_key or ''
local c1=c..(c=='' and '' or '.')..tostring(k)
tabs[v],tabs.__current_key=c1,c1
rs=rs..table.dump(v,margin,maxdep-1,tabs)
tabs.__current_key=c
else
rs=rs..'<<Refer to '..tabs[v]..'>>'
end
else
rs=rs..table.dump(v,margin,maxdep-1,tabs)
end
elseif type(v) == "function" then
rs=rs..'<'..string.from(v)..'>'
elseif type(v) == "userdata" then
rs=rs..'<userdata('..tostring(v)..')>'
elseif type(v) == "string" then
rs=rs..string.format("%q",v:gsub("\n","\n"..string.rep(" ",#margin)))
else
rs=rs..tostring(v)
end
rs=rs..',\n'
ind=ind+1
end
if ind==0 then return '{}' end
rs=rs:sub(1,-3)..'\n'
if ind<2 then return rs:sub(1,-2)..' }' end
return rs..indent..'}'
end
function try(args)
local succ,res,err,final=pcall(args[1])
local catch=args.catch or args[2]
local finally=args.finally or args[3]
final,err=true,not succ
if err and catch then
if(type(res)=="string" and env.ansi) then
res=res:match(env.ansi.pattern.."(.-)"..env.ansi.pattern)
end
succ,res=pcall(catch,res)
end
if finally then
final,err=pcall(finally,err)
if not catch or not final then succ,res=final,err or res end
end
if not succ then env.raise_error(res) end
return res
end
function string.fromhex(str)
return (str:gsub('..', function (cc)
return string.char(tonumber(cc, 16))
end))
end
--[[UTF-8 codepoint:
byte 1 2 3 4
--------------------------------------------
00 - 7F
C2 - DF 80 - BF
E0 A0 - BF 80 - BF
E1 - EC 80 - BF 80 - BF
ED 80 - 9F 80 - BF
EE - EF 80 - BF 80 - BF
F0 90 - BF 80 - BF 80 - BF
F1 - F3 80 - BF 80 - BF 80 - BF
F4 80 - 8F 80 - BF 80 - BF
The first hex character present the bytes of the char:
0-7: 1 byte, e.g.: 57
C-D: 2 bytes,e.g.: ce 9a
E: 3 bytes,e.g.: e6 ad a1
F: 4 bytes
--]]--
function string.chars(s,start)
local i = start or 1
if not s or i>#s then return nil end
local function next()
local c,i1,p,is_multi = s:byte(i),i
if not c then return end
if c >= 0xC2 and c <= 0xDF then
local c2 = s:byte(i + 1)
if c2 and c2 >= 0x80 and c2 <= 0xBF then i=i+1 end
elseif c >= 0xE0 and c <= 0xEF then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local flag = c2 and c3 and true or false
if c == 0xE0 then
if flag and c2 >= 0xA0 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c >= 0xE1 and c <= 0xEC then
if flag and c2 >= 0x80 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c == 0xED then
if flag and c2 >= 0x80 and c2 <= 0x9F and c3 >= 0x80 and c3 <= 0xBF then i1=i+2 end
elseif c >= 0xEE and c <= 0xEF then
if flag and
not (c == 0xEF and c2 == 0xBF and (c3 == 0xBE or c3 == 0xBF)) and
c2 >= 0x80 and c2 <= 0xBF and c3 >= 0x80 and c3 <= 0xBF
then i1=i+2 end
end
elseif c >= 0xF0 and c <= 0xF4 then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local c4 = s:byte(i + 3)
local flag = c2 and c3 and c4 and true or false
if c == 0xF0 then
if flag and
c2 >= 0x90 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
elseif c >= 0xF1 and c <= 0xF3 then
if flag and
c2 >= 0x80 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
elseif c == 0xF4 then
if flag and
c2 >= 0x80 and c2 <= 0x8F and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
then i1=i+3 end
end
end
p,i,is_multi=s:sub(i,i1),i1+1,i1>i
return p,is_multi,i
end
return next
end
function string.wcwidth(s)
if s=="" then return 0,0 end
if not s then return nil end
local len1,len2=0,0
for c,is_multi in s:chars() do
len1,len2=len1+1,len2+(is_multi and 2 or 1)
end
return len1,len2
end |
<h1>{{ icon( "equipment/" .. class.short, piece.rarity ) }} {{ T( piece.name ) }}</h1>
<h2>Stats</h2>
Defense: {{ piece.defense }}<br>
Fire res: {{ piece.fireRes }}<br>
Water res: {{ piece.waterRes }}<br>
Thunder res: {{ piece.thunderRes }}<br>
Ice res: {{ piece.iceRes }}<br>
Dragon res: {{ piece.dragonRes }}<br>
Rarity: <span class="rare{{ piece.rarity }}">{{ piece.rarity }}</span>
{%
if piece.skills then
print( "<h3>Skills</h3>" )
for _, skill in ipairs( piece.skills ) do
-- :)
local form =
skill.points > 0 and
"%s: +%d"
or skill.points < 0 and
"%s: <span class=\"neg\">%d</span>"
or
"%s"
printf( form .. "<br>", T( Skills[ skill.id ].name ), skill.points )
end
end
%}
<h2>Crafting</h2>
{%
if piece.create then
print( "<h3>Create</h3>" )
print( itemCounts( { materials = piece.create } ) )
printf( "Price: %sz", commas( piece.price ) )
end
if piece.scraps then
print( "<h3>Scraps</h3>" )
print( itemCounts( { materials = piece.scraps } ) )
end
%}
|
-- chest (strange egg) in level jacks lighthouse
onLoot = function(W)
local enemyData = {
id = 27,
position = {x=2330, y=840},
luapath = "res/level/jacklighthouse/elysia.lua",
}
W:spawnEnemy(enemyData)
W:addConditionProgress("default","elysia_intro")
end
|
#!/usr/bin/env luajit
-- Copyright 2020, Michael Adler <therisen06@gmail.com>
local log = require("log")
log.level = "error"
local List = require("pl.List")
local class = require("pl.class")
-- local fname = "small.txt"
local fname = "input.txt"
local function read_input()
local f = io.open(fname, "r")
local p1, p2 = List({}), List({})
local ignore = f:read("*l")
assert(ignore ~= nil)
for line in f:lines() do
if line == "" then
goto continue
end
if line == "Player 2:" then
break
end
p1:append(assert(tonumber(line)))
::continue::
end
for line in f:lines() do
p2:append(assert(tonumber(line)))
end
f:close()
return p1, p2
end
local function compute_score(t1, t2)
local t = t1
if t[1] == nil then
t = t2
end
local n = #t
local score = 0
for i = 1, n do
score = score + (n - i + 1) * t[i]
end
return score
end
local function part1()
local cards1, cards2 = read_input()
while cards1[1] ~= nil and cards2[1] ~= nil do
local c1 = cards1:pop(1)
local c2 = cards2:pop(1)
log.progress("New round: Player 1: ", c1, ", Player 2: ", c2)
if c1 > c2 then
log.debug("Player 1 wins")
cards1:append(c1)
cards1:append(c2)
else
log.debug("Player 2 wins")
cards2:append(c2)
cards2:append(c1)
end
end
return compute_score(cards1, cards2)
end
local Game = class()
function Game:_init(game_id, cards1, cards2)
self.game_id = game_id
self.cards1 = cards1
self.cards2 = cards2
self.history = {}
self.winner = nil
self.round = 0
log.debug(string.format("=== Game %d ===\n", game_id))
end
function Game:check_finished()
if self.winner == nil then
if self.cards1[1] == nil then
log.debug("Player 1 has no cards left")
self.winner = 2
elseif self.cards2[1] == nil then
log.debug("Player 2 has no cards left")
self.winner = 1
end
end
return self.winner ~= nil
end
function Game:check_cycle()
-- check if we've seen this state before
if self.history[self:serialize_cards()] then
self.winner = 1
return true
end
return false
end
function Game:serialize_cards()
return string.format("%s %s", tostring(self.cards1), tostring(self.cards2))
end
function Game:deal_cards()
self.round = self.round + 1
log.progress(string.format("-- Round %d (Game %d) --", self.round, self.game_id))
log.debug("Player 1's deck: ", tostring(self.cards1))
log.debug("Player 2's deck: ", tostring(self.cards2))
self.history[self:serialize_cards()] = true
local c1, c2 = self.cards1:pop(1), self.cards2:pop(1)
log.debug("Player 1 plays: ", c1)
log.debug("Player 2 plays: ", c2)
return c1, c2
end
local function part2()
local cards1, cards2 = read_input()
local current = Game(1, cards1, cards2)
-- "stack" frames / suspended games
local frames = {}
local winner
while true do
if current:check_finished() or current:check_cycle() then
winner = current.winner
log.debug(string.format("Player %d wins round %d of game %d!", winner, current.round, current.game_id))
if frames[1] == nil then
log.progress("Game over")
break
else
-- pop parent game
local frm = table.remove(frames, #frames)
current = frm.game
local c1, c2 = frm.c1, frm.c2
if winner == 1 then
current.cards1:append(c1)
current.cards1:append(c2)
else
current.cards2:append(c2)
current.cards2:append(c1)
end
end
else
-- this round's cards must be in a new configuration
local c1, c2 = current:deal_cards()
-- If both players have at least as many cards remaining in their deck as
-- the value of the card they just drew, the winner of the round is
-- determined by playing a new game of Recursive Combat
if #current.cards1 >= c1 and #current.cards2 >= c2 then
log.debug("Playing a sub-game to determine the winner...")
table.insert(frames, { game = current, c1 = c1, c2 = c2 })
-- the quantity of cards copied is equal to the number on the card they
-- drew to trigger the sub-game
current = Game(current.game_id + 1, current.cards1:slice(1, c1), current.cards2:slice(1, c2))
else
-- Otherwise, at least one player must not have enough cards left in
-- their deck to recurse; the winner of the round is the player with the
-- higher-value card.
if c1 > c2 then
log.debug(string.format("Player 1 wins round %d of game %d!", current.round, current.game_id))
current.cards1:append(c1)
current.cards1:append(c2)
else
log.debug(string.format("Player 2 wins round %d of game %d!", current.round, current.game_id))
current.cards2:append(c2)
current.cards2:append(c1)
end
end
end
end
return compute_score(cards1, cards2)
end
local answer1 = part1()
print("Part 1:", answer1)
local answer2 = part2()
print("Part 2:", answer2)
assert(answer1 == 33680)
assert(answer2 == 33683)
|
ITEM.name = "СИМК (пустой)"
ITEM.desc = "Свинцово-изолированный металлический контейнгер артефактом (СИМК) представляет собой простой металлический ящик с толстыми стенками, обшитыми пенопластом, а так же тяжелой крышкой с уплотнительными резинками. Специально разработан для транспортиртировки радиоактивных материалов. \n\nХАРАКТЕРИСТКИ: \n-ехнологическое приспособление \n-не требует подзарядки \n-позволяет транспортировать артефакты \n-максимальная вместимость: 1 \n-состояние: пустой \n\nВНИМАНИЕ: \n\nСледует извлечь артефакт из контейнера перед их продажей"
ITEM.price = 5718
ITEM.exRender = false
ITEM.weight = 2
ITEM.model = "models/kek1ch/lead_box_open.mdl"
ITEM.width = 1
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(70, -465, 130),
ang = Angle(13.757962226868, 98.598724365234, 0),
fov = 2.6
}
|
-- recipe
data:extend(
{
{
type = "recipe",
name = "fundamental-physics-research-center-mk1",
enabled = false,
energy_required = 10,
ingredients =
{
{"stone-brick", 100}
},
icons = {
{
icon = "__fundamental_physics__/graphics/item/lab-1.png",
}
},
icon_size = 32,
result = "fundamental-physics-research-center-mk1"
},
{
type = "recipe",
name = "fundamental-physics-research-center-mk2",
enabled = false,
energy_required = 20,
ingredients =
{
{"fundamental-physics-research-center-mk1", 1},
{"advanced-circuit", 30},
{"iron-plate", 100},
{"concrete", 100}
},
icons = {
{
icon = "__fundamental_physics__/graphics/item/lab-2.png",
}
},
icon_size = 32,
result = "fundamental-physics-research-center-mk2"
},
{
type = "recipe",
name = "fundamental-physics-research-center-mk3",
enabled = false,
energy_required = 40,
ingredients =
{
{"fundamental-physics-research-center-mk2", 1},
{"steel-plate", 100},
{"refined-concrete", 100}
},
icons = {
{
icon = "__fundamental_physics__/graphics/item/lab-3.png",
}
},
icon_size = 32,
result = "fundamental-physics-research-center-mk3"
},
})
if data.raw.item["basic-circuit-board"] then
table.insert(data.raw.recipe["fundamental-physics-research-center-mk1"].ingredients, {"basic-circuit-board", 20})
else
table.insert(data.raw.recipe["fundamental-physics-research-center-mk1"].ingredients, {"electronic-circuit", 20})
end
if data.raw.item["advanced-processing-unit"] then
table.insert(data.raw.recipe["fundamental-physics-research-center-mk3"].ingredients, {"advanced-processing-unit", 40})
else
table.insert(data.raw.recipe["fundamental-physics-research-center-mk3"].ingredients, {"processing-unit", 40})
end
-- item & entity
for i=1,3 do
local lab_item = table.deepcopy(data.raw["item"]["lab"])
lab_item.name = "fundamental-physics-research-center-mk"..i
lab_item.subgroup = "fundamental-physics-lab"
lab_item.place_result = "fundamental-physics-research-center-mk"..i
lab_item.icons = {
{
icon = "__fundamental_physics__/graphics/item/lab-"..i..".png",
}
}
mylib.add_angel_num_icon(lab_item,i)
local lab = table.deepcopy(data.raw["lab"]["lab"])
lab.name = "fundamental-physics-research-center-mk"..i
lab.fast_replaceable_group = "fundamental-physics-research-center"
lab.minable.result = "fundamental-physics-research-center-mk"..i
lab.max_health = (2^i)*data.raw.lab["lab"].max_health
lab.module_specification.module_slots = i
lab.energy_usage = (2^i*10).."MW"
lab.on_animation =
{
filename = "__fundamental_physics__/graphics/entity/lab-"..i..".png",
width = 113,
height = 91,
frame_count = 33,
line_length = 11,
animation_speed = 1 / 3,
shift = {0.2, 0.15}
}
lab.off_animation =
{
filename = "__fundamental_physics__/graphics/entity/lab-"..i..".png",
width = 113,
height = 91,
frame_count = 1,
shift = {0.2, 0.15}
}
lab.inputs =
{
"research-report-1",
"research-report-2",
"research-report-3",
"research-report-4",
"research-report-5",
"research-report-6",
"research-report-7",
}
lab.researching_speed = i
lab.icons = {
{
icon = "__fundamental_physics__/graphics/item/lab-"..i..".png"
}
}
mylib.add_angel_num_icon(lab,i)
data:extend({lab_item, lab})
end |
--]]
local test_url = 'https://www.baidu.com/'
local tap = require('util/tap')
local test = tap.test
local http = require('http')
test("http-client", function(expect)
http.get(test_url, expect(function(res)
print(res.statusCode)
assert(res.statusCode == 200)
assert(res.httpVersion == '1.1')
res:on('data', function(chunk)
console.log("ondata", {chunk = #chunk}, chunk)
end)
res:once('end', expect(function()
console.log('stream ended')
end))
end))
end)
tap.run()
|
-- Copyright (c) 2020 Trevor Redfern
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
describe("assets.quests.explore_dungeon", function()
local explore_dungeon = require "assets.quests.explore_dungeon"
it("has the primary attributes", function()
local ed = explore_dungeon:clone()
assert.not_nil(ed.title)
assert.not_nil(ed.description)
assert.not_nil(ed.image)
assert.not_nil(ed.prerequisites)
end)
end) |
LhdLoadingCcsView = class("LhdLoadingCcsView")
LhdLoadingCcsView.onCreationComplete = function (slot0)
ClassUtil.extends(slot0, BaseGameLoadingCcsView)
BaseGameLoadingCcsView.onCreationComplete(slot0)
end
LhdLoadingCcsView.onShow = function (slot0)
if slot0.loadingSpine2 == nil then
slot0.loadingSpine2 = slot0.controller:createSpine(LHD_SPINE.LoadingSpine2)
slot0.bgSpineNd:addChild(slot0.loadingSpine2)
slot0.loadingSpine2:setPosition(0, 0)
slot0.loadingSpine2:setAnimation(0, LHD_SPINE.LoadingSpine2.PlayName, false)
slot0.loadingSpine2:addAnimation(0, LHD_SPINE.LoadingSpine2.IdleName, true)
else
slot0.loadingSpine2:setVisible(true)
slot0.loadingSpine2:setAnimation(0, LHD_SPINE.LoadingSpine2.PlayName, false)
slot0.loadingSpine2:addAnimation(0, LHD_SPINE.LoadingSpine2.IdleName, true)
end
if slot0.loadingSpine == nil then
slot0.loadingSpine = slot0.controller:createSpine(LHD_SPINE.LoadingSpine1)
slot0.bgSpineNd:addChild(slot0.loadingSpine)
slot0.loadingSpine:setPosition(0, 0)
slot0.loadingSpine:setAnimation(0, LHD_SPINE.LoadingSpine1.PlayName, false)
slot0.loadingSpine:addAnimation(0, LHD_SPINE.LoadingSpine1.IdleName, true)
else
slot0.loadingSpine:setVisible(true)
slot0.loadingSpine:setAnimation(0, LHD_SPINE.LoadingSpine1.PlayName, false)
slot0.loadingSpine:addAnimation(0, LHD_SPINE.LoadingSpine1.IdleName, true)
end
end
return
|
function _init()
--global variables
grid_size=2
snake_vel=2
score = 0
highscore= 0
highscore_normal = 0
highscore_harcore = 0
difficulty = " normal"
collide= "not gameover"
colors_option = "normal"
collision = false
main_color = 7
small_color = 0
sprite_blocks = 1
color_apple_string = " gray"
color_apple = 5
palt(0,false)
palt(9,true)
apple_positions_1_x = { 13,23,33,43,53,63,73,83,93,103}
apple_positions_1_y = { 23,33,43,53,63,73,83,93,103,113}
apple_positions_2_x = { 11,21,31,41,51}
apple_positions_2_y = { 21,31,41,51}
--first state
init_menu()
end
function init_menu()
music(00)
sprite = 7
y = 78
_update = update_menu
_draw = draw_menu
end
function init_game()
music(-1, 200)
if(grid_size == 1) then
pix_x_b = 5
pix_y_b = 15
base_y_b= 15
last_y_b = 9
max_x_b = 11
max_y_b = 10
end
if grid_size == 2 then
pix_x_b = 3
pix_y_b = 13
base_y_b= 13
last_y_b= 18
max_x_b = 5
max_y_b = 4
end
cant_turn_back_y = false
cant_turn_back_x = false
score = 0
apples={}
add(apples,apple_spawn())
snake = {}
add(snake,snake_spawn())
blocks = {}
for x=0,max_x_b do
for y=0,max_y_b do
add(blocks,block_spawn(pix_x_b,pix_y_b))
pix_y_b = pix_y_b + 10
end
pix_x_b = pix_x_b + 10
pix_y_b = base_y_b
end
ticks = 0
_update = update_game
_draw = draw_game
end
function init_gameover()
y = 0
ticks = 0
timer = { elapsed = 0, last = time() }
circle = {}
circle.animation = { length = -100, elapsed = 0}
_update = update_gameover
_draw= draw_gameover
end
function init_options()
sprite = 8
color_difficulty = 7
color_gameover = 7
color_menu = 7
color_apple_options = 7
color_options_string = 7
y = 20
i = 1
positions = {20,45,70,95,110}
_update = update_options
_draw = draw_options
end
|
--[[
desc:龙虎
auth:Carol Luo
]]
local math = math
local table = table
local pairs = pairs
local ipairs = ipairs
local setmetatable = setmetatable
local random = require("random")
local class = require("class")
local ifNumber = require("ifNumber")
local hundredLogic = require("hundred.logic")
local senum = require("dragonTiger.enum")
---@class dragonTigerLogic:hundredLogic
local logic = class(hundredLogic)
local this = logic
---构造
function logic:ctor()
end
---重置数据
function logic:dataReboot()
self:super(this,"dataReboot")
local cfg = self._competition:getGameConf()
local poker = cfg.pokers
self._pokers = setmetatable({nil},
{
__index = function(t,index)
return poker[index]
end
})
self._count = #poker
end
---清除数据
function logic:dataClear()
self:super(this,"dataClear")
table.clear(self._pokers)
---龙牌
---@type pkCard
self._dragonCard = nil
---虎牌
---@type pkCard
self._tigerCard = nil
---结果
---@type senum
self._winner = nil
end
---发牌
function logic:dealCards()
self:dealDragonCard()
self:dealTigerCard()
self:dealCompare()
end
---发牌龙牌
function logic:dealDragonCard()
local poker = self._pokers
local index = math.random(1,self._count)
self._dragonCard = poker[index]
poker[1],poker[index] = poker[index],poker[1]
end
---发牌龙牌
function logic:dealTigerCard()
local poker = self._pokers
local index = math.random(2,self._count)
self._tigerCard = poker[index]
poker[2],poker[index] = poker[index],poker[2]
end
---发牌结果
function logic:dealCompare()
---龙虎算法
---@type dragonTigerAlgor
local algor = self._gor
self._winner = algor:compare(self._dragonCard,self._tigerCard)
end
---龙区发牌
---@return pkCard
function logic:getDragonCard()
return self._dragonCard
end
---龙区发牌
---@return pkCard
function logic:getTigerCard()
return self._tigerCard
end
---龙区发牌
---@return pkCard
function logic:getWinner()
return self._winner
end
return logic |
--- 模块功能:电话本功能测试.
-- @author openLuat
-- @module pb.testPb
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.27
module(...,package.seeall)
require"pb"
--[[
函数名:storagecb
功能 :设置电话本存储区域后的回调函数
参数 :
result:设置结果,true为成功,其余为失败
返回值:无
]]
local function storagecb(result)
log.info("testPb.storagecb",result)
--删除第1个位置的电话本记录
pb.delete(1,deletecb)
end
--[[
函数名:writecb
功能 :写入一条电话本记录后的回调函数
参数 :
result:写入结果,true为成功,其余为失败
返回值:无
]]
function writecb(result)
log.info("testPb.writecb",result)
--读取第1个位置的电话本记录
pb.read(1,readcb)
end
--[[
函数名:deletecb
功能 :删除一条电话本记录后的回调函数
参数 :
result:删除结果,true为成功,其余为失败
返回值:无
]]
function deletecb(result)
log.info("testPb.deletecb",result)
--写入电话本记录到第1个位置
pb.write(1,"name1","11111111111",writecb)
end
--[[
函数名:readcb
功能 :读取一条电话本记录后的回调函数
参数 :
result:读取结果,true为成功,其余为失败
name:姓名
number:号码
返回值:无
]]
function readcb(result,name,number)
log.info("testPb.readcb",result,name,number)
end
local function ready(result,name,number)
log.info("testPb.ready",result)
if result then
sys.timerStop(pb.read,1,ready)
--设置电话本存储区域,SM表示sim卡存储
pb.setStorage("SM",storagecb)
end
end
--循环定时器只是为了判断PB功能模块是否ready
sys.timerLoopStart(pb.read,2000,1,ready)
|
local util = require("github-theme.util")
local theme = require("github-theme.theme")
local config_module = require("github-theme.config")
local function setup(user_config)
if user_config then config_module.apply_configuration(user_config) end
-- Load colorscheme
util.load(theme.setup(config_module.config))
end
return {setup = setup}
|
-- puppet.lua
-- A simplified puppet without posable joints, but that
-- looks roughly humanoid.
rootnode = gr.node('root')
lblue = gr.material({0.67, 0.74, 1.0}, {0.1, 0.1, 0.1}, 10)
lpurp = gr.material({0.76, 0.55, 1.0}, {0.1, 0.1, 0.1}, 10)
player = gr.mesh('sphere', 'player')
rootnode:add_child(player)
player:set_material(lblue)
ext1 = gr.mesh('sphere', 'ext1')
player:add_child(ext1)
ext1:set_material(lpurp)
ext1:scale(0.2, 0.2, 0.2)
ext1:translate(0.85, 0.0, 0.0)
ext2 = gr.mesh('sphere', 'ext2')
player:add_child(ext2)
ext2:set_material(lpurp)
ext2:scale(0.2, 0.2, 0.2)
ext2:translate(-0.85, 0.0, 0.0)
ext3 = gr.mesh('sphere', 'ext3')
player:add_child(ext3)
ext3:set_material(lpurp)
ext3:scale(0.2, 0.2, 0.2)
ext3:translate(0.0, 0.85, 0.0)
ext4 = gr.mesh('sphere', 'ext4')
player:add_child(ext4)
ext4:set_material(lpurp)
ext4:scale(0.2, 0.2, 0.2)
ext4:translate(0.0, -0.85, 0.0)
ext5 = gr.mesh('sphere', 'ext5')
player:add_child(ext5)
ext5:set_material(lpurp)
ext5:scale(0.2, 0.2, 0.2)
ext5:translate(0.0, 0.0, 0.85)
ext6 = gr.mesh('sphere', 'ext6')
player:add_child(ext6)
ext6:set_material(lpurp)
ext6:scale(0.2, 0.2, 0.2)
ext6:translate(0.0, 0.0, -0.85)
return rootnode
|
-- Author: G4BB3R
-- Fibonacci function with memoization
local fib_cache = {}
local function fib (n)
if fib_cache[n] then
return fib_cache[n]
elseif n <= 1 then
return n
end
local result = fib (n - 1) + fib (n - 2)
fib_cache[n] = result
return result
end
local resultado = 0
for i = 1, 1000 do
local fib_value = fib(i)
if fib_value > 4000000 then
break
elseif fib_value % 2 == 0 then
resultado = resultado + fib_value
end
end
print(resultado) |
-- @requirements:MetatableBuilder
-- @author: xpecya
local MetatableBuilder = require "aul.metatableBuilder.MetatableBuilder";
local __type = "Stream";
local function basic(stream)
return function()
return stream.__data;
end
end
local function append(stream, consumer)
local localExecute;
if stream.__execute == nil then
localExecute = basic(stream);
else
localExecute = stream.__execute;
end
stream.__execute = function()
return consumer(localExecute());
end
end
return function(value)
local stream = {};
local data;
if value == nil then
data = {};
elseif type(value) == "table" then
if value.__type == __type then
data = value.__data;
else
data = value;
end
else
data = {value};
end
return setmetatable(stream, MetatableBuilder.new().immutable().index({
-- middle functions
map = function(consumer)
append(stream, function(input)
local result = {};
for _, v in ipairs(input) do
table.insert(result, consumer(v));
end
return result;
end);
return stream;
end,
filter = function(consumer)
append(stream, function(input)
local result = {};
for _, v in ipairs(input) do
local check = consumer(v);
if check ~= false and check ~= nil then
table.insert(result, v);
end
end
return result;
end);
return stream;
end,
distinct = function()
append(stream, function(input)
local result = {};
for _, dataInstance in ipairs(input) do
local check = true;
for __, resultInstance in ipairs(result) do
if resultInstance == dataInstance then
check = false;
break
end
end
if check then
table.insert(result, dataInstance);
end
end
return result;
end);
return stream;
end,
flatMap = function(consumer)
append(stream, function(input)
local result = {};
for _, v in ipairs(input) do
local stream = consumer(v);
assert(stream.__type == __type);
for __, value in ipairs(stream.__data) do
table.insert(result, value);
end
end
return result;
end);
return stream;
end,
limit = function(size)
append(stream, function(input)
local result = {};
for i, v in ipairs(input) do
if size < i then
break;
end
table.insert(result, v);
end
return result;
end);
return stream;
end,
skip = function(size)
append(stream, function(input)
local result = {};
for i, v in ipairs(data) do
if i > size then
table.insert(result, v);
end
end
return result;
end);
return stream;
end,
peek = function(consumer)
append(stream, function(input)
for _, v in ipairs(input) do
consumer(v);
end
return input;
end);
return stream;
end,
sort = function(comparator)
append(stream, function(input)
table.sort(input, comparator);
return data;
end);
return stream;
end,
-- collecting functions
toArray = function()
if stream.__execute == nil then
return stream.__data;
end
return stream.__execute();
end,
toTable = function(keyGenerator, valueGenerator)
local result = {};
for _, v in ipairs(stream.toArray()) do
result[keyGenerator(v)] = valueGenerator(v);
end
return result;
end,
count = function()
return #stream.toArray();
end,
forEach = function(consumer)
for _, v in ipairs(stream.toArray()) do
consumer(v);
end
end,
reduce = function(biConsumer)
local last = nil;
for _, v in ipairs(stream.toArray()) do
if last ~= nil then
last = biConsumer(last, v);
else
last = v;
end
end
return last;
end,
-- internal fields
__type = __type,
__data = data
}).build());
end
|
module("luci.controller.netspeedtest", package.seeall)
function index()
entry({"admin","network","netspeedtest"},cbi("netspeedtest/netspeedtest", {hideapplybtn=true, hidesavebtn=true, hideresetbtn=true}),_("Netspeedtest"),90).dependent=true
entry({"admin", "network", "netspeedtest", "status"}, call("act_status")).leaf = true
entry({"admin", "network","test_iperf0"}, post("test_iperf0"), nil).leaf = true
entry({"admin", "network","test_iperf1"}, post("test_iperf1"), nil).leaf = true
entry({"admin","network","netspeedtest", "run"}, call("run"))
entry({"admin", "network", "netspeedtest", "realtime_log"}, call("get_log"))
end
function act_status()
local e={}
e.status=luci.sys.call("pgrep iperf3 >/dev/null")==0
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function testlan(cmd, addr)
luci.http.prepare_content("text/plain")
local util = io.popen(cmd)
if util then
while true do
local ln = util:read("*l")
if not ln then break end
luci.http.write(ln)
luci.http.write("\n")
end
util:close()
end
end
function testwan(cmd)
local util = io.popen(cmd)
util:close()
end
function test_iperf0(addr)
luci.sys.call("killall unblockneteasemusic")
luci.sys.call("/etc/init.d/unblockneteasemusic stop ")
luci.sys.call("/etc/init.d/unblockmusic stop ")
testlan("iperf3 -s ", addr)
end
function test_iperf1(addr)
luci.sys.call("killall iperf3 ")
luci.sys.call("/etc/init.d/unblockneteasemusic restart")
luci.sys.call("/etc/init.d/unblockmusic restart")
end
function get_log()
local fs = require "nixio.fs"
local e = {}
e.running = luci.sys.call("busybox ps -w | grep netspeedtest | grep -v grep >/dev/null") == 0
e.log = fs.readfile("/var/log/netspeedtest.log") or ""
luci.http.prepare_content("application/json")
luci.http.write_json(e)
end
function run()
testwan("/etc/init.d/netspeedtest nstest ")
luci.http.redirect(luci.dispatcher.build_url("admin","network","netspeedtest"))
end
|
local function urldecode(s)
s = s:gsub('+', ' ')
:gsub('%%(%x%x)', function(h)
return string.char(tonumber(h, 16))
end)
return s
end
local function parseurl(s)
local ans = {}, k, v
for k, v in s:gmatch('([^&=?]-)=([^&=?]+)' ) do
ans[ k ] = urldecode(v)
end
return ans
end
-- parse http header
return function(headerBuf)
local request = {}
local headDiff = headerBuf:find("\n", 1, true)
if headDiff == nill then
return nil
end
request.http = headerBuf:sub(1, headDiff - 1)
request.method = headerBuf:sub(1, request.http:find(" ", 1, true) - 1)
local tmp = #request.method + 2
request.url = headerBuf:sub(tmp, request.http:find(" ", tmp, true) - 1)
tmp = #request.method + #request.url + 3
request.version = headerBuf:sub(tmp, #request.http)
request.headers = {}
headDiff = headDiff + 1
while headDiff < #headerBuf do
local chunkEnd = headerBuf:find("\n", headDiff, true)
local nameEnd = headerBuf:find(":", headDiff, true)
if chunkEnd == nil then
chunkEnd = #headerBuf + 1
end
if nameEnd == nil then
break
end
local key = headerBuf:sub(headDiff, nameEnd - 1)
local value = headerBuf:sub(nameEnd + 1, chunkEnd - 1)
request.headers[key] = value
headDiff = chunkEnd + 1
end
if request.method == "POST" and tonumber(request.headers['Content-Length']) > 0 then
headDiff = headDiff + 1
local postStr = headerBuf:sub(headDiff + 1, headDiff + tonumber(request.headers['Content-Length']))
--print("post: ", #postStr, postStr)
postStr = urldecode(postStr)
request.post = parseurl(postStr)
end
return request
end
|
local dpdk = require "dpdk"
local pipe = require "pipe"
local timer = require "timer"
function master()
local p = pipe:newSlowPipe()
p:send(1, 2, 3, 4)
p:send("string")
p:send({ foo = "bar", 1, 2, 3, subtable = {1}})
dpdk.launchLua("slave", p)
dpdk.sleepMillis(50)
p:send("delayed")
dpdk.waitForSlaves()
p = pipe:newSlowPipe()
dpdk.launchLua("numProducer", p)
dpdk.launchLua("consumer", p)
dpdk.waitForSlaves()
p = pipe:newSlowPipe()
dpdk.launchLua("stringProducer", p)
dpdk.launchLua("consumer", p)
dpdk.waitForSlaves()
p = pipe:newSlowPipe()
dpdk.launchLua("tblProducer", p)
dpdk.launchLua("consumer", p)
dpdk.waitForSlaves()
end
function slave(pipe)
assert(pipe:count() == 3)
local a, b, c, d = pipe:recv()
assert(a == 1 and b == 2 and c == 3 and d == 4)
assert(pipe:recv() == "string")
local obj = pipe:recv()
assert(obj.foo == "bar")
assert(obj[2] == 2)
assert(obj.subtable[1] == 1)
assert(pipe:tryRecv(10 * 1000) == nil)
assert(pipe:count() == 0)
dpdk.sleepMillis(40)
assert(pipe:tryRecv(1000) == "delayed")
end
function numProducer(pipe)
local timer = timer:new(10)
local i = 0
while timer:running() do
i = i + 1
pipe:send(i)
end
printf("Sent %d number objects, %f kmessages per second", i, i / 10 / 10^3)
end
function stringProducer(pipe)
local timer = timer:new(10)
local i = 0
while timer:running() do
i = i + 1
pipe:send("stringtest" .. tostring(i))
end
printf("Sent %d string objects, %f kmessages per second", i, i / 10 / 10^3)
end
function tblProducer(pipe)
local timer = timer:new(10)
local i = 0
while timer:running() do
i = i + 1
pipe:send({ foo = i })
end
printf("Sent %d tbl objects, %f kmessages per second", i, i / 10 / 10^3)
end
function consumer(pipe)
local timer = timer:new(10)
local i = 0
while timer:running() do
local obj = pipe:tryRecv(1000)
if obj then
i = i + 1
end
end
printf("Received %d objects, %f kmessages per second", i, i / 10 / 10^3)
end
|
local createApp = require("tevgit:core/dashboard/appCard.lua")
return {
name = "Develop",
iconId = "layer-group",
iconType = "faSolid",
scrollView = true,
setup = function(page)
local loading = teverse.construct("guiTextBox", {
parent = page,
size = guiCoord(1.0, 100, 1.0, 100),
position = guiCoord(0, -50, 0, -50),
backgroundAlpha = 0.4,
backgroundColour = colour(0, 0, 0),
text = "Working...",
textColour = colour(0,0,0),
textAlign = "middle",
visible = false,
zIndex = 10000
})
teverse.construct("guiTextBox", {
parent = page,
size = guiCoord(1.0, -20, 0, 48),
position = guiCoord(0, 10, 0, 10),
backgroundAlpha = 0,
text = "Develop",
textSize = 48,
textAlign = "middleLeft"
})
local btns = {
{
"Run packaged .tevapp",
"archive",
function()
teverse.apps:promptApp()
end
},
{
"Run unpacked app",
"code",
function ()
-- backwards compatibility
if _TEV_VERSION_MINOR < 25 then
return teverse.apps:promptAppDirectory()
end
local recents = teverse.apps:recentDirectories()
if #recents == 0 then
teverse.apps:promptAppDirectory()
else
local backdrop = teverse.construct("guiFrame", {
parent = teverse.interface,
size = guiCoord(1, 100, 1, 100),
position = guiCoord(0, -50, 0, -50),
backgroundColour = colour(0, 0, 0),
backgroundAlpha = 0.0,
zIndex = 10
})
teverse.tween:begin(backdrop, 0.2, {
backgroundAlpha = 0.8
})
local dialog = teverse.construct("guiFrame", {
parent = backdrop,
size = guiCoord(0, 200, 0, 100),
position = guiCoord(0.5, -100, 0.5, -50),
backgroundColour = colour(1, 1, 1),
strokeRadius = 2,
dropShadowAlpha = 0.15,
strokeAlpha = 0.05
})
teverse.tween:begin(dialog, 0.2, {
size = guiCoord(0, 500, 0, 200),
position = guiCoord(0.5, -250, 0.5, -100)
}, "outQuad")
local prompt = teverse.construct("guiIcon", {
parent = dialog,
size = guiCoord(0.3, 0, 1, 0),
position = guiCoord(0.7, 0, 0, 0),
iconMax = 40,
iconColour = colour.rgb(74, 140, 122),
backgroundAlpha = 0.05,
backgroundColour = colour(0, 0, 0),
iconType = "faSolid",
iconId = "folder-open"
})
prompt:on("mouseLeftUp", function()
teverse.apps:promptAppDirectory()
end)
local y = 0
for _,v in pairs(recents) do
local trigger = teverse.construct("guiTextBox", {
parent = dialog,
size = guiCoord(0.7, -20, 0, 18),
position = guiCoord(0, 10, 0, y),
backgroundAlpha = 0.0,
text = v,
textSize = 18
})
trigger:on("mouseLeftUp", function()
teverse.apps:runRecent(v)
end)
y = y + 20
end
end
end
}
}
if teverse.dev.localTevGit then
table.insert(btns, {
"Run workshop (in dev)",
"tools",
function ( )
teverse.apps:loadWorkshop()
end
})
end
local btnWidth = 1 / #btns
for i, cb in pairs(btns) do
local newSandboxBtn = teverse.construct("guiFrame", {
parent = page,
size = guiCoord(btnWidth, -20, 0, 70),
position = guiCoord((i-1)*btnWidth, 10, 0, 60),
backgroundColour = colour.rgb(74, 140, 122),
strokeRadius = 2,
dropShadowAlpha = 0.15,
strokeAlpha = 0.05
})
teverse.guiHelper
.bind(newSandboxBtn, "xs", {
size = guiCoord(1, -20, 0, 70),
position = guiCoord(0, 10, 0, 60 + ((i - 1) * 90))
})
.bind(newSandboxBtn, "md", {
size = guiCoord(btnWidth, -20, 0, 70),
position = guiCoord((i-1)*btnWidth, 10, 0, 60)
})
.hoverColour(newSandboxBtn, colour.rgb(235, 187, 83))
newSandboxBtn:on("mouseLeftUp", cb[3])
teverse.construct("guiTextBox", {
parent = newSandboxBtn,
size = guiCoord(0.75, -20, 0, 18),
position = guiCoord(0.25, 10, 0.5, -9),
backgroundAlpha = 0,
text = cb[1],
textSize = 18,
textAlign = "middle",
textColour = colour(1, 1, 1),
active = false
--textFont = "tevurl:fonts/openSansLight.ttf"
})
teverse.construct("guiIcon", {
parent = newSandboxBtn,
size = guiCoord(0, 40, 0, 40),
position = guiCoord(0.25, -20, 0.5, -20),
iconMax = 40,
iconColour = colour(1, 1, 1),
iconType = "faSolid",
iconId = cb[2],
iconAlpha = 0.9,
active = false
})
end
local appsContainer = teverse.construct("guiFrame", {
parent = page,
size = guiCoord(1.0, -20, 1, -150),
position = guiCoord(0, 10, 0, 150),
backgroundAlpha = 0
})
teverse.guiHelper
.gridConstraint(appsContainer, {
cellSize = guiCoord(0, 200, 0, 200),
cellMargin = guiCoord(0, 15, 0, 25)
})
teverse.guiHelper
.bind(appsContainer, "xs", {
size = guiCoord(1, -20, 1, -330),
position = guiCoord(0, 10, 0, 330)
})
.bind(appsContainer, "lg", {
size = guiCoord(1, 0, 1, -150),
position = guiCoord(0, 0, 0, 150)
})
teverse.http:get("https://teverse.com/api/users/" .. teverse.networking.localClient.id .. "/apps", {
["Authorization"] = "BEARER " .. teverse.userToken
}, function(code, body)
if code == 200 then
local apps = teverse.json:decode(body)
for _,app in pairs(apps) do
local appGui, launchButton = createApp(app)
appGui.parent = appsContainer
launchButton:on("mouseLeftUp", function()
if not loading.visible then
loading.text = "Loading App " .. (app.packageNetworked and "Online" or "Offline")
loading.visible = true
if not app.packageNetworked then
teverse.apps:loadRemote(app.id)
else
teverse.networking:initiate(app.id)
end
teverse.apps:waitFor("download")
loading.visible = false
end
end)
end
else
subtitle.text = "Server error."
end
end)
local function calculateScrollHeight()
local y = 0
for _,v in pairs(appsContainer.children) do
y = math.max(y, v.absolutePosition.y + 390)
end
appsContainer.size = guiCoord(1.0, -20, 0, y - appsContainer.absolutePosition.y)
page.canvasSize = guiCoord(1, 0, 0, y - appsContainer.absolutePosition.y)
end
calculateScrollHeight()
appsContainer:on("childAdded", calculateScrollHeight)
teverse.input:on("screenResized", calculateScrollHeight)
end
} |
-- Online Interiors IPL Edits
-- Use https://github.com/Bob74/bob74_ipl/wiki to edit below
-- Yacht (Del Perro)
Citizen.CreateThread(function()
-- Getting the object to interact with
HeistYacht = exports['bob74_ipl']:GetHeistYachtObject()
-- Enabling the yacht
HeistYacht.Enable(true)
end) |
--------------------------------------------------------------------------------
-- ARS-D/ARS-Ezh3/BKBD safety system BLPM unit
--------------------------------------------------------------------------------
-- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o.
-- Contains proprietary code. See license.txt for additional information.
--------------------------------------------------------------------------------
Metrostroi.DefineSystem("ALS_ARS_BLPM")
TRAIN_SYSTEM.DontAccelerateSimulation = false
function TRAIN_SYSTEM:Initialize()
self.Train:LoadSystem("BLPM_1R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_1R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_1R3","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_2R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_2R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_2R3","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_3R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_3R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_3R3","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_4R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_4R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_4R3","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_5R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_5R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_5R3","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_6R1","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_6R2","Relay","ARS",{bass=true,bass_separate=true})
self.Train:LoadSystem("BLPM_6R3","Relay","ARS",{bass=true,bass_separate=true})
self.Power = 0
self.NoneFreq = 0
self.OneFreq = 0
self.TwoFreq = 0
self.BadFreq = 0
end
function TRAIN_SYSTEM:Outputs()
return {}
end
function TRAIN_SYSTEM:Inputs()
return {}
end
function TRAIN_SYSTEM:TriggerInput(name,value)
end
local S = {}
function TRAIN_SYSTEM:Think(dT)
local Train = self.Train
local ALS = Train.ALSCoil
--[[if Train.KPK2 and Train.KPK2.Value > 0 then
S["TW94"] = Train:ReadTrainWire(self.PKWire or 94)
S["F6"] = bit.band(S["TW94"],32)/32
S["F5"] = bit.band(S["TW94"],16)/16
S["F4"] = bit.band(S["TW94"],8)/8
S["F3"] = bit.band(S["TW94"],4)/4
S["F2"] = bit.band(S["TW94"],2)/2
S["F1"] = bit.band(S["TW94"],1)/1
else
S["F6"] = ALS.F6
S["F5"] = ALS.F5
S["F4"] = ALS.F4
S["F3"] = ALS.F3
S["F2"] = ALS.F2
S["F1"] = ALS.F1
end]]
S["F6"] = ALS.F6
S["F5"] = ALS.F5
S["F4"] = ALS.F4
S["F3"] = ALS.F3
S["F2"] = ALS.F2
S["F1"] = ALS.F1
if Train.KPK2 and Train.KPK2.Value > 0 then
S["TW94"] = Train:ReadTrainWire(self.PKWire or 94)
S["F6"] = math.max(S["F6"],bit.band(S["TW94"],32)/32)
S["F5"] = math.max(S["F5"],bit.band(S["TW94"],16)/16)
S["F4"] = math.max(S["F4"],bit.band(S["TW94"],8)/8)
S["F3"] = math.max(S["F3"],bit.band(S["TW94"],4)/4)
S["F2"] = math.max(S["F2"],bit.band(S["TW94"],2)/2)
S["F1"] = math.max(S["F1"],bit.band(S["TW94"],1)/1)
end
local freqCount = self.Power*(S["F6"]+S["F5"]+S["F4"]+S["F3"]+S["F2"]+S["F1"])
self.NoneFreq =freqCount==0 and 1 or 0
self.OneFreq = freqCount==1 and 1 or 0
self.TwoFreq = freqCount==2 and 1 or 0
self.BadFreq = freqCount>2 and 1 or 0
Train.BLPM_1R1:TriggerInput("Set",self.Power*S["F1"])
Train.BLPM_1R2:TriggerInput("Set",self.Power*S["F1"])
Train.BLPM_1R3:TriggerInput("Set",(1-Train.BLPM_1R1.Value)*(1-Train.BLPM_1R2.Value))
Train.BLPM_2R1:TriggerInput("Set",self.Power*S["F2"])
Train.BLPM_2R2:TriggerInput("Set",self.Power*S["F2"])
Train.BLPM_2R3:TriggerInput("Set",(1-Train.BLPM_2R1.Value)*(1-Train.BLPM_2R2.Value))
Train.BLPM_3R1:TriggerInput("Set",self.Power*S["F3"])
Train.BLPM_3R2:TriggerInput("Set",self.Power*S["F3"])
Train.BLPM_3R3:TriggerInput("Set",(1-Train.BLPM_3R1.Value)*(1-Train.BLPM_3R2.Value))
Train.BLPM_4R1:TriggerInput("Set",self.Power*S["F4"])
Train.BLPM_4R2:TriggerInput("Set",self.Power*S["F4"])
Train.BLPM_4R3:TriggerInput("Set",(1-Train.BLPM_4R1.Value)*(1-Train.BLPM_4R2.Value))
Train.BLPM_5R1:TriggerInput("Set",self.Power*S["F5"])
Train.BLPM_5R2:TriggerInput("Set",self.Power*S["F5"])
Train.BLPM_5R3:TriggerInput("Set",(1-Train.BLPM_5R1.Value)*(1-Train.BLPM_5R2.Value))
if Train.PD1 then
Train.BLPM_6R1:TriggerInput("Set",self.Power*S["F6"]*Train.PD1.Value)
Train.BLPM_6R2:TriggerInput("Set",self.Power*S["F6"]*Train.PD2.Value)
Train.BLPM_6R3:TriggerInput("Set",(1-Train.BLPM_6R1.Value)*(1-Train.BLPM_6R2.Value))
else
Train.BLPM_6R1:TriggerInput("Set",self.Power*S["F6"])
Train.BLPM_6R2:TriggerInput("Set",self.Power*S["F6"])
Train.BLPM_6R3:TriggerInput("Set",(1-Train.BLPM_6R1.Value)*(1-Train.BLPM_6R2.Value))
end
if Train.GetDriver and Train:GetDriver() then
--print(123,Train.KPK2.Value,Train:ReadTrainWire(94))
--print("\nBLPM")
--print("1 2 3 4 5 6")
--print("123123123123123123")
--print(Train.BLPM_1R1.Value..Train.BLPM_1R2.Value..Train.BLPM_1R3.Value..Train.BLPM_2R1.Value..Train.BLPM_2R2.Value..Train.BLPM_2R3.Value..Train.BLPM_3R1.Value..Train.BLPM_3R2.Value..Train.BLPM_3R3.Value..Train.BLPM_4R1.Value..Train.BLPM_4R2.Value..Train.BLPM_4R3.Value..Train.BLPM_5R1.Value..Train.BLPM_5R2.Value..Train.BLPM_5R3.Value..Train.BLPM_6R1.Value..Train.BLPM_6R2.Value..Train.BLPM_6R3.Value,Train.KPK2.Value)
--print("\nSIR")
--print("54321 12")
--print(Train.BSM_SIR5.Value..Train.BSM_SIR4.Value..Train.BSM_SIR3.Value..Train.BSM_SIR2.Value..Train.BSM_SIR1.Value.." "..Train.BSM_SR1.Value..Train.BSM_SR2.Value)
end
end
|
fx_version "cerulean"
game "gta5"
author "Zua - https://github.com/thatziv @ https://github.com/jevajs"
description "An example resource that aims to demonstrate how low-level game events work in FiveM"
|
--@name StringStreamParser
--@author Vurv
--@shared
-- Builds a table struct from type data with stringstreams.
-- Useful especially for the ability to read arrays of any type.
-- One usecase may be for reading file types like .vvd or something.
local SSBuilder = class("SSBuilder")
-- Beware there's no 'float' or 'double' concepts for this.
-- Use Rust-like types. Aka float = f32, double = f64.
-- Note using a 'big' stream while reading regular sizes (f32, etc) will break stuff.
local Handlers = {
["i8"] = function(self)
return self:readInt8()
end,
["i16"] = function(self)
return self:readInt16()
end,
-- I32. This is simply 'Int' in most languages.
["i32"] = function(self)
return self:readInt32()
end,
-- UInt8
["u8"] = function(self)
return self:readUInt8()
end,
-- UInt16
["u16"] = function(self)
return self:readUInt16()
end,
-- UInt32
["u32"] = function(self)
return self:readUInt32()
end,
-- Null terminated string
["cstr"] = function(self)
return self:readString()
end,
-- Float
["f32"] = function(self)
return self:readFloat()
end,
-- Double. Needs parseBig (This is the default lua number type in 5.1)
["f64"] = function(self, big)
if not big then throw("SSBuilder tried to serialize double but was not 'big'. Use SSBuilder:parseBig") end
return self:readDouble()
end
}
function SSBuilder:initialize(definition)
assert(type(definition)=="string", "SSBuilder must be used with a string")
local nocomments = definition:gsub("[-/]+.-\n", "\n")
local used_keys = {}
local struc, n = {}, 1
for line in nocomments:gmatch("[^\n\r,]+") do
local key, rtype, count = line:match("%s*([%w_]+)%s*[:=]%s*%[?%s*([uifcstr]+%d*);?%s*(%$?[%w_%d]*)%]?")
-- Check if key exists, because an empty line being passed here would break it otherwise.
-- Comments cause this.
if key then
if used_keys[key] then
-- Key already exists. Why do you do this?
throw("Repeated key [" .. key .. "] found at line " .. n .. " in SSBuilder")
end
local handler = Handlers[rtype]
if not handler then throw("Unknown or invalid type [".. rtype .. "] in SSBuilder") end
struc[n] = { key, rtype, count or 1 }
used_keys[key] = true
n = n + 1
end
end
self.nfields = n
self.struc = struc
self.data = {}
end
-- This function may error with some cryptic 'bit' library error.
-- In this case, your serialization is wrong and the struct is trying to read values that don't exist or are different types.
function SSBuilder:parse(raw, big)
local struc, stream = self.struc, bit.stringstream(raw, 1, big and "big" or "little")
local data = self.data
for _, field_data in ipairs(struc) do
local key, rtype, count = unpack(field_data)
if type(count) ~= "number" then
if count:startWith("$") then
local var_name = count:sub(2)
local var = data[var_name]
if not var then throw("Variable " .. var_name .. " not found in parse runtime!") end
count = var
else
count = count=="" and 1 or tonumber(count)
end
end
local handler = Handlers[rtype]
if count > 1 then
-- We found an array.
local arr = {}
for i = 1, count do
arr[i] = handler(stream, big)
end
data[key] = arr
else
data[key] = handler(stream, big)
end
end
return data
end
function SSBuilder:parseBig(raw)
return self:parse(raw, true)
end
return SSBuilder |
--------------------------------------------------------------------------------
-- Raid move
--------------------------------------------------------------------------------
local function CheckHelper(aUniqueID)
local raidHelpers = raid.GetLeaderHelpers()
if not raidHelpers then
return false
end
for _, uniqueID in pairs(raidHelpers) do
if uniqueID:IsEqual(aUniqueID) then
return true
end
end
return false
end
function MoveTo(aPartyNum, anUniqueID, aMyUniqueID)
local iamHelper = CheckHelper(aMyUniqueID)
if isRaid() and (raid.IsLeader() or iamHelper) and anUniqueID then
if aPartyNum < 4 then
local currGroupSize = getGroupSizeFromPersId(anUniqueID)
local currGroupNum = getGroupFromPersId(anUniqueID)
if currGroupNum and aPartyNum < currGroupNum or currGroupSize and currGroupSize > 1 then
local emptyParty = getFirstEmptyPartyInRaid()
if aPartyNum < emptyParty then
raid.MoveMemberToGroup(anUniqueID, aPartyNum)
else
raid.IsolateMember(anUniqueID)
end
end
end
end
end
function SwapPlayers(anUniqueID1, anUniqueID2, aMyUniqueID)
local iamHelper = CheckHelper(aMyUniqueID)
if isRaid() and (raid.IsLeader() or iamHelper) then
if anUniqueID1 and anUniqueID2 then
raid.SwapMembers(anUniqueID1, anUniqueID2)
end
end
end
--------------------------------------------------------------------------------
-- Menu
--------------------------------------------------------------------------------
local m_menu = nil
local m_menuWidth = 210
local m_menuInfos = {}
local m_whisperMode = false
local m_template = createWidget(nil, "Template", "Template")
local function CloseMenu()
if m_menu then
destroy(m_menu)
m_menu=nil
end
end
local function AddToMenu(aName, aFunc)
table.insert(m_menuInfos, aName)
AddReaction(aName, aFunc)
end
function GenerateMenuInfos(aPlayerBar, aMyUniqueID)
local uniqueID = aPlayerBar.uniqueID
local playerID = aPlayerBar.playerID
local iamHelper = CheckHelper(aMyUniqueID)
m_menuInfos = {}
local name = aPlayerBar.optimizeInfo.name
local isAvatar = avatar.GetId()==playerID
local canWhisper = isExist(playerID) and unit.IsPlayer(playerID) and isFriend(playerID) and not isAvatar
local canInvite = canWhisper and not raid.IsAutomatic() and not group.IsAutomatic()
local isLeader = aPlayerBar.optimizeInfo.isLeader
if isAvatar and (isRaid() or isGroup()) then
local lootScheme=loot.GetLootScheme()
if lootScheme then
if lootScheme==LOOT_SCHEME_TYPE_FREE_FOR_ALL then AddToMenu("freeLootMenuButton", function () if isLeader then loot.SetLootScheme(LOOT_SCHEME_TYPE_MASTER) CloseMenu() end end) end
if lootScheme==LOOT_SCHEME_TYPE_MASTER then AddToMenu("masterLootMenuButton", function () if isLeader then loot.SetLootScheme(LOOT_SCHEME_TYPE_GROUP) CloseMenu() end end) end
if lootScheme==LOOT_SCHEME_TYPE_GROUP then AddToMenu("groupLootMenuButton", function () if isLeader then loot.SetLootScheme(LOOT_SCHEME_TYPE_FREE_FOR_ALL) CloseMenu() end end) end
end
local quality=loot.GetMinItemQualityForLootScheme()
if quality then
if quality==ITEM_QUALITY_JUNK then AddToMenu("junkLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_GOODS) CloseMenu() end end) end
if quality==ITEM_QUALITY_GOODS then AddToMenu("goodsLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_COMMON) CloseMenu() end end) end
if quality==ITEM_QUALITY_COMMON then AddToMenu("commonLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_UNCOMMON) CloseMenu() end end) end
if quality==ITEM_QUALITY_UNCOMMON then AddToMenu("uncommonLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_RARE) CloseMenu() end end) end
if quality==ITEM_QUALITY_RARE then AddToMenu("rareLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_EPIC) CloseMenu() end end) end
if quality==ITEM_QUALITY_EPIC then AddToMenu("epicLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_LEGENDARY) CloseMenu() end end) end
if quality==ITEM_QUALITY_LEGENDARY then AddToMenu("legendaryLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_RELIC) CloseMenu() end end) end
if quality==ITEM_QUALITY_RELIC then AddToMenu("relicLootMenuButton", function () if isLeader then loot.SetMinItemQualityForLootScheme(ITEM_QUALITY_JUNK) CloseMenu() end end) end
end
end
--[[
if not isAvatar and playerID ~= nil then
AddToMenu("inspectButton", function () if avatar.IsInspectAllowed() then avatar.StartInspect(playerID) end CloseMenu() end)
end
]]
if canWhisper then
AddToMenu("whisperMenuButton", function ()
local chat=stateMainForm:GetChildUnchecked("ChatInput", false)
chat=getChild(chat, "ChatInput")
m_whisperMode = true
show(chat)
getChild(chat, "Input", true):SetFocus(true)
mission.SetChatInputText((toWString("/whisper "..toString(name).." ")), 0)
CloseMenu() end)
end
if isRaid() then
local rights = raid.GetMemberRights(uniqueID)
local isHelper = rights and (rights[0] and rights[0]==RAID_MEMBER_RIGHT_LEADER_HELPER or rights[1] and rights[1]==RAID_MEMBER_RIGHT_LEADER_HELPER)
if raid.IsPlayerInAvatarsRaidById(uniqueID) then
local isMaster = rights and (rights[0] and rights[0]==RAID_MEMBER_RIGHT_LOOT_MASTER or rights[1] and rights[1]==RAID_MEMBER_RIGHT_LOOT_MASTER)
if isAvatar then AddToMenu("raidLeaveMenuButton", function () raid.Leave() CloseMenu() end) end
if raid.IsLeader() then
if not isAvatar and playerID ~= nil then
AddToMenu("leaderMenuButton", function () raid.ChangeLeader(uniqueID) CloseMenu() end)
if not isHelper then AddToMenu("addLeaderHelperMenuButton", function () raid.AddRight(uniqueID, RAID_MEMBER_RIGHT_LEADER_HELPER) CloseMenu() end)
else AddToMenu("deleteLeaderHelperMenuButton", function () raid.RemoveRight(uniqueID, RAID_MEMBER_RIGHT_LEADER_HELPER) CloseMenu() end) end
if not isMaster then AddToMenu("addMasterLootMenuButton", function () raid.AddRight(uniqueID, RAID_MEMBER_RIGHT_LOOT_MASTER) CloseMenu() end)
else AddToMenu("deleteMasterLootMenuButton", function () raid.RemoveRight(uniqueID, RAID_MEMBER_RIGHT_LOOT_MASTER) CloseMenu() end) end
end
if not raid.IsAutomatic() then
if not isAvatar then AddToMenu("kickMenuButton", function () raid.Kick(uniqueID) CloseMenu() end) end
AddToMenu("disbandMenuButton", function () raid.Disband() CloseMenu() end)
end
AddToMenu("moveMenuButton", function () StartMove(uniqueID) CloseMenu() end)
elseif iamHelper then
AddToMenu("disbandMenuButton", function () raid.Disband() CloseMenu() end)
AddToMenu("moveMenuButton", function () StartMove(uniqueID) CloseMenu() end)
end
else
if canInvite and (isHelper or raid.IsLeader()) then AddToMenu("inviteMenuButton", function () raid.Invite(playerID) CloseMenu() end) end
end
elseif isGroup() then
local memberInfo = group.GetMemberInfoById(uniqueID)
if memberInfo or group.IsCreatureInGroup(playerID) then
if isAvatar then
AddToMenu("leaveMenuButton", function () group.Leave() CloseMenu() end)
if group.IsLeader() and not group.IsAutomatic() then
AddToMenu("createRaidMenuButton", function () raid.Create() CloseMenu() end)
AddToMenu("createSmallRaidMenuButton", function () raid.CreateSmall() CloseMenu() end)
end
else
if group.CanKickMember() then AddToMenu("kickMenuButton", function () group.KickMember(name) CloseMenu() end) end
if group.IsLeader() and playerID ~= nil then AddToMenu("leaderMenuButton", function () group.SetLeader(uniqueID) CloseMenu() end) end
end
else
if canInvite and group.CanInvite() then AddToMenu("inviteMenuButton", function () group.Invite(playerID) CloseMenu() end) end
end
else
if canInvite then AddToMenu("inviteMenuButton", function () group.Invite(playerID) CloseMenu() end) end
end
AddToMenu("closeMenuButton", function () CloseMenu() end)
end
function ShowMenu(aPlayerBar, aParams, aRaidPanelWdg, aRaidPanelSize, aMyUniqueID)
CloseMenu()
GenerateMenuInfos(aPlayerBar, aMyUniqueID)
if not m_menuInfos then return end
setTemplateWidget(m_template)
local menuHeight=(table.maxn(m_menuInfos)+1)*20+8
local menuX = aParams.x
local menuY = aParams.y
local raidPlacement = aRaidPanelWdg:GetPlacementPlain()
if aParams.x > raidPlacement.posX + aRaidPanelSize.w - m_menuWidth then
menuX = menuX - m_menuWidth
menuX = menuX < 0 and 0 or menuX
end
if aParams.y > raidPlacement.posY + aRaidPanelSize.h/2 then
menuY = menuY - menuHeight - 20
menuY = menuY < 0 and 0 or menuY
end
m_menu = createWidget(mainForm, "Menu", "Panel", WIDGET_ALIGN_LOW, WIDGET_ALIGN_LOW, m_menuWidth, menuHeight, menuX, menuY)
priority(m_menu, 5600)
local name = aPlayerBar.optimizeInfo.name
setText(createWidget(m_menu, "Name", "TextView", WIDGET_ALIGN_CENTER, WIDGET_ALIGN_LOW, m_menuWidth-8, 20, nil, 4), name, "LogColorYellow", "center")
for i,j in ipairs(m_menuInfos) do
setLocaleText(createWidget(m_menu, j, "Button", WIDGET_ALIGN_CENTER, WIDGET_ALIGN_LOW, m_menuWidth-8, 20, nil, 4+(i)*20))
end
end |
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
local M = P:GetModule("Misc")
--------------------------
-- Credit: Mission Report
--------------------------
local tabs = {}
local datas = {
{Enum.GarrisonType.Type_9_0, GARRISON_TYPE_9_0_LANDING_PAGE_TITLE, 3675495},
{Enum.GarrisonType.Type_8_0, GARRISON_TYPE_8_0_LANDING_PAGE_TITLE, 1044517},
{Enum.GarrisonType.Type_7_0, ORDER_HALL_LANDING_PAGE_TITLE, 1411833},
{Enum.GarrisonType.Type_6_0, GARRISON_LANDING_PAGE_TITLE, 237381},
}
local function ToggleLandingPage(self)
if self.pageID ~= self.__owner.garrTypeID then
HideUIPanel(self.__owner)
ShowGarrisonLandingPage(self.pageID)
else
self:SetChecked(true)
end
end
local function GarrisonLandingPage_UpdateTabs(self)
for _, tab in pairs(tabs) do
local available = C_Garrison.HasGarrison(tab.pageID)
tab:SetEnabled(available)
tab:GetNormalTexture():SetDesaturated(not available)
tab:SetChecked(tab.pageID == self.garrTypeID)
end
end
function M:GarrisonTabs_Create()
for index, data in pairs(datas) do
local tab = CreateFrame("CheckButton", nil, _G.GarrisonLandingPage, "SpellBookSkillLineTabTemplate")
tab.__owner = _G.GarrisonLandingPage
tab:SetNormalTexture(data[3])
tab:SetScript("OnClick", ToggleLandingPage)
tab:Show()
if index == 1 then
tab:SetPoint("TOPLEFT", _G.GarrisonLandingPage, "TOPRIGHT", 2, -25)
else
tab:SetPoint("TOP", tabs[index-1], "BOTTOM", 0, -25)
end
if C.db["Skins"]["BlizzardSkins"] then
tab:GetNormalTexture():SetTexCoord(unpack(DB.TexCoord))
tab:GetRegions():Hide()
tab:SetCheckedTexture(DB.textures.pushed)
tab:GetHighlightTexture():SetColorTexture(1, 1, 1, .25)
B.CreateBDFrame(tab)
end
tab.pageID = data[1]
tab.tooltip = data[2]
table.insert(tabs, tab)
end
hooksecurefunc(_G.GarrisonLandingPage, "UpdateUIToGarrisonType", GarrisonLandingPage_UpdateTabs)
end
-- fix error and some incorrect wigdets when toggle old expansion page
function M:FixOldExpansionPage()
hooksecurefunc(_G.GarrisonLandingPage, "UpdateUIToGarrisonType", function(self)
self.Report.Sections:SetShown(self.garrTypeID == Enum.GarrisonType.Type_9_0)
if self.garrTypeID ~= Enum.GarrisonType.Type_6_0 and GarrisonThreatCountersFrame:IsShown() then
GarrisonThreatCountersFrame:Hide()
end
end)
local done
hooksecurefunc(_G.GarrisonLandingPage.FollowerList, "Setup", function(self)
if done then return end
local buttons = self.listScroll and self.listScroll.buttons
if buttons then
for _, button in ipairs(buttons) do
local follower = button.Follower
if follower and not follower.DownArrow then
local downArrow = follower:CreateTexture(nil, "ARTWORK")
downArrow:SetTexture("Interface\\Buttons\\SquareButtonTextures")
downArrow:SetSize(13, 13)
downArrow:SetPoint("TOPRIGHT", -10, -38)
downArrow:SetTexCoord(.45312500, .64062500, .01562500, .20312500)
downArrow:SetAlpha(0)
follower.DownArrow = downArrow
end
end
done = true
end
end)
hooksecurefunc(_G.GarrisonLandingPage.FollowerList, "UpdateFollowers", function(self)
if not self.followerTab then return end
if not GarrisonFollowerOptions[self.followerType].showNumFollowers then
self.followerTab.NumFollowers:SetText("")
end
end)
hooksecurefunc(_G.GarrisonLandingPage.FollowerTab, "ShowFollower", function(self)
local isAutoCombatant = self:GetParent():GetFollowerList().followerType == Enum.GarrisonFollowerType.FollowerType_9_0
if not isAutoCombatant then
if self.CovenantFollowerPortraitFrame then
self.CovenantFollowerPortraitFrame:Hide()
end
self.Class:Show()
self.autoCombatStatsPool:ReleaseAll()
self.autoSpellPool:ReleaseAll()
self.AbilitiesFrame:Layout()
end
end)
end
function M:GarrisonTabs()
if not M.db["GarrisonTabs"] then return end
M:GarrisonTabs_Create()
M:FixOldExpansionPage()
end
P:AddCallbackForAddon("Blizzard_GarrisonUI", M.GarrisonTabs) |
-- Copyright 2004-present Facebook. All Rights Reserved.
require('cutorch')
local tablex = require 'pl.tablex'
local withDevice = cutorch.withDevice
local gpu_local_copy_buffers = {}
--[[
`nn.AbstractParallel` is the base class for modules controlling
data/model-parallel behaviour in Torch.
The key concept is that data/model-parallelism _splits_ along a
dimension, and this class controls the distribution of input and
merging of output along this dimension.
To extend this class, override `_distributeInput` as appropriate.
See `nn.DataParallel` and `nn.ModelParallel` for examples of usage.
]]
local AbstractParallel, parent = torch.class('nn.AbstractParallel',
'nn.Container')
-- Iterates over all key/value pairs in a table, in reverse order.
-- Equivalent to ipairs(t) in reverse. See
-- http://lua-users.org/wiki/IteratorsTutorial for more detail.
local function ripairs(t)
local max = 1
while t[max] ~= nil do
max = max + 1
end
local function ripairs_it(t, i)
i = i-1
local v = t[i]
if v ~= nil then
return i,v
else
return nil
end
end
return ripairs_it, t, max
end
function AbstractParallel:__init(dimension)
if not dimension then
error "must specify a dimension!"
end
parent.__init(self)
self.modules = {}
self.gpu_assignments = {}
self.size = torch.LongStorage()
self.dimension = dimension
self.container_gpuid = cutorch.getDevice()
self.input_gpu = {} -- inputs for each gpu
self.gradOutput_gpu = {} -- inputs for each gpu
self.gradInput_gpu = {} -- gradInput for each gpu
end
function AbstractParallel:_freeCaches()
self.input_gpu = {}
self.gradOutput_gpu = {}
self.gradInput_gpu = {}
end
--[[
This function yields the GPU id for the module to be added.
It can be used for load balancing. It assumes all GPUs are available.
]]
function AbstractParallel:nextGPU()
local gpuid = #self.gpu_assignments % cutorch.getDeviceCount() + 1
return gpuid
end
function AbstractParallel._getBuffer()
local device = cutorch.getDevice()
if not gpu_local_copy_buffers[device] then
gpu_local_copy_buffers[device] = torch.CudaTensor()
end
return gpu_local_copy_buffers[device]
end
function AbstractParallel:add(module, gpuid)
table.insert(self.modules, module)
local gpuid = gpuid or self:nextGPU()
table.insert(self.gpu_assignments, gpuid)
return self
end
function AbstractParallel:get(index)
return self.modules[index]
end
--[[
Asynchronous copy from dest to source.
Use with caution; there needs to be some sort of external synchronization to
prevent source from being modified after this copy is enqueued.
]]
function AbstractParallel:gpuSend(dest, source)
assert(torch.typename(dest) == 'torch.CudaTensor')
assert(torch.typename(source) == 'torch.CudaTensor')
local dest_gpuid = dest:getDevice()
local source_gpuid = source:getDevice()
if source_gpuid == dest_gpuid then
-- if both tensors are on the same gpu normal copy works
withDevice(dest_gpuid, function()
dest:copy(source)
end)
return
end
-- if both tensors are contiguous copy across gpus works
if source:isContiguous() and dest:isContiguous() then
withDevice(dest_gpuid, function() dest:copy(source) end)
return
end
local tmp_source = source
if not source:isContiguous() then
withDevice(source_gpuid, function()
self:_getBuffer():resizeAs(source)
self:_getBuffer():copy(source)
tmp_source = self:_getBuffer()
end)
end
withDevice(dest_gpuid, function()
-- if destination is not contiguous copy across gpus does not
-- work; we need to first copy the source to the dest gpu
if not dest:isContiguous() then
self:_getBuffer():resizeAs(tmp_source)
self:_getBuffer():copy(tmp_source)
dest:copy(self:_getBuffer())
else
if false then
-- Whoops! TODO t5112851
dest:lazyCopy(tmp_source)
else
dest:copy(tmp_source)
end
end
end)
end
function AbstractParallel:updateOutput(input)
local container_gpuid = cutorch.getDevice()
local outs = {}
-- distribute the input to GPUs
self:_distributeInput(input)
-- update output for each module.
for i, module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
assert(self.input_gpu[gpuid]:getDevice() ==
self.gpu_assignments[gpuid])
outs[i] = module:updateOutput(self.input_gpu[gpuid])
end)
end
-- find the size of the merged output.
assert(container_gpuid == self.gpu_assignments[1])
assert(outs[1].getDevice and
(outs[1]:getDevice() == 0 or
outs[1]:getDevice() == container_gpuid))
self.size:resize(outs[1]:dim()):copy(outs[1]:size())
for i=2,#outs do
self.size[self.dimension] =
self.size[self.dimension] + outs[i]:size(self.dimension)
end
-- merge (concatenate) the outputs
self.output:resize(self.size)
local offset = 1
for i=1,#outs do
local outputDim = outs[i]:size(self.dimension)
local output_narrowed =
self.output:narrow(self.dimension, offset, outputDim)
self:gpuSend(output_narrowed, outs[i])
offset = offset + outputDim
end
return self.output
end
function AbstractParallel:updateGradInput(_input, gradOutput)
local container_gpuid = cutorch.getDevice()
-- gradOutput for each module on its appropriate gpu
self.gradInput:resizeAs(self.input_gpu[container_gpuid])
-- distribute gradOutput chunks to modules
local offset = 1
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
local currentOutput = module.output
-- get the gradOutput chunk for this module
local currentGradOutput =
gradOutput:narrow(self.dimension, offset,
currentOutput:size(self.dimension))
if not self.gradOutput_gpu[i] then
self.gradOutput_gpu[i] = torch.CudaTensor()
end
self.gradOutput_gpu[i]:resizeAs(currentGradOutput)
if gpuid == container_gpuid then
self.gradOutput_gpu[i]:copy(currentGradOutput)
else
-- copy gradoutput chunk to module's gpu
self:gpuSend(self.gradOutput_gpu[i], currentGradOutput)
end
offset = offset + currentOutput:size(self.dimension)
end)
end
-- update gradInput for each module
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
module:updateGradInput(self.input_gpu[gpuid],
self.gradOutput_gpu[i])
end)
end
-- add gradInputs
for i, module in ripairs(self.modules) do
if module.gradInput then
if i == 1 then
self.gradInput:copy(module.gradInput)
return self.gradInput
end
local parent_module_idx = math.floor(i / 2)
local parent_gpuid = self.gpu_assignments[parent_module_idx]
withDevice(parent_gpuid, function()
if not self.gradInput_gpu[i] then
self.gradInput_gpu[i] = torch.CudaTensor()
end
self.gradInput_gpu[i]:resizeAs(module.gradInput)
self:gpuSend(self.gradInput_gpu[i], module.gradInput)
self.modules[parent_module_idx].gradInput:add(
self.gradInput_gpu[i])
end)
end
end
return self.gradInput
end
function AbstractParallel:accGradParameters(_input, _gradOutput, scale)
scale = scale or 1
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
module:accGradParameters(self.input_gpu[gpuid],
self.gradOutput_gpu[i],
scale)
end)
end
end
function AbstractParallel:accUpdateGradParameters(_input, _gradOutput, lr)
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
module:accUpdateGradParameters(self.input_gpu[gpuid], self.gradOutput_gpu[i], lr)
end)
end
end
function AbstractParallel:zeroGradParameters()
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
module:zeroGradParameters()
end)
end
end
function AbstractParallel:updateParameters(learningRate)
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
module:updateParameters(learningRate)
end)
end
end
function AbstractParallel:share(mlp,...)
error("Share is not supported for the AbstractParallel layer.")
end
function AbstractParallel:clone()
local clone = parent.clone(self)
clone:cuda()
return clone
end
function AbstractParallel:reset(stdv)
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
self.modules[i]:reset(stdv)
end)
end
end
|
-- See LICENSE for terms
local mod_EnableMod
local function ModOptions(id)
-- id is from ApplyModOptions
if id and id ~= CurrentModId then
return
end
mod_EnableMod = CurrentModOptions:GetProperty("EnableMod")
end
OnMsg.ModsReloaded = ModOptions
OnMsg.ApplyModOptions = ModOptions
local Sleep = Sleep
local IsValid = IsValid
local PlaceObject = PlaceObject
local GetPassablePointNearby = GetPassablePointNearby
local table = table
local Random = ChoGGi.ComFuncs.Random
-- redefined AttackRover to blow up after it's out of ammo or too old
DefineClass.TowerDefense_Rover = {
__parents = {"AttackRover"},
attack_range = 500 * guim,
}
-- sometimes they get stuck in the mountains so we blow them up after a Sol
function TowerDefense_Rover:GameInit(...)
self.TowerDefense_spawned_sol = UICity.day
return AttackRover.GameInit(self,...)
end
local function SuicideByRocket(obj)
obj:SetCommand("Dead")
obj:FireRocket({target = obj},nil,true)
repeat
Sleep(500)
until obj.suicide_by_rocket
obj.city:RemoveFromLabel("HostileAttackRovers", obj)
obj.city:RemoveFromLabel("Rover", obj)
DeleteThread(obj.track_thread)
obj:delete()
end
function TowerDefense_Rover:FireRocket(luaobj, rocket_class, byebye)
rocket_class = rocket_class or "RocketProjectile"
self:SetAnim(1, "attackStart")
Sleep(self:TimeToAnimEnd())
self:SetAnim(1, "attackIdle")
Sleep(500)
local rocket = PlaceObject(rocket_class, luaobj)
local spot = self:GetSpotBeginIndex("Rocket")
local pos = self:GetSpotLoc(spot)
rocket.shooter = self
rocket:SetPos(pos)
rocket.move_dir = axis_z
rocket:StartMoving()
PlayFX("MissileFired", "start", self, nil, pos, axis_z)
self:SetAnim(1, "attackEnd")
Sleep(self:TimeToAnimEnd())
if byebye then
self.suicide_by_rocket = true
-- get rid of any ones that're out of ammo
elseif not self.attacks_remaining or self.attacks_remaining == 0 then
CreateGameTimeThread(SuicideByRocket,self)
end
end
local function LoadMapSectorsStats()
local UICity = UICity
if not UICity then
return
end
-- store amounts per save here
if not UICity.ChoGGi_TowerDefense then
-- build list of out map sectors (all of 1 and 10, and the top/bottom from the rest
local sectors = UICity.MapSectors
local sector_table = {}
local c = 0
local function AddOneTen(sector)
for i = 1, #sector do
c = c + 1
sector_table[c] = sector[i]
end
end
AddOneTen(sectors[1])
AddOneTen(sectors[10])
for i = 2, 9 do
local sector = sectors[i]
c = c + 1
sector_table[c] = sector[1]
c = c + 1
sector_table[c] = sector[10]
end
UICity.ChoGGi_TowerDefense = {
-- rovers to spawn next sol
rovers_next = 5,
-- ammo to give each rover
ammo_next = 4,
-- index table of sectors
sectors = sector_table,
-- count of sectors
count = c,
}
end
end
OnMsg.MapSectorsReady = LoadMapSectorsStats
OnMsg.LoadGame = LoadMapSectorsStats
local function RemoveOldRovers(label, sol)
-- go backwards and remove any invalid/old rovers
for i = #(label or ""), 1, -1 do
local r = label[i]
if not IsValid(r) then
table.remove(label, i)
elseif r.class == "TowerDefense_Rover" and r.TowerDefense_spawned_sol ~= sol then
CreateGameTimeThread(SuicideByRocket,r)
end
end
end
function OnMsg.NewDay(sol)
if not mod_EnableMod then
return
end
CreateGameTimeThread(function()
-- let other stuff go first
Sleep(1000)
if sol > 24 and not IsTechDiscovered("DefenseTower") then
UIColony:SetTechDiscovered("DefenseTower")
end
if sol < 49 then
return
end
local UICity = UICity
-- remove any old rovers stuck in the mountains
RemoveOldRovers(UICity.labels.HostileAttackRovers, sol)
RemoveOldRovers(UICity.labels.Rover, sol)
-- just in case
if not UICity.ChoGGi_TowerDefense then
LoadMapSectorsStats()
end
local stats = UICity.ChoGGi_TowerDefense
for _ = 1, stats.rovers_next do
-- add a bit of a random delay
Sleep(Random(2500, 10000))
-- muhhahahaha
local r = PlaceObject("TowerDefense_Rover", {
spawn_pos = GetPassablePointNearby(stats.sectors[Random(1, stats.count)]:GetPos()),
attacks_remaining = stats.ammo_next,
})
-- need to make 'em nasty
Sleep(250)
r:SetCommand("Idle")
end
-- bump the stats
stats.rovers_next = stats.rovers_next + 1
stats.ammo_next = stats.ammo_next + 2
-- I doubt anyone will make it to max_int rovers, but what the hell
if stats.rovers_next < 0 then
stats.rovers_next = 5
end
if stats.ammo_next < 0 then
stats.ammo_next = 4
end
end)
end
|
ancient_reptillian = Creature:new {
objectName = "",
customName = "Ancient Reptillian",
socialGroup = "voritor",
faction = "",
level = 57,
chanceHit = 0.55,
damageMin = 420,
damageMax = 550,
baseXp = 5555,
baseHAM = 11000,
baseHAMmax = 13000,
armor = 0,
resists = {45,45,10,10,10,-1,10,10,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = KILLER + STALKER,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/voritor_lizard.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"dizzyattack",""},
{"posturedownattack",""}
}
}
CreatureTemplates:addCreatureTemplate(ancient_reptillian, "ancient_reptillian") |
local BagConst = {
--BagConst.Pos.Bag
Pos = {
Bag = 1,
Warehouse = 2,
Equip = 3,
},
--BagConst.MaxCell
MaxCell = 50,
}
return BagConst |
PLUGIN.name = "Containers"
PLUGIN.author = "AleXXX_007"
PLUGIN.desc = "Adds placeable containers."
nut.util.include("sv_plugin.lua")
nut.command.add("getlock", {
onRun = function(client, arguments)
local trace = client:GetEyeTraceNoCursor()
local target = trace.Entity
if target and IsValid(target) and (target:isDoor() or target:GetClass() == "nut_container") then
if target:isDoor() then
local data = target:getNetVar("doorData")
if not data["locked"] then
if data["lockedid"] then
local data1 = {}
data1["id"] = data["lockedid"]
client:getChar():getInv():add("lock", 1, data)
data["lockedid"] = nil
target:setNetVar("doorData", data)
client:notify("Замок снят!")
else
client:notify("На двери нет замка!")
end
else
client:notify("Дверь должна быть открытой, чтобы снять с нее замок!")
end
else
if not target:getNetVar("locked", false) then
if (target:getNetVar("lockedid")) then
client:getChar():getInv():add("lock", 1, data)
target:setNetVar("lockedid", nil)
client:notify("Замок снят!")
else
client:notify("На контейнере нет замка!")
end
else
client:notify("Контейнер должен быть открытым, чтобы снять с него замок!")
end
end
else
client:notify("Вы должны смотреть на дверь или контейнер!")
end
end
})
function PLUGIN:OnContainerSpawned(container, item, load)
container:SetModel(item.model)
container:PhysicsInit(SOLID_VPHYSICS)
container:SetMoveType(MOVETYPE_VPHYSICS)
container:SetUseType(SIMPLE_USE)
local physicsObject = container:GetPhysicsObject()
if (IsValid(physicsObject)) then
physicsObject:EnableMotion(true)
physicsObject:Wake()
end
container.owner = item.player:getChar():getID()
container.selfMat = container:GetMaterial()
if (!load == true) then
container:SetMaterial("models/wireframe")
end
container.item = item
local invData = {
name = item.name,
desc = item.desc,
width = item.invW,
height = item.invH,
locksound = item.locksound,
opensound = item.opensound
}
container.invData = invData
container.money = 0
container:setNetVar("uid", item.uniqueID)
end
function PLUGIN:LoadData()
local savedTable = self:getData() or {}
for k, v in ipairs(savedTable) do
local container = ents.Create("nut_container")
container:SetPos(v.pos)
container:SetAngles(v.ang)
container:Spawn()
container:SetModel(v.model)
container:PhysicsInit(SOLID_VPHYSICS)
container:SetMoveType(MOVETYPE_VPHYSICS)
container:SetUseType(SIMPLE_USE)
local physicsObject = container:GetPhysicsObject()
if (IsValid(physicsObject)) then
physicsObject:EnableMotion(false)
physicsObject:Sleep()
end
container.owner = v.owner
container.selfMat = v.selfMat
container.item = v.item
container.invData = v.invData
container.money = v.money
container.placed = true
container.lockedid = v.lockedid
container:setNetVar("uid", v.uid)
container:setNetVar("locked", v.locked)
nut.item.restoreInv(v.id, v.invData.width, v.invData.height, function(inventory)
if (IsValid(container)) then
container:setInventory(inventory)
end
end)
end
end
function PLUGIN:SaveData()
self:saveContainer()
end
function PLUGIN:saveContainer()
local saveTable = {}
for k, v in ipairs(ents.FindByClass("nut_container")) do
if v.placed == true then
table.insert(saveTable, {
model = v:GetModel(),
pos = v:GetPos(),
ang = v:GetAngles(),
item = v.item,
owner = v.owner,
invData = v.invData,
selfMat = v.selfMat,
id = v:getNetVar("id"),
money = v:getMoney(),
lockedid = v.lockedid,
locked = v:getNetVar("locked", false),
uid = v:getNetVar("uid")
})
end
end
self:setData(saveTable)
end
if (CLIENT) then
local PLUGIN = PLUGIN
netstream.Hook("ContainerMoney", function(value, index)
if (!IsValid(nut.gui["inv"..index])) then
return
end
nut.gui["inv"..index].money = value
end)
netstream.Hook("invOpen2", function(entity, index, lave)
netstream.Start("EntGiveMoney", entity, 0)
local char = LocalPlayer():getChar()
if (IsValid(nut.gui.inv1)) or (IsValid(invent_info_kek)) or (IsValid(equipment_panel)) or (IsValid(equipment)) then return false end
if (char) then
nut.gui.inv1 = vgui.Create("nutInventory")
nut.gui.inv1:ShowCloseButton(false)
local inventory2 = char:getInv()
if (inventory2) then nut.gui.inv1:setInventory(inventory2) end
nut.gui.inv1:SetSize(nut.gui.inv1:GetWide(), nut.gui.inv1:GetTall())
nut.gui.inv1:SetPos(ScrW()*0.6592, ScrH()*0.29)
invent_info_kek = vgui.Create("invent_info_kek")
invent_info_kek:SetPos(ScrW()*0.6592, ScrH()*0.067)
invent_info_kek:SetSize(invent_info_kek:GetSize())
safebox_menuINV = vgui.Create("nutInventory")
safebox_menuINV:ShowCloseButton(false)
safebox_menuINV:SetTitle("")
safebox_menuINV:setInventory(nut.item.inventories[index])
safebox_menuINV:SetPos(ScrW()*0.035, ScrH()*0.29)
function safebox_menuINV:Paint(w, h)
nut.util.drawBlur(self, 10)
surface.SetDrawColor(Color( 20, 20, 20, 220))
surface.DrawRect( 0, 0, w, h )
surface.DrawOutlinedRect(0, 0, w, h)
surface.SetDrawColor(0, 0, 14, 150)
surface.DrawRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033)
surface.SetDrawColor(Color( 30, 30, 30, 90))
surface.DrawOutlinedRect(ScrW() * 0, ScrH() * 0, ScrW() * 0.41, ScrH() * 0.033) --шапка
draw.DrawText("Инвентарь", "Roh20", ScrW() * 0.005, ScrH() * 0.003, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT )
surface.SetDrawColor(Color( 138, 149, 151, 60))
surface.DrawLine(ScrW() * 0.018, ScrH() * 0.0325, ScrW() * 0.29, ScrH() * 0.0325)
surface.SetDrawColor(Color( 0, 33, 55, 210))
surface.DrawRect(ScrW() * 0.017, ScrH() * 0.059, ScrW() * 0.2715, ScrH() * 0.027) --верхняя панель крафта
draw.DrawText("Тайник", "Roh20", ScrW() * 0.02, ScrH() * 0.06, Color(255, 255, 255, 210), TEXT_ALIGN_LEFT )
surface.SetDrawColor(Color( 0, 0, 0, 255))
surface.DrawOutlinedRect(ScrW() * 0.0165, ScrH() * 0.059, ScrW() * 0.273, ScrH() * 0.53) --обводка модели игрока
surface.SetDrawColor( Color(125, 105, 0, 40) )
surface.SetMaterial( Material("lgh/circle_gradient.png") )
surface.DrawTexturedRectUV( -ScrW() * 0.01, ScrH() * 0.657, ScrW() * 0.35, ScrH() * 0.032, 1, 0.9, 0, 0.3 )
end
case_info_kek = vgui.Create("safe_info_kek")
case_info_kek:SetPos(ScrW()*0.035, ScrH()*0.067)
case_info_kek:SetSize(case_info_kek:GetSize())
equipment_panel = vgui.Create("equipment_panel")
equipment_panel:SetPos(ScrW()*0.35, ScrH()*0.29)
equipment_panel:SetSize(equipment_panel:GetSize())
safebox_menuINV.OnClose = function(this)
if (IsValid(nut.gui.inv1) and !IsValid(nut.gui.menu)) then
nut.gui.inv1:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
case_info_kek:Remove()
end
end
local oldClose = nut.gui.inv1.OnClose
nut.gui.inv1.OnClose = function()
if (IsValid(safebox_menuINV) and !IsValid(nut.gui.menu)) then
safebox_menuINV:Remove()
invent_info_kek:Remove()
equipment_panel:Remove()
case_info_kek:Remove()
end
nut.gui.inv1.OnClose = oldClose
end
end
nut.gui["inv"..index] = safebox_menuINV
local function paintDtextEntry(s, w, h)
surface.SetDrawColor(0, 0, 14, 100)
surface.DrawRect(0, 0, w, h)
s:DrawTextEntryText(color_white, color_white, color_white)
end
local entry = nut.gui.inv1:Add("DTextEntry")
entry:SetSize(ScrW() * 0.173, ScrH() * 0.0325)
entry:SetPos(ScrW() * 0.017, ScrH() * 0.608)
entry:SetValue(0)
entry:SetNumeric(true)
entry.Paint = paintDtextEntry
entry:SetFont("Roh20")
entry:SetTextColor(Color(255, 255, 255, 210))
entry.OnEnter = function()
local value = tonumber(entry:GetValue()) or 0
if LocalPlayer():getChar():hasMoney(value) and value > 0 then
surface.PlaySound("hgn/crussaria/items/itm_gold_down.wav")
netstream.Start("TakeMoney", value)
netstream.Start("EntGiveMoney", entity, value)
entry:SetValue(0)
elseif value <= 0 then
nut.util.notify("Вы ввели недействительное значение!")
entry:SetValue(0)
else
nut.util.notify("У вас нет таких денег!")
entry:SetValue(0)
end
end
local transfer = nut.gui.inv1:Add("DButton")
transfer:SetSize( ScrW() * 0.095, ScrH() * 0.0325)
transfer:SetPos(ScrW() * 0.1937, ScrH() * 0.608)
transfer:SetText("Положить")
transfer:SetFont("Roh20")
transfer:SetTextColor(Color(211, 211, 211))
function transfer:Paint( w, h )
if self:IsDown() then
surface.SetDrawColor(Color( 255, 186, 0, 12))
surface.SetMaterial(nut.util.getMaterial("gui/center_gradient"))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 255, 186, 0, 24))
surface.DrawOutlinedRect(0, 0, w, h)
elseif self:IsHovered() then
surface.SetDrawColor(Color( 30, 30, 30, 150))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 0, 0, 0, 235))
surface.DrawOutlinedRect(0, 0, w, h)
else
surface.SetDrawColor(Color( 30, 30, 30, 160))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 0, 0, 0, 235))
surface.DrawOutlinedRect(0, 0, w, h)
end
end
transfer.DoClick = function()
local value = tonumber(entry:GetValue()) or 0
if LocalPlayer():getChar():hasMoney(value) and value > 0 then
surface.PlaySound("hgn/crussaria/items/itm_gold_down.wav")
netstream.Start("TakeMoney", value)
netstream.Start("EntGiveMoney", entity, value)
entry:SetValue(0)
elseif value <= 0 then
nut.util.notify("Вы ввели недействительное значение!")
entry:SetValue(0)
else
nut.util.notify("У вас нет таких денег!")
entry:SetValue(0)
end
end
safebox_menuINV:SetSize(safebox_menuINV:GetWide(), safebox_menuINV:GetTall())
local entry1 = safebox_menuINV:Add("DTextEntry")
entry1:SetSize(ScrW() * 0.173, ScrH() * 0.0325)
entry1:SetPos(ScrW() * 0.017, ScrH() * 0.608)
entry1:SetValue(0)
entry1.Paint = paintDtextEntry
entry1:SetFont("Roh20")
entry1:SetTextColor(Color(255, 255, 255, 210))
entry1:SetNumeric(true)
entry1.OnEnter = function()
local value = tonumber(entry1:GetValue()) or 0
if nut.gui["inv"..index].money >= value and value > 0 then
surface.PlaySound("hgn/crussaria/items/itm_gold_up.wav")
netstream.Start("EntTakeMoney", entity, value)
netstream.Start("GiveMoney", value)
entry1:SetValue(0)
elseif value <= 0 then
nut.util.notify("Вы ввели недействительное значение!")
entry1:SetValue(0)
else
nut.util.notify("Здесь нет таких денег!")
entry1:SetValue(0)
end
end
local transfer1 = safebox_menuINV:Add("DButton")
transfer1:SetSize( ScrW() * 0.095, ScrH() * 0.0325)
transfer1:SetPos(ScrW() * 0.1937, ScrH() * 0.608)
transfer1:SetFont("Roh20")
transfer1:SetTextColor(Color(211, 211, 211))
function transfer1:Paint( w, h )
if self:IsDown() then
surface.SetDrawColor(Color( 255, 186, 0, 12))
surface.SetMaterial(nut.util.getMaterial("gui/center_gradient"))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 255, 186, 0, 24))
surface.DrawOutlinedRect(0, 0, w, h)
elseif self:IsHovered() then
surface.SetDrawColor(Color( 30, 30, 30, 150))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 0, 0, 0, 235))
surface.DrawOutlinedRect(0, 0, w, h)
else
surface.SetDrawColor(Color( 30, 30, 30, 160))
surface.DrawRect(0, 0, w, h)
surface.SetDrawColor(Color( 0, 0, 0, 235))
surface.DrawOutlinedRect(0, 0, w, h)
end
end
transfer1:SetText("Снять")
transfer1.DoClick = function()
local value = tonumber(entry1:GetValue()) or 0
if nut.gui["inv"..index].money >= value and value > 0 then
surface.PlaySound("hgn/crussaria/items/itm_gold_up.wav")
netstream.Start("EntTakeMoney", entity, value)
netstream.Start("GiveMoney", value)
entry1:SetValue(0)
elseif value <= 0 then
nut.util.notify("Вы ввели недействительное значение!")
entry1:SetValue(0)
else
nut.util.notify("Здесь нет таких денег!")
entry1:SetValue(0)
end
print("Я блядь ахуеваю")
end
end)
end
|
function onBuildingSummon(keys)
end |
-- Pulls cookies set by server originnaly in cache_cookies.lua
-- Sends the back to the R server
-- Remove some headers blocked by the Notebooks proxy.
-- This helps with local debugging
ngx.req.clear_header("Cookie")
ngx.req.clear_header("X-CSRF-Token")
-- Add back in the missing headers
local cookie_cache = ngx.shared.cookie_cache
local cookie_string = ""
for _, k in pairs(cookie_cache:get_keys()) do
local dict_val, err = cookie_cache:get(k)
cookie_string = cookie_string .. k .. "=" .. dict_val .. "; "
end
ngx.req.set_header("Cookie", cookie_string)
local csrf_val, err = cookie_cache:get("csrf-token")
if csrf_val ~= nil then
ngx.req.set_header("X-CSRF-Token", csrf_val)
end
|
-- telescope modules
local actions = require "telescope.actions"
local action_state = require "telescope.actions.state"
local pickers = require "telescope.pickers"
local conf = require("telescope.config").values
-- telescope-project modules
local _actions = require "telescope._extensions.project.actions"
local _finders = require "telescope._extensions.project.finders"
local _git = require "telescope._extensions.project.git"
local _utils = require "telescope._extensions.project.utils"
local M = {}
-- Variables that setup can change
local base_dirs
local hidden_files
-- Allow user to set base_dirs
M.setup = function(setup_config)
if setup_config.base_dir then
error "'base_dir' is no longer a valid value for setup. See 'base_dirs'"
end
base_dirs = setup_config.base_dirs or nil
hidden_files = setup_config.hidden_files or false
_git.update_git_repos(base_dirs)
end
-- This creates a picker with a list of all of the projects
M.project = function(opts)
pickers.new(opts or {}, {
prompt_title = "Select a project",
results_title = "Projects",
finder = _finders.project_finder(opts, _utils.get_projects()),
sorter = conf.file_sorter(opts),
attach_mappings = function(prompt_bufnr, map)
local refresh_projects = function()
local picker = action_state.get_current_picker(prompt_bufnr)
local finder = _finders.project_finder(opts, _utils.get_projects())
picker:refresh(finder, { reset_prompt = true })
end
_actions.add_project:enhance { post = refresh_projects }
_actions.delete_project:enhance { post = refresh_projects }
_actions.rename_project:enhance { post = refresh_projects }
-- Project key mappings
map("n", "d", _actions.delete_project)
map("n", "r", _actions.rename_project)
map("n", "c", _actions.add_project)
map("n", "f", _actions.find_project_files)
map("n", "b", _actions.browse_project_files)
map("n", "s", _actions.search_in_project_files)
map("n", "R", _actions.recent_project_files)
map("n", "w", _actions.change_working_directory)
map("i", "<c-d>", _actions.delete_project)
map("i", "<c-v>", _actions.rename_project)
map("i", "<c-a>", _actions.add_project)
map("i", "<c-f>", _actions.find_project_files)
map("i", "<c-b>", _actions.browse_project_files)
map("i", "<c-s>", _actions.search_in_project_files)
map("i", "<c-r>", _actions.recent_project_files)
map("i", "<c-l>", _actions.change_working_directory)
-- Workspace key mappings
map("i", "<c-w>", _actions.change_workspace)
local on_project_selected = function()
-- _actions.find_project_files(prompt_bufnr, hidden_files)
-- [[rakan]] open session on enter
_actions.open_session(prompt_bufnr)
end
actions.select_default:replace(on_project_selected)
return true
end,
}):find()
end
return M
|
local AddonName, AddonTable = ...
AddonTable.mining = {
-- Ore
52183, -- Pyrite Ore
52185, -- Elementium Ore
53038, -- Obsidium Ore
-- Bars
52186, -- Elementium Bar
54849, -- Obsidium Bar
}
|
-- Copyright 2016 Anurag Ranjan and the Max Planck Gesellschaft.
-- All rights reserved.
-- This software is provided for research purposes only.
-- By using this software you agree to the terms of the license file
-- in the root folder.
-- For commercial use, please contact ps-license@tue.mpg.de.
-------------------------
-- Optical Flow Utilities
-------------------------
local stringx = require('pl.stringx')
local M = {}
local eps = 1e-6
local function warp(img, flow)
local mean_pixel = torch.DoubleTensor({123.68/256.0, 116.779/256.0, 103.939/256.0})
result = image.warp(img, flow, 'bilinear', true, 'pad', -1)
for x=1, result:size(2) do
for y=1, result:size(3) do
if result[1][x][y] == -1 and result[2][x][y] == -1 and result[3][x][y] == -1 then
result[1][x][y] = mean_pixel[1]
result[2][x][y] = mean_pixel[2]
result[3][x][y] = mean_pixel[3]
end
end
end
return result
end
M.warp = warp
local function computeNorm(...)
-- check args
local _, flow_x, flow_y = xlua.unpack(
{...},
'opticalflow.computeNorm',
'computes norm (size) of flow field from flow_x and flow_y,\n',
{arg='flow_x', type='torch.Tensor', help='flow field (x), (WxH)', req=true},
{arg='flow_y', type='torch.Tensor', help='flow field (y), (WxH)', req=true}
)
local flow_norm = torch.Tensor()
local x_squared = torch.Tensor():resizeAs(flow_x):copy(flow_x):cmul(flow_x)
flow_norm:resizeAs(flow_y):copy(flow_y):cmul(flow_y):add(x_squared):sqrt()
return flow_norm
end
M.computeNorm = computeNorm
------------------------------------------------------------
-- computes angle (direction) of flow field from flow_x and flow_y,
--
-- @usage opticalflow.computeAngle() -- prints online help
--
-- @param flow_x flow field (x), (WxH) [required] [type = torch.Tensor]
-- @param flow_y flow field (y), (WxH) [required] [type = torch.Tensor]
------------------------------------------------------------
local function computeAngle(...)
-- check args
local _, flow_x, flow_y = xlua.unpack(
{...},
'opticalflow.computeAngle',
'computes angle (direction) of flow field from flow_x and flow_y,\n',
{arg='flow_x', type='torch.Tensor', help='flow field (x), (WxH)', req=true},
{arg='flow_y', type='torch.Tensor', help='flow field (y), (WxH)', req=true}
)
local flow_angle = torch.Tensor()
flow_angle:resizeAs(flow_y):copy(flow_y):cdiv(flow_x):abs():atan():mul(180/math.pi)
flow_angle:map2(flow_x, flow_y, function(h,x,y)
if x == 0 and y >= 0 then
return 90
elseif x == 0 and y <= 0 then
return 270
elseif x >= 0 and y >= 0 then
-- all good
elseif x >= 0 and y < 0 then
return 360 - h
elseif x < 0 and y >= 0 then
return 180 - h
elseif x < 0 and y < 0 then
return 180 + h
end
end)
return flow_angle
end
M.computeAngle = computeAngle
------------------------------------------------------------
-- merges Norm and Angle flow fields into a single RGB image,
-- where saturation=intensity, and hue=direction
--
-- @usage opticalflow.field2rgb() -- prints online help
--
-- @param norm flow field (norm), (WxH) [required] [type = torch.Tensor]
-- @param angle flow field (angle), (WxH) [required] [type = torch.Tensor]
-- @param max if not provided, norm:max() is used [type = number]
-- @param legend prints a legend on the image [type = boolean]
------------------------------------------------------------
local function field2rgb(...)
-- check args
local _, norm, angle, max, legend = xlua.unpack(
{...},
'opticalflow.field2rgb',
'merges Norm and Angle flow fields into a single RGB image,\n'
.. 'where saturation=intensity, and hue=direction',
{arg='norm', type='torch.Tensor', help='flow field (norm), (WxH)', req=true},
{arg='angle', type='torch.Tensor', help='flow field (angle), (WxH)', req=true},
{arg='max', type='number', help='if not provided, norm:max() is used'},
{arg='legend', type='boolean', help='prints a legend on the image', default=false}
)
-- max
local saturate = false
if max then saturate = true end
max = math.max(max or norm:max(), 1e-2)
-- merge them into an HSL image
local hsl = torch.Tensor(3,norm:size(1), norm:size(2))
-- hue = angle:
hsl:select(1,1):copy(angle):div(360)
-- saturation = normalized intensity:
hsl:select(1,2):copy(norm):div(max)
if saturate then hsl:select(1,2):tanh() end
-- light varies inversely from saturation (null flow = white):
hsl:select(1,3):copy(hsl:select(1,2)):mul(-0.5):add(1)
-- convert HSL to RGB
local rgb = image.hsl2rgb(hsl)
-- legend
if legend then
_legend_ = _legend_
or image.load(paths.concat(paths.install_lua_path, 'opticalflow/legend.png'),3)
legend = torch.Tensor(3,hsl:size(2)/8, hsl:size(2)/8)
image.scale(_legend_, legend, 'bilinear')
rgb:narrow(1,1,legend:size(2)):narrow(2,hsl:size(2)-legend:size(2)+1,legend:size(2)):copy(legend)
end
-- done
return rgb
end
M.field2rgb = field2rgb
------------------------------------------------------------
-- Simplifies display of flow field in HSV colorspace when the
-- available field is in x,y displacement
--
-- @usage opticalflow.xy2rgb() -- prints online help
--
-- @param x flow field (x), (WxH) [required] [type = torch.Tensor]
-- @param y flow field (y), (WxH) [required] [type = torch.Tensor]
------------------------------------------------------------
local function xy2rgb(...)
-- check args
local _, x, y, max = xlua.unpack(
{...},
'opticalflow.xy2rgb',
'merges x and y flow fields into a single RGB image,\n'
.. 'where saturation=intensity, and hue=direction',
{arg='x', type='torch.Tensor', help='flow field (norm), (WxH)', req=true},
{arg='y', type='torch.Tensor', help='flow field (angle), (WxH)', req=true},
{arg='max', type='number', help='if not provided, norm:max() is used'}
)
local norm = computeNorm(x,y)
local angle = computeAngle(x,y)
return field2rgb(norm,angle,max)
end
M.xy2rgb = xy2rgb
local function loadFLO(filename)
TAG_FLOAT = 202021.25
local ff = torch.DiskFile(filename):binary()
local tag = ff:readFloat()
if tag ~= TAG_FLOAT then
xerror('unable to read '..filename..
' perhaps bigendian error','readflo()')
end
local w = ff:readInt()
local h = ff:readInt()
local nbands = 2
local tf = torch.FloatTensor(h, w, nbands)
ff:readFloat(tf:storage())
ff:close()
local flow = tf:permute(3,1,2)
return flow
end
M.loadFLO = loadFLO
local function writeFLO(filename, F)
F = F:permute(2,3,1):clone()
TAG_FLOAT = 202021.25
local ff = torch.DiskFile(filename, 'w'):binary()
ff:writeFloat(TAG_FLOAT)
ff:writeInt(F:size(2)) -- width
ff:writeInt(F:size(1)) -- height
ff:writeFloat(F:storage())
ff:close()
end
M.writeFLO = writeFLO
local function loadPFM(filename)
ff = torch.DiskFile(filename):binary()
local header = ff:readString("*l")
local color, nbands
if stringx.strip(header) == 'PF' then
color = true
nbands = 3
else
color = false
nbands = 1
end
local dims = stringx.split(ff:readString("*l"))
local scale = ff:readString("*l")
if tonumber(scale) < 0 then
ff:littleEndianEncoding()
else
ff:bigEndianEncoding()
end
local tf = ff:readFloat(dims[1]*dims[2]*nbands)
ff:close()
tf = torch.FloatTensor(tf):resize(dims[2],dims[1],nbands):permute(3,1,2)
tf = image.vflip(tf)
return tf[{{1,2},{},{}}]
end
M.loadPFM = loadPFM
local function rotate(flow, angle)
local flow_rot = image.rotate(flow, angle, 'simple')
local fu = torch.mul(flow_rot[1], math.cos(-angle)) - torch.mul(flow_rot[2], math.sin(-angle))
local fv = torch.mul(flow_rot[1], math.sin(-angle)) + torch.mul(flow_rot[2], math.cos(-angle))
flow_rot[1]:copy(fu)
flow_rot[2]:copy(fv)
return flow_rot
end
M.rotate = rotate
local function scale(flow, sc, opt)
opt = opt or 'simple'
local flow_scaled = image.scale(flow, '*'..sc, opt)*sc
return flow_scaled
end
M.scale = scale
local function scaleBatch(flow, sc)
local flowR = torch.FloatTensor(opt.batchSize*2, flow:size(3), flow:size(4))
local outputR = torch.FloatTensor(opt.batchSize, 2, flow:size(3)*sc, flow:size(4)*sc)
flowR:copy(flow)
local output = image.scale(flowR, '*'..sc, 'simple')*sc
outputR:copy(output)
return outputR
end
M.scaleBatch = scaleBatch
return M
|
-- @namespace foundation.com.binary_types
local bit = assert(foundation.com.bit)
local ByteBuf = assert(foundation.com.ByteBuf.little)
-- @class BitFlags
local BitFlags = foundation.com.Class:extends("foundation.com.binary_types.BitFlags")
local ic = BitFlags.instance_class
function ic:initialize(size, mapping)
self.m_size = size
self.m_mapping = mapping
end
function ic:size()
return self.m_size
end
function ic:read(stream)
local int, bytes_read = ByteBuf:r_uv(stream, self.m_size)
local result = {}
for key,mask in pairs(self.m_mapping) do
result[key] = bit.band(int, mask)
end
return result, bytes_read
end
function ic:write(stream, map)
local result = 0
for key,mask in pairs(self.m_mapping) do
result = bit.bor(result, bit.band(map[key], mask))
end
return ByteBuf:w_uv(stream, self.m_size, result)
end
foundation.com.binary_types.BitFlags = BitFlags
|
local client = client
local awful = require("awful")
local util = require("awful.util")
local scratch = {}
local defaultRule = {instance = "scratch"}
-- Turn on this scratch window client (add current tag to window's tags,
-- then set focus to the window)
local function turn_on(c)
local current_tag = awful.tag.selected(c.screen)
ctags = {current_tag}
for k,tag in pairs(c:tags()) do
if tag ~= current_tag then table.insert(ctags, tag) end
end
c:tags(ctags)
c:raise()
client.focus = c
end
-- Turn off this scratch window client (remove current tag from window's tags)
local function turn_off(c)
local current_tag = awful.tag.selected(c.screen)
local ctags = {}
for k,tag in pairs(c:tags()) do
if tag ~= current_tag then table.insert(ctags, tag) end
end
c:tags(ctags)
end
function scratch.raise(cmd, rule)
local rule = rule or defaultRule
local function matcher(c) return awful.rules.match(c, rule) end
-- logic mostly copied form awful.client.run_or_raise, except we don't want
-- to change to or merge with scratchpad tag, just show the window
local clients = client.get()
local findex = util.table.hasitem(clients, client.focus) or 1
local start = util.cycle(#clients, findex + 1)
for c in awful.client.iterate(matcher, start) do
turn_on(c)
return
end
-- client not found, spawn it
util.spawn(cmd)
end
function scratch.toggle(cmd, rule, alwaysclose)
local rule = rule or defaultRule
if client.focus and awful.rules.match(client.focus, rule) then
turn_off(client.focus)
else
scratch.raise(cmd, rule)
end
end
return scratch
|
local moon = require("moon")
local socket = require("moon.socket")
local HOST = "127.0.0.1"
local PORT = 23850
-------------------2 bytes len (big endian) protocol------------------------
socket.on("accept", function(fd, msg)
print("accept ", fd, moon.decode(msg, "Z"))
socket.settimeout(fd, 10)
end)
socket.on("message", function(fd, msg)
--echo message to client
socket.write(fd, moon.decode(msg, "Z"))
end)
socket.on("close", function(fd, msg)
print("close ", fd, moon.decode(msg, "Z"))
end)
socket.on("error", function(fd, msg)
print("error ", fd, moon.decode(msg, "Z"))
end)
local listenfd = socket.listen(HOST, PORT, moon.PTYPE_SOCKET)
socket.start(listenfd)--start accept
print("server start ", HOST, PORT)
print("enter 'CTRL-C' stop server.")
moon.shutdown(function()
socket.close(listenfd)
moon.quit()
end)
|
if not system.IsLinux() then return end
--[[
Most of these functions can be called at any time. Send queues what you send until a connection is made.
Only "tcp" and "udp" is supported. Default is tcp. There isn't much of a difference between udp and tcp in this wrapper so you can easily change between the two modes.
By default the socket has a 3 second timeout. The timeout count is started/restarted whenever the mesage is "timeout" and stopped otherwise
luasocket.debug = true
will logn debug messages about sending and receiving data
very useful for (duh) debugging!
-- client
CLIENT = luasocket.Client("udp" or "tcp") -- this defaults to tcp
CLIENT:GetTimeoutDuration()
CLIENT:IsTimingOut()
CLIENT:IsSending()
CLIENT:IsConnected()
CLIENT:SetTimeout(seconds or nil)
CLIENT:GetTimeout()
CLIENT:SetReceiveMode("line" or "all" or bytes)
CLIENT:GetReceiveMode()
CLIENT:OnReceive(str)
-- return false to prevent the socket from being removed
-- if the timeout duration has exceeded the max timeout duration
CLIENT:OnTimeout(count)
CLIENT:OnSend(str, bytes)
CLIENT:OnError(msg)
CLIENT:OnClose()
CLIENT:Connect(ip, port)
--
-- server
SERVER = luasocket.Server("udp" or "tcp") -- this defaults to tcp
SERVER:Host(ip, port)
-- returning false here will close and remove the client
-- returning true will call SetKeepAlive true on the client
SERVER:OnClientConnected(client, ip, port)
SERVER:OnReceive(str, client)
SERVER:OnClientClosed(client)
SERVER:OnClientError(client, msg)
SERVER:GetClients()
SERVER:HasClients() -- returns true if someone is connected, false otherwise
--
-- shared
SHARED:Send(str, instant)
SHARED:GetIP()
SHARED:GetPort()
SHARED:IsValid()
SHARED:Remove()
-- These have Get ones as well but they only return something if Set was called. This uses setoption.
SHARED:SetReuseAddress(val)
SHARED:SetNoDelay(val)
SHARED:SetLinger(val)
SHARED:SetKeepAlive(val)
--
]]
local luasocket = {}
if _G.luasocket and _G.luasocket.Panic then
_G.luasocket.Panic()
end
-- external functions
local on_error = mmyy and mmyy.OnError or error
local logn = logn or MsgN or print
local table_print = PrintTable or table.print or logn
local warning = ErrorNoHalt or logn
local check = check or function() end
local cares = select(2, pcall(require,"cares")) or _G.cares
function luasocket.Initialized()
if gmod then
_G.luasocket = luasocket
hook.Add("Think", "socket_think", function()
luasocket.Update()
end)
end
end
luasocket.socket = require("socket") or _G.socket
function luasocket.DebugPrint(...)
if luasocket.debug then
local tbl = {}
for i = 1, select("#", ...) do
tbl[i] = tostring(select(i, ...))
end
logn(string.format(unpack(tbl)))
end
end
do -- helpers/usage
function luasocket.HeaderToTable(header)
local tbl = {}
if not header then return tbl end
for line in header:gmatch("(.-)\n") do
local key, value = line:match("(.+):%s+(.+)\13")
if key and value then
tbl[key] = value
end
end
return tbl
end
function luasocket.TableToHeader(tbl)
local str = ""
for key, value in pairs(tbl) do
str = str .. tostring(key) .. ": " .. tostring(value) .. "\r\n"
end
return str
end
local function request(url, callback, method, timeout, post_data, user_agent, binary)
url = url:gsub("http://", "")
callback = callback or table_print
method = method or "GET"
user_agent = user_agent or "goluwa"
local host, location = url:match("(.-)/(.+)")
if not location then
host = url:gsub("/", "")
location = ""
end
local socket = luasocket.Client("tcp")
socket:SetTimeout(timeout or 0.5)
socket:Connect(host, 80)
socket:Send(("%s /%s HTTP/1.1\r\n"):format(method, location))
socket:Send(("Host: %s\r\n"):format(host))
socket:Send(("User-Agent: %s\r\n"):format(user_agent))
socket:Send("Connection: Keep-Alive\r\n")
if binary then
socket:SetReceiveMode("all")
end
if method == "POST" then
socket:Send(("Content-Length: %i"):format(#post_data))
socket:Send(post_data)
end
socket:Send("\r\n")
local chunks = {}
function socket:OnReceive(str)
table.insert(chunks, str)
end
function socket:OnClose()
local str = table.concat(chunks, "")
local content
local header
header, content = str:match("(.-\10\13)(.+)")
header = luasocket.HeaderToTable(header)
if header["Content-Length"] then
content = str:sub(-header["Content-Length"])
end
local ok, err = xpcall(callback, on_error, {content = content, header = header})
if err then
warning(err)
end
end
end
function luasocket.Get(url, callback, timeout, user_agent, binary)
check(url, "string")
check(callback, "function", "nil", "false")
check(user_agent, "nil", "string")
return request(url, callback, "GET", timeout, nil, user_agent, binary)
end
function luasocket.Post(url, post_data, callback, timeout, user_agent, binary)
check(url, "string")
check(callback, "function", "nil", "false")
check(post_data, "table", "string")
check(user_agent, "nil", "string")
if type(post_data) == "table" then
post_data = luasocket.TableToHeader(post_data)
end
return request(url, callback, "POST", timeout, post_data, user_agent, binary)
end
function luasocket.WebResource(url, callback)
if url:sub(0, 4) == "http" then
if callback then
luasocket.Get(url, function(data) callback(data.content) end, nil, nil, true)
else
return {Download = function(_, callback) luasocket.Get(url, function(data) callback(data.content) end, nil, nil, true) end}
end
end
return false
end
local sck = luasocket.socket.udp()
function luasocket.SendUDPData(ip, port, str)
if not str and type(port) == "string" then
str = port
port = tonumber(ip:match(".-:(.+)"))
end
local ok, msg = sck:sendto(str, ip, port)
if ok then
luasocket.DebugPrint("SendUDPData sent data to %s:%i (%s)", ip, port, str)
else
luasocket.DebugPrint("SendUDPData failed %q", msg)
end
return ok, msg
end
end
local receive_types = {all = "*a", line = "*l"}
do -- tcp socket meta
local NULL = {}
NULL.IsNull = true
local function FALSE()
return false
end
function NULL:__tostring()
return "NULL"
end
function NULL:__index(key)
if key == "ClassName" then
return "NULL"
end
if key == "Type" then
return "null"
end
if key == "IsValid" then
return FALSE
end
if type(key) == "string" and key:sub(0, 2) == "Is" then
return FALSE
end
error(("tried to index %q on a NULL socket"):format(key), 2)
end
local sockets = {}
function luasocket.GetSockets()
return sockets
end
function luasocket.Panic()
for key, sock in pairs(sockets) do
if sock:IsValid() then
sock:DebugPrintf("removed from luasocket.Panic()")
sock:Remove()
else
table.remove(sockets, key)
end
end
end
function luasocket.Update()
for key, sock in pairs(sockets) do
if sock:IsValid() then
local ok, err = xpcall(sock.Think, on_error, sock)
if not ok then
warning(err)
sock:Remove()
end
else
sockets[key] = nil
end
if sock.remove_me then
sock.socket:close()
setmetatable(sock, NULL)
end
end
end
local function assert(res, err)
if not res then
error(res, 3)
end
return res
end
local function new_socket(override, META, typ)
typ = typ or "tcp"
typ = typ:lower()
if typ == "udp" or typ == "tcp" then
local self = {}
self.socket = override or assert(luasocket.socket[typ]())
self.socket:settimeout(0)
self.socket_type = typ
local obj = setmetatable(self, META)
obj:Initialize()
table.insert(sockets, obj)
obj:DebugPrintf("created")
return obj
end
end
local function remove_socket(self)
self.remove_me = true
end
local options =
{
KeepAlive = "keepalive",
Linger = "linger",
ReuseAddress = "ReuseAddr",
NoDelay = "tcp-nodelay",
}
local function add_options(tbl)
for func_name, key in pairs(options) do
tbl["Set" .. func_name] = function(self, val)
self.socket:setoption(key, val)
self:DebugPrintf("option[%q] = %s", key, val)
self[func_name] = val
end
tbl["Get" .. func_name] = function(self, val)
return self[func_name]
end
end
end
do -- client
local CLIENT = {}
CLIENT.__index = CLIENT
CLIENT.Type = "socket"
CLIENT.ClassName = "client"
add_options(CLIENT)
function CLIENT:Initialize()
self.Buffer = {}
self:SetTimeout(3)
end
function CLIENT:__tostring()
return string.format("client_%s[%s][%s]", self.socket_type, self:GetIP() or "none", self:GetPort() or "0")
end
function CLIENT:DebugPrintf(fmt, ...)
luasocket.DebugPrint("%s - " .. fmt, self, ...)
end
function CLIENT:Connect(ip, port, skip_cares)
check(ip, "string")
check(port, "number")
if not skip_cares and cares and cares.Resolve then
self:DebugPrintf("using cares to resolve domain %s", ip)
cares.Resolve(ip, function(_, errored, newip)
if not errored then
self:DebugPrintf("cares resolved domain from %q to %q", ip, newip)
self:Connect(newip, port, true)
else
self:DebugPrintf("cares errored resolving domain %s with code %s", ip, errored)
self:Connect(ip, port, true)
end
end)
return
end
self:DebugPrintf("connecting to %s:%s", ip, port)
local ok, msg
if self.socket_type == "tcp" then
ok, msg = self.socket:connect(ip, port)
else
ok, msg = self.socket:setpeername(ip, port)
end
if not ok and msg and msg ~= "timeout" then
self:DebugPrintf("connect failed: %s", msg)
self:OnError(msg)
else
self.connecting = true
end
end
function CLIENT:Send(str, instant)
if self.socket_type == "tcp" then
if instant then
local bytes, b, c, d = self.socket:send(str)
if bytes then
self:DebugPrintf("sucessfully sent %q", str)
self:OnSend(str, bytes, b,c,d)
end
else
table.insert(self.Buffer, str)
end
else
self.socket:send(str)
self:DebugPrintf("sent %q", str)
end
end
CLIENT.ReceiveMode = "all"
function CLIENT:SetReceiveMode(type)
self.ReceiveMode = type
end
function CLIENT:GetReceiveMode()
return self.ReceiveMode
end
function CLIENT:Think()
local sock = self.socket
sock:settimeout(0)
-- check connection
if self.connecting then
local res, msg = sock:getpeername()
if res then
self:DebugPrintf("connected to %s:%s", res, msg)
-- ip, port = res, msg
self.connected = true
self.connecting = nil
self:OnConnect(res, msg)
self:Timeout(false)
elseif msg == "timeout" or msg == "getpeername failed" then
self:Timeout(true)
else
self:DebugPrintf("errored: %s", msg)
self:OnError(msg)
end
end
if self.connected then
-- try send
if self.socket_type == "tcp" then
for i = 1, 128 do
local data = self.Buffer[1]
if data then
local bytes, b, c, d = sock:send(data)
if bytes then
self:DebugPrintf("sucessfully sent %q", data)
self:OnSend(data, bytes, b,c,d)
table.remove(self.Buffer, 1)
elseif b ~= "Socket is not connected" then
self:DebugPrintf("could not send %s : %s", data, b)
break
end
else
break
end
end
end
-- try receive
local mode
if self.socket_type == "udp" then
mode = 1024
else
mode = receive_types[self.ReceiveMode] or self.ReceiveMode
end
local data, err, partial = sock:receive(mode)
if not data and partial and partial ~= "" then
data = partial
end
if data then
if data:find("\n") then
self:DebugPrintf("received (mode %s) %i bytes of data", mode, #data)
else
self:DebugPrintf("received (mode %s) %i bytes of data (%q)", mode, #data, data)
end
self:OnReceive(data)
self:Timeout(false)
if self.__server then
self.__server:OnReceive(data, self)
end
elseif err == "timeout" or "Socket is not connected" then
self:Timeout(true)
elseif err == "closed" then
self:DebugPrintf("closed")
if not self.__server or self.__server:OnClientClosed(self) ~= false then
self:Remove()
end
else
self:DebugPrintf("errored: %s", err)
if self.__server then
self.__server:OnClientError(self3, err)
end
self:OnError(err)
end
end
end
do -- timeout
function CLIENT:Timeout(bool)
if not self.TimeoutLength then return end
if not bool then
self.TimeoutStart = nil
return
end
local time = os.clock()
if not self.TimeoutStart then
self.TimeoutStart = time + self.TimeoutLength
end
local seconds = time - self.TimeoutStart
if self:OnTimeout(seconds) ~= false then
if seconds > self.TimeoutLength then
self:DebugPrintf("timed out")
self:Remove()
end
end
end
function CLIENT:GetTimeoutDuration()
if not self.TimeoutStart then return 0 end
local t = os.clock()
return t - self.TimeoutStart
end
function CLIENT:IsTimingOut()
return
end
function CLIENT:SetTimeout(seconds)
self.TimeoutLength = seconds
end
function CLIENT:GetTimeout()
return self.TimeoutLength or math.huge
end
end
function CLIENT:Remove()
if self.remove_me then return end
self:DebugPrintf("removed")
self:OnClose()
remove_socket(self)
if self.__server then
for k, v in pairs(self.__server.Clients) do
if v == self then
table.remove(self.__server.Clients, k)
break
end
end
self.__server:OnClientClosed(self)
end
end
function CLIENT:IsConnected()
return self.connected == true
end
function CLIENT:IsSending()
return #self.Buffer > 0
end
function CLIENT:GetIP()
if not self.connected then return "nil" end
local ip, port
if self.__server then
ip, port = self.socket:getpeername()
else
ip, port = self.socket:getsockname()
end
return ip
end
function CLIENT:GetPort()
if not self.connected then return "nil" end
local ip, port
if self.__server then
ip, port = self.socket:getpeername()
else
ip, port = self.socket:getsockname()
end
return ip and port or nil
end
function CLIENT:GetIPPort()
if not self.connected then return "nil" end
local ip, port
if self.__server then
ip, port = self.socket:getpeername()
else
ip, port = self.socket:getsockname()
end
return ip .. ":" .. port
end
function CLIENT:GetSocketName()
return self.socket:getpeername()
end
function CLIENT:IsValid()
return true
end
function CLIENT:OnTimeout(count) end
function CLIENT:OnConnect(ip, port) end
function CLIENT:OnReceive(data) end
function CLIENT:OnError(msg) self:Remove() end
function CLIENT:OnSend(data, bytes, b,c,d) end
function CLIENT:OnClose() end
function luasocket.Client(typ)
return new_socket(nil, CLIENT, typ)
end
luasocket.ClientMeta = CLIENT
end
do -- server
local SERVER = {}
SERVER.__index = SERVER
SERVER.Type = "socket"
SERVER.ClassName = "server"
add_options(SERVER)
function SERVER:Initialize()
self.Clients = {}
end
function SERVER:__tostring()
return string.format("server_%s[%s][%s]", self.socket_type, self:GetIP() or "nil", self:GetPort() or "nil")
end
function SERVER:DebugPrintf(fmt, ...)
luasocket.DebugPrint("%s - " .. fmt, self, ...)
end
function SERVER:GetClients()
return self.Clients
end
function SERVER:HasClients()
return next(self.Clients) ~= nil
end
function SERVER:Host(ip, port)
ip = ip or "*"
port = port or 0
local ok, msg
if self.socket_type == "tcp" then
self.socket:setoption("reuseaddr", true)
ok, msg = self.socket:bind(ip, port)
elseif self.socket_type == "udp" then
ok, msg = self.socket:setsockname(ip, port)
end
if not ok and msg then
self:DebugPrintf("bind failed: %s", msg)
self:OnError(msg)
else
if self.socket_type == "tcp" then
ok, msg = self.socket:listen()
if not ok and msg then
self:DebugPrintf("bind failed: %s", msg)
self:OnError(msg)
end
end
self.ready = true
end
end
SERVER.Bind = SERVER.Host
function SERVER:Send(data, ip, port)
check(ip, "string")
if self.socket_type == "tcp" then
for key, client in pairs(self:GetClients()) do
if client:GetIP() == ip and (not port or (port == client:GetPort())) then
client:Send(data)
break
end
end
elseif self.socket_type == "udp" then
check(port, "number")
self.socket:sendto(data, ip, port)
end
end
local DUMMY = {}
DUMMY.__index = DUMMY
DUMMY.__tostring = function(s)
return string.format("dummy_client_%s[%s][%s]", "udp", s.ip or "nil", s.port or "nil")
end
DUMMY.GetIP = function(s) return s.ip end
DUMMY.GetPort = function(s) return s.port end
DUMMY.IsValid = function() return true end
DUMMY.Close = function() return end
DUMMY.Remove = function() return end
local function create_dummy_client(ip, port)
return setmetatable({ip = ip, port = port}, DUMMY)
end
function SERVER:Think()
if not self.ready then return end
if self.socket_type == "udp" then
local data, ip, port = self.socket:receivefrom()
if ip == "timeout" then return end
if not data then
self:DebugPrintf("errored: %s", ip)
else
self:DebugPrintf("received %s from %s:%s", data, ip, port)
local client = create_dummy_client(ip, port)
local b = self:OnClientConnected(client, ip, port)
if b == true or b == nil then
self:OnReceive(data, client)
end
client.IsValid = function() return false end
end
elseif self.socket_type == "tcp" then
local sock = self.socket
sock:settimeout(0)
local client, err = sock:accept()
if client then
client = new_socket(client, luasocket.ClientMeta, "tcp")
client.connected = true
self:DebugPrintf("%s connected", client)
table.insert(self.Clients, client)
client.__server = self
local b = self:OnClientConnected(client, client:GetIP(), client:GetPort())
if b == true then
client:SetKeepAlive(true)
client:SetTimeout()
elseif b == false then
client:Remove()
end
end
end
end
function SERVER:SuppressSend(client)
self.suppressed_send = client
end
function SERVER:Broadcast(...)
for k,v in pairs(self:GetClients()) do
if self.suppressed_send ~= v then
v:Send(...)
end
end
end
function SERVER:KickAllClients()
for k,v in pairs(self:GetClients()) do
v.__server = nil
v:Remove()
end
end
function SERVER:Remove()
self:DebugPrintf("removed")
self:KickAllClients()
remove_socket(self)
end
function SERVER:IsValid()
return true
end
function SERVER:GetIP()
local ip, port = self.socket:getsockname()
return ip
end
function SERVER:GetPort()
local ip, port = self.socket:getsockname()
return ip and port or nil
end
function SERVER:GetIPPort()
local ip, port = self.socket:getsockname()
return ip .. ":" .. port
end
function SERVER:GetSocketName()
return self.socket:getsockname()
end
function SERVER:OnClientConnected(client, ip, port) end
function SERVER:OnClientClosed(client) end
function SERVER:OnReceive(data, client) end
function SERVER:OnClientError(client, err) end
function SERVER:OnError(msg) self:Remove() end
function luasocket.Server(typ)
return new_socket(nil, SERVER, typ)
end
luasocket.ServerMeta = SERVER
end
end
luasocket.Initialized()
luasocket.Initialized = nil
return luasocket |
--[[ File meta info
@file Localization.lua
@brief Localization strings, translations and client locale check
--]]
--[[
@brief Accessing the addons private table
@var _ addonName, thrown away
@var wt Global addonTable
--]]
local _, wt = ...
-- Table of localized strings
local localeText = {
enUS = {
AVAILABLE_HEADER = "Available Now",
MISSINGREQS_HEADER = "Available but Missing Requirements",
NEXTLEVEL_HEADER = "Coming Soon",
NOTLEVEL_HEADER = "Not Yet Available",
MISSINGTALENT_HEADER = "Missing Required Talents",
KNOWN_HEADER = "Already Known",
COST_FORMAT = "Cost: %s",
TOTALCOST_FORMAT = "Total Cost: %s",
TOTALSAVINGS_FORMAT = "Total Savings: %s",
LEVEL_FORMAT = "Level %s",
TAB_TEXT = "What can I train?",
},
frFR = {
AVAILABLE_HEADER = "Disponible",
MISSINGREQS_HEADER = "Disponible mais pré-requis manquants",
NEXTLEVEL_HEADER = "Bientôt disponible",
NOTLEVEL_HEADER = "Pas encore disponible",
MISSINGTALENT_HEADER = "Talents requis manquants",
KNOWN_HEADER = "Déjà connu",
COST_FORMAT = "Coût : %s",
TOTALCOST_FORMAT = "Coût total : %s",
TOTALSAVINGS_FORMAT = "Coût économisé : %s",
LEVEL_FORMAT = "Niveau %s",
TAB_TEXT = "Que puis-je apprendre ?"
},
ruRU = {
AVAILABLE_HEADER = "Доступен сейчас",
MISSINGREQS_HEADER = "Доступно, но отсутствуют требования",
NEXTLEVEL_HEADER = "Скоро будет",
NOTLEVEL_HEADER = "Пока недоступно",
MISSINGTALENT_HEADER = "Отсутствующие необходимые таланты",
KNOWN_HEADER = "Уже известно",
COST_FORMAT = "Стоимость: %s",
TOTALCOST_FORMAT = "Общая стоимость: %s",
TOTALSAVINGS_FORMAT = "Все сбережения: %s",
LEVEL_FORMAT = "Уровень %s",
TAB_TEXT = "Что я могу изучить?"
},
zhCN = {
AVAILABLE_HEADER = "可学",
MISSINGREQS_HEADER = "满足条件方可学习",
NEXTLEVEL_HEADER = "即将学习",
NOTLEVEL_HEADER = "等级不够",
MISSINGTALENT_HEADER = "缺少相关天赋",
KNOWN_HEADER = "已学技能",
COST_FORMAT = "花费: %s",
TOTALCOST_FORMAT = "总花费: %s",
TOTALSAVINGS_FORMAT = "总共节省: %s",
LEVEL_FORMAT = "等级 %s",
TAB_TEXT = "我能学什么技能?"
},
zhTW = {
AVAILABLE_HEADER = "現在可以訓練",
MISSINGREQS_HEADER = "可以訓練但是缺少需求條件",
NEXTLEVEL_HEADER = "即將可以訓練",
NOTLEVEL_HEADER = "還不可以訓練",
MISSINGTALENT_HEADER = "缺少需要的天賦",
KNOWN_HEADER = "已學會",
COST_FORMAT = "花費: %s",
TOTALCOST_FORMAT = "總需花費: %s",
TOTALSAVINGS_FORMAT = "總共省下: %s",
LEVEL_FORMAT = "等級 %s",
TAB_TEXT = "我可以接受什麼訓練?"
},
deDE = {
AVAILABLE_HEADER = "Jetzt verfügbar",
MISSINGREQS_HEADER = "Verfügbar, aber fehlende Anforderungen",
NEXTLEVEL_HEADER = "Demnächst",
NOTLEVEL_HEADER = "Noch nicht verfügbar",
MISSINGTALENT_HEADER = "Fehlende Talente",
KNOWN_HEADER = "Bereits bekannt",
COST_FORMAT = "Kosten: %s",
TOTALCOST_FORMAT = "Gesamtkosten: %s",
TOTALSAVINGS_FORMAT = "Gesamtersparnis: %s",
LEVEL_FORMAT = "Level %s",
TAB_TEXT = "Was kann ich Lernen?"
},
koKR = {
AVAILABLE_HEADER = "지금 사용 가능",
MISSINGREQS_HEADER = "사용 가능하지만 누락된 요구 사항",
NEXTLEVEL_HEADER = "곧 사용 가능",
NOTLEVEL_HEADER = "아직 사용 불가",
MISSINGTALENT_HEADER = "필수 특성 누락",
KNOWN_HEADER = "이미 배움",
COST_FORMAT = "비용: %s",
TOTALCOST_FORMAT = "총 비용: %s",
TOTALSAVINGS_FORMAT = "총 절감: %s",
LEVEL_FORMAT = "레벨 %s",
TAB_TEXT = "무엇을 훈련할 수 있나요?"
}
}
-- Set "enUS" as default locale
wt.L = localeText["enUS"]
-- Get current locale from game client
local locale = GetLocale()
-- @brief Check if locale is enUS, enGB or nil
-- @return exit to skip localization if default locale
if (locale == "enUS" or locale == "enGB" or localeText[locale] == nil) then
return
end
-- @brief Localization of variables
for k, v in pairs(localeText[locale]) do
wt.L[k] = v
end
|
function string.lastIndexOf(s, pattern, init)
local i = -1
local startIdx, lastIdx = nil, (init or 1) - 1
repeat
startIdx, lastIdx = string.find(s, pattern, lastIdx + 1, true)
if startIdx then
i = startIdx
end
until not startIdx
return i
end |
return {
--//Physics
MaxForce = Vector3.new(2500000, 0, 2500000) ;
MaxSpeed = 187.5 ;
MaxPower = 10 ;
MaxBrake = 20 ;
PowerMovementSpeed = 5 ;
BrakeMovementSpeed = 5 ;
IsCombinedLever = true ; --Use a combined brake/lever handle
Lever1Notches = 4 ; --(THROTTLE LEVER)
Lever2Notches = 6 ; --(BRAKE LEVER) if IsCombinedLever is true, this will act as the brake section
--//Keybinds
Keybinds = {
Keyboard = {
IncreaseLever1 = Enum.KeyCode.W ;
DecreaseLever1 = Enum.KeyCode.S ;
IncreaseLever2 = Enum.KeyCode.L ;
DecreaseLever2 = Enum.KeyCode.Semicolon ;
SwitchCab = Enum.KeyCode.C ;
} ;
Gamepad = {
IncreaseLever1 = Enum.KeyCode.ButtonR2 ;
DecreaseLever1 = Enum.KeyCode.ButtonR1 ;
IncreaseLever2 = Enum.KeyCode.ButtonL2 ;
DecreaseLever2 = Enum.KeyCode.ButtonL1 ;
SwitchCab = Enum.KeyCode.ButtonY ;
} ;
} ;
--//Misc
CabSwitchSpeed = 0
}
|
object_ship_nova_orion_smuggler_heavy_tier7 = object_ship_shared_nova_orion_smuggler_heavy_tier7:new {
}
ObjectTemplates:addTemplate(object_ship_nova_orion_smuggler_heavy_tier7, "object/ship/nova_orion_smuggler_heavy_tier7.iff")
|
--[[
LuCI - Lua Configuration Interface
Copyright 2008 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ast = require("luci.asterisk")
local function find_outgoing_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "dialplan",
function(s)
if not h[s['.name']] then
c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] }
h[s['.name']] = true
end
end)
return c
end
local function find_incoming_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "sip",
function(s)
if s.context and not h[s.context] and
uci:get_bool("asterisk", s['.name'], "provider")
then
c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context }
h[s.context] = true
end
end)
return c
end
--
-- SIP phone info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Phone Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Phone %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "phones")
)
end
return form
--
-- SIP phone configuration
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Client")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "friend",
qualify = "yes",
host = "dynamic",
nat = "no",
canreinvite = "no"
}
back = peer:option(DummyValue, "_overview", "Back to phone overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "phones")
active = peer:option(Flag, "disable", "Account enabled")
active.enabled = "yes"
active.disabled = "no"
function active.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "yes"
end
exten = peer:option(Value, "extension", "Extension Number")
cbimap.uci:foreach("asterisk", "dialplanexten",
function(s)
exten:value(
s.extension,
"%s (via %s/%s)" %{ s.extension, s.type:upper(), s.target }
)
end)
display = peer:option(Value, "callerid", "Display Name")
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
regtimeout = peer:option(Value, "registertimeout", "Registration Time Value")
function regtimeout.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "60"
end
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
linekey = peer:option(ListValue, "_linekey", "Linekey Mode (broken)")
linekey:value("", "Off")
linekey:value("trunk", "Trunk Appearance")
linekey:value("call", "Call Appearance")
dialplan = peer:option(ListValue, "context", "Assign Dialplan")
dialplan.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans")
for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do
dialplan:value(unpack(v))
end
incoming = peer:option(StaticList, "incoming", "Receive incoming calls from")
for _, v in ipairs(find_incoming_contexts(cbimap.uci)) do
incoming:value(unpack(v))
end
--function incoming.cfgvalue(...)
--error(table.concat(MultiValue.cfgvalue(...),"."))
--end
return cbimap
end
|
---
-- This is a sample program file for the MoonDrop IRC Bot Framework.
-- This file will create a bot, bind a couple of functions to it, and
-- connect it to a local IRC server running on port 6667.
local MoonDrop = require("moondrop")
local txt = require("moondrop.textutils")
Client = MoonDrop()
Client:setNick("MoonDrop")
Client:setUserName("MoonDrop")
Client:setRealName("MoonDrop Bot")
Client:on("ready", function(self)
local channel = self:open("#channel")
channel:on("ready", function(self)
self:on("PRIVMSG", function(self, user, message)
if message == "Hello, MoonDrop!" then
self:message("Hello, " .. txt.nick_from_address(user) .. "!")
end
end)
self:on("PRIVMSG", function(self, user, message)
if message == "Go away, MoonDrop!" then
self:message("Okay, " .. txt.nick_from_address(user) .. "!")
self:getClient():quit(txt.nick_from_address(user) .. " said to go away!")
end
end)
end)
end)
Client:connect("localhost", 6667)
|
--[[
################################################################################
#
# Copyright (c) 2014-2017 Ultraschall (http://ultraschall.fm)
#
# 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 info = debug.getinfo(1,'S');
script_path = info.source:match[[^@?(.*[\/])[^\/]-$]]
dofile(script_path .. "ultraschall_helper_functions.lua")
--[[reaper.GetPlayState()
0=stop,
1=playing,
2=pause,
5=is recording
6=record paused
]]
function main()
state = reaper.GetPlayState()
if state == 5 then -- is recording
--[[type:
0=OK,
1=OKCANCEL,
2=ABORTRETRYIGNORE,
3=YESNOCANCEL,
4=YESNO,
5=RETRYCANCEL]]
type = 4
title = "Stop Recording?"
msg = "Stop the currently running recording. No more audio will be recorded to disk."
-- Safe-Mode Toggle-Logic
A,SafeModeToggleState=ultraschall.GetUSExternalState("Ultraschall_Transport", "Safemode_Toggle") -- Get the Safemode-Toggle-State
if SafeModeToggleState=="OFF" then -- If Safe-Mode is OFF, show no message-box
result = 6
elseif SafeModeToggleState=="ON" or SafeModeToggleState=="" or SafeModeToggleState=="-1" then -- If Safe-Mode is ON or was never toggled, show the message-box
result=reaper.ShowMessageBox( msg, title, type )
end
--[[result:
1=OK,
2=CANCEL,
3=ABORT,
4=RETRY,
5=IGNORE,
6=YES,
7=NO
]]
if result == 6 then -- it's ok to stop the recording
reaper.OnPauseButton()
end
elseif state == 1 then -- playing
reaper.OnPauseButton()
else -- stop or pause
reaper.OnPlayButton()
end
end
reaper.defer(main)
|
local form = require "sailor.form"
local model = require "sailor.model"
local User = model("user")
describe("Testing form generator", function()
local u = User:new()
it("should not create fields that don't exist", function ()
assert.has_error(
function() form.blah(u,'password') end
)
end)
it("should create a generic field accordingly", function()
local html = form.text(u,'password')
assert.equal('<input type="text" name="user:password" id="user:password" />',html)
end)
it("should create textarea field accordingly", function()
local html = form.textarea(u,'password')
assert.equal(html,'<textarea name="user:password" id="user:password" ></textarea>')
end)
it("should create a dropdown list accordingly", function()
local html = form.dropdown(u,'password',{'a','b'},'Select...')
assert.equal(html,'<select name="user:password" id="user:password" > <option value="" selected>Select...</option> <option value="1">a</option> <option value="2">b</option> </select>')
end)
it("should create a radio list accordingly", function()
local html = form.radio_list(u,'password',{'a','b'},1,'vertical')
assert.equal(html,'<input type="radio" value="1" checked /> a <br/><input type="radio" value="2" /> b')
end)
it("should create a checkbox accordingly", function()
local html = form.checkbox(u,'password',nil, true)
assert.equal(html,'<input type="checkbox" name="user:password" id="user:password" checked /> password')
end)
end)
|
local playsession = {
{"Wellow", {539559}},
{"Knugn", {688459}},
{"Krono", {502585}},
{"FAChyba", {523032}},
{"npo6ka", {1879}},
{"jbro1231", {79574}},
{"120148", {293929}},
{"mariyuchi", {703}},
{"Sneakypoop", {590129}},
{"kalenmonster", {1140295}},
{"borgez_fact", {9222}},
{"Ry_Blackcat", {13391}},
{"GuidoCram", {161088}},
{"waxman", {567327}},
{"AgileW", {89539}},
{"TCP", {335}},
{"Jeffthermite", {884463}},
{"nakedzeldas", {256}},
{"samnrad", {347}},
{"blue_libra", {9544}},
{"twice2double", {6461}}
}
return playsession |
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author (gustaf@thrivingventures.com).
]]
local plugin = plugin
plugin:IncludeFile("shared.lua", SERVERGUARD.STATE.SHARED)
plugin:IncludeFile("imports/ulx.lua", SERVERGUARD.STATE.SERVER)
function plugin:Load(addon, import)
addon, import = string.lower(addon), string.lower(import)
local addonTable = self[addon]
if (addonTable) then
if (addonTable[import]) then
local bSuccess, message = addonTable[import]()
if (bSuccess) then
serverguard.PrintConsole(string.format("%s %s imported successfully.\n", addon, import))
elseif (message) then
serverguard.PrintConsole(string.format("%s %s failed to import (%s).\n", addon, import, message))
else
serverguard.PrintConsole(string.format("%s %s failed to import.\n", addon, import))
end
else
serverguard.PrintConsole(string.format("%s has no import for %q.\n", addon, import))
end
else
serverguard.PrintConsole(string.format("No imports found for %s.\n", addon))
end
end
concommand.Add("serverguard_import", function(player, command, arguments)
if (util.IsConsole(player)) then
local addon = arguments[1]
local import = arguments[2]
if (not addon or not import) then
serverguard.PrintConsole("You must specify an addon and what to import from it.\n")
return
end
plugin:Load(addon, import)
end
end) |
return {
id = "octopus",
name = "Octopus",
description = "Smart denizen of the sea!",
type = "hat",
rarity = 4,
hidden = false,
}
|
object_static_item_eqp_camping_cot_s3 = object_static_item_shared_eqp_camping_cot_s3:new {
}
ObjectTemplates:addTemplate(object_static_item_eqp_camping_cot_s3, "object/static/item/eqp_camping_cot_s3.iff")
|
realgames = {
sprite("Milestone/APEX.jpg"),
sprite("Milestone/EGT.jpg"),
sprite("Milestone/REvo.jpg"),
sprite("Milestone/S1.jpg"),
sprite("Milestone/S2.jpg"),
sprite("Milestone/SBK2011.jpg"),
sprite("Milestone/SBK.jpg"),
sprite("Milestone/SCAR.jpg"),
sprite("Milestone/XFUK.jpg"), --9
sprite("Milestone/ERE.jpg"),
}
pos = {
{ 200, 200 },
{ 600, 600 },
{ 1350, 550 },
{ 300, 400 },
{ 500, 200 },
{ 1100, 150 },
{ 1500, 200 },
{ 900, 500 },
{ 1400, 250 },
{ 800, 100 },
}
title = text(_TEXT);
function reset()
state = 0;
time0 = 0;
end
function draw(time)
time = time - time0;
if (state == 0) then
for i = 1, 8 do
local alpha = 2*time - i
local x, y = pos[i][1], pos[i][2];
realgames[i].draw(x, y, alpha);
end
elseif (state == 1) then
for i = 1, #realgames do
local alpha = 2*time - (i - 8)
local x, y = pos[i][1], pos[i][2];
if (i <= 8) then
alpha = 1
end
realgames[i].draw(x, y, alpha);
end
elseif (state == 2) then
for i = 1, #realgames do
local x, y = pos[i][1], pos[i][2];
if (i <= 8) then
y = y + 981 * time * time;
end
realgames[i].draw(x, y, 1);
end
elseif (state == 3) then
for i = 8, 10 do
local x, y = pos[i][1], pos[i][2];
local alpha = 1;
if (i <= 8) then
alpha = 2*time
end
realgames[i].draw(x, y, alpha);
end
end
-- title.draw();
end
function click(time)
state = state + 1;
time0 = time;
if (state == 4) then
next();
end
end
|
local CMaxTable, parent = torch.class('nn.CMaxTable', 'nn.Module')
function CMaxTable:__init()
parent.__init(self)
self.gradInput = {}
self.maxIdx = torch.Tensor()
self.mask = torch.Tensor()
self.maxVals = torch.Tensor()
self.gradMaxVals = torch.Tensor()
end
function CMaxTable:updateOutput(input)
self.output:resizeAs(input[1]):copy(input[1])
self.maxIdx:resizeAs(input[1]):fill(1)
for i=2,#input do
self.maskByteTensor = self.maskByteTensor or
(torch.type(self.output) == 'torch.CudaTensor' and
torch.CudaByteTensor() or torch.ByteTensor())
self.mask:gt(input[i], self.output)
self.maskByteTensor:resize(self.mask:size()):copy(self.mask)
self.maxIdx:maskedFill(self.maskByteTensor, i)
self.maxVals:maskedSelect(input[i], self.maskByteTensor)
self.output:maskedCopy(self.maskByteTensor, self.maxVals)
end
return self.output
end
function CMaxTable:updateGradInput(input, gradOutput)
for i=1,#input do
self.gradInput[i] = self.gradInput[i] or input[i].new()
self.gradInput[i]:resizeAs(input[i]):fill(0.0)
self.maskByteTensor = self.maskByteTensor or
(torch.type(self.output) == 'torch.CudaTensor' and
torch.CudaByteTensor() or torch.ByteTensor())
self.mask:eq(self.maxIdx, i)
self.maskByteTensor:resize(self.mask:size()):copy(self.mask)
self.gradMaxVals:maskedSelect(gradOutput, self.maskByteTensor)
self.gradInput[i]:maskedCopy(self.maskByteTensor, self.gradMaxVals)
end
for i=#input+1, #self.gradInput do
self.gradInput[i] = nil
end
return self.gradInput
end
|
local cjson = require "cjson"
--[[
local redis=require "redis.zs_redis"
local redisClient = redis:new();
if(redisClient) then
local res =redisClient:do_command("hgetall")
ngx.say(cjson.encode(res))
else
ngx.say('redis read error')
end
return
]]
-- mysql search test
--[[
if zhCn_bundles then
for k,v in pairs(zhCn_bundles) do
ngx.say(k..' '..v)
end
else
ngx.say('english bundle is nil')
end
local session = {
_VERSION = "2.15"
}
]]
local abc={
a=1,b=2,c=3
}
local mt = { __index = abc }
local source={};
function abc.new()
local source1={};
return setmetatable(source1, mt)
end
local cjson = require "cjson"
local test=abc.new();
ngx.say(cjson.encode(test))
--ngx.say(getmetatable(test)) -- nil
local t1=abc.new();
local t2=abc.new();
ngx.say("t1.a:"..t1.a)
ngx.say("t2:"..cjson.encode(t2))
t2.a=3;
ngx.say("t2: "..cjson.encode(t2))
ngx.say("t2.a:"..t2.a)
ngx.say("t1.a:"..t1.a)
|
--[[
core entity class
handles ordered creation and destruction of components from a given set of systems
]]
local entity = class({
name = "entity",
})
--unique name handler
local _component_id_gen = 0
local function generate_unique_name(fragment)
local name = fragment.._component_id_gen
_component_id_gen = _component_id_gen + 1
return name
end
--construct a new entity
function entity:new(systems)
self.systems = systems
--component and destructor storage
self.components = {}
self.origin_system = {}
self.destructors = {}
end
--by-name access
function entity:get_component(name)
return self.components[name]
end
--shorthand
function entity:c(name)
return self.components[name]
end
--add an existing component to this entity
function entity:add_existing_component(name, component, system, destructor)
if self.components[name] ~= nil then
error("component name clash for '"..name.."' on this entity")
end
self.components[name] = component
self.origin_system[name] = system
self.destructors[name] = destructor
return component
end
--default destructor for components
--just remove from the system they were added from
local function call_default_destructor(entity, component, system)
system:remove(component)
end
--add a component to this entity using its accessible systems
function entity:add_component(system, name, ...)
local sys = self.systems[system]
if sys == nil then
error("system "..system.." not registered for this entity")
end
if name == nil then
name = generate_unique_name("__unnamed_component_")
end
--add it and move on
local comp = sys:add(...)
return self:add_existing_component(
name,
comp,
sys,
call_default_destructor
)
end
--remove a component by name
function entity:remove_component(name)
--capture, then shred out before calling
local component = self.components[name]
local system = self.origin_system[name]
local destructor = self.destructors[name]
self.components[name] = nil
self.origin_system[name] = nil
self.destructors[name] = nil
--call dtor if there is one
if type(destructor) == "function" then
destructor(self, component, system)
end
end
--remove a component by value
--slow, because we have to walk through with pairs to find it
function entity:remove_component_by_value(comp)
for name, c in pairs(self.components) do
if c == comp then
self:remove_component(name)
return
end
end
end
--remove all this entity's components
function entity:remove_all_components()
for _, name in ipairs(table.keys(self.components)) do
self:remove_component(name)
end
end
--entity destruction
--(helper)
function entity:_check_double_destroyed()
if self._destroyed then
error("entity double-destroyed")
end
end
--set of entities to destroy upon flush_entities
local entities_to_destroy = set()
--deferred
function entity:destroy()
self:_check_double_destroyed()
entities_to_destroy:add(self)
end
--immediate
function entity:destroy_now()
self:_check_double_destroyed()
self._destroyed = true
self:remove_all_components()
end
--flush all deferred entities - should do this at least once per frame
function entity.flush_entities()
if entities_to_destroy:size() > 0 then
for _, e in entities_to_destroy:ipairs() do
e:destroy_now()
end
entities_to_destroy:clear()
end
end
return entity
|
replay_load_code = [[
function nilCheck(input, default)
if input == nil then
return default
end
return input
end
local mode_names = ...
local replays = {}
local replay_tree = {{name = "All"}}
local dict_ref = {}
for key, value in pairs(mode_names) do
dict_ref[value] = key + 1
replay_tree[key + 1] = {name = value}
end
print("Loading replay file list")
local replay_file_list = love.filesystem.getDirectoryItems("replays")
local binser = require "libs/binser"
require "funcs"
print("Loading replay contents")
for i=1, #replay_file_list do
local data = love.filesystem.read("replays/"..replay_file_list[i])
local new_replay = binser.deserialize(data)[1]
local mode_name = nilCheck(new_replay, {mode = "znil"}).mode
replays[#replays+1] = new_replay
if dict_ref[mode_name] ~= nil and mode_name ~= "znil" then
table.insert(replay_tree[dict_ref[mode_name] ], #replays)
end
table.insert(replay_tree[1], #replays)
end
print("Sorting replays...")
local function padnum(d) return ("%03d%s"):format(#d, d) end
table.sort(replay_tree, function(a,b)
return tostring(a.name):gsub("%d+",padnum) < tostring(b.name):gsub("%d+",padnum) end)
for key, submenu in pairs(replay_tree) do
table.sort(submenu, function(a, b)
return replays[a]["timestamp"] > replays[b]["timestamp"]
end)
end
print("Pushing replays...")
love.thread.getChannel( 'replays' ):push( replays )
love.thread.getChannel( 'replay_tree' ):push( replay_tree )
love.thread.getChannel( 'dict_ref' ):push( dict_ref )
love.thread.getChannel( 'loaded_replays' ):push( true )
print("Pushed replays.")
]] |
-- Arrays are call be ref, therefore assignment of array members work without write-back
-- I assume that _G members are different from global and just represent a runtime variable(maybe it is _G.global)
-- also _G.global somehow does not survive saving the map, it seems factorio doc is wrong
-- remember this when investigating desyncs...
-------------------------------------------------------------------------------
local ncoData = _G.ncoData or {}
ncoData.LongWarehouses = ncoData.LongWarehouses or {}
local myData = ncoData.LongWarehouses
myData.whSizes = myData.whSizes or {}
myData.RegisteredWarehouses = myData.RegisteredWarehouses or {}
-------------------------------------------------------------------------------
return myData
|
wait(0.016666666666667)
Effects = {}
local Player = game.Players.localPlayer
local Character = Player.Character
local Humanoid = Character.Humanoid
local mouse = Player:GetMouse()
local m = Instance.new("Model", Character)
m.Name = "WeaponModel"
local effect = Instance.new("Model", Character)
effect.Name = "Effects"
local LeftArm = Character["Left Arm"]
local RightArm = Character["Right Arm"]
local LeftLeg = Character["Left Leg"]
local RightLeg = Character["Right Leg"]
local Head = Character.Head
local Torso = Character.Torso
local cam = game.Workspace.CurrentCamera
local RootPart = Character.HumanoidRootPart
local RootJoint = RootPart.RootJoint
local equipped = false
local attack = false
local Anim = "Idle"
local idle = 0
local attacktype = 1
local Torsovelocity = RootPart.Velocity * Vector3.new(1, 0, 1).magnitude
local velocity = RootPart.Velocity.y
local sine = 0
local change = 1
local mana = 0
local it = Instance.new
vt = Vector3.new
local grabbed = false
local cf = CFrame.new
local mr = math.rad
local angles = CFrame.Angles
local ud = UDim2.new
local c3 = Color3.new
local NeckCF = cf(0, 1, 0, -1, 0, 0, 0, 0, 1, 0, 1, 0)
local RootCF = CFrame.fromEulerAnglesXYZ(-1.57, 0, 3.14)
local RHCF = CFrame.fromEulerAnglesXYZ(0, 1.6, 0)
local LHCF = (CFrame.fromEulerAnglesXYZ(0, -1.6, 0))
RSH = nil
RW = Instance.new("Weld")
LW = Instance.new("Weld")
RH = Torso["Right Hip"]
LH = Torso["Left Hip"]
RSH = Torso["Right Shoulder"]
LSH = Torso["Left Shoulder"]
RSH.Parent = nil
LSH.Parent = nil
RW.Name = "RW"
RW.Part0 = Torso
RW.C0 = cf(1.5, 0.5, 0)
RW.C1 = cf(0, 0.5, 0)
RW.Part1 = RightArm
RW.Parent = Torso
LW.Name = "LW"
LW.Part0 = Torso
LW.C0 = cf(-1.5, 0.5, 0)
LW.C1 = cf(0, 0.5, 0)
LW.Part1 = LeftArm
LW.Parent = Torso
clerp = function(a, b, t)
return a:lerp(b, t)
end
local RbxUtility = LoadLibrary("RbxUtility")
local Create = RbxUtility.Create
RemoveOutlines = function(part)
part.TopSurface = 10
end
CreatePart = function(Parent, Material, Reflectance, Transparency, BColor, Name, Size)
local Part = Create("Part")({Parent = Parent, Reflectance = Reflectance, Transparency = Transparency, CanCollide = false, Locked = true, BrickColor = BrickColor.new(tostring(BColor)), Name = Name, Size = Size, Material = Material})
RemoveOutlines(Part)
return Part
end
CreateMesh = function(Mesh, Part, MeshType, MeshId, OffSet, Scale)
local Msh = Create(Mesh)({Parent = Part, Offset = OffSet, Scale = Scale})
if Mesh == "SpecialMesh" then
Msh.MeshType = MeshType
Msh.MeshId = MeshId
end
return Msh
end
local co1 = 10
local co2 = 30
local co3 = 30
local co4 = 60
local cooco = 3
local cooldown1 = 0
local cooldown2 = 0
local cooldown3 = 0
local cooldown4 = 0
local coolcool = 0
local maxEnergy = 100
local Energy = 0
local skill1stam = 10
local skill2stam = 50
local skill3stam = 60
local skill4stam = 100
local skill5stam = 100
local recovermana = 5
local skillcolorscheme = BrickColor.new("Really black").Color
local scrn = Instance.new("ScreenGui", Player.PlayerGui)
makeframe = function(par, trans, pos, size, color)
local frame = Instance.new("Frame", par)
frame.BackgroundTransparency = trans
frame.BorderSizePixel = 0
frame.Position = pos
frame.Size = size
frame.BackgroundColor3 = color
return frame
end
makelabel = function(par, text)
local label = Instance.new("TextLabel", par)
label.BackgroundTransparency = 1
label.Size = UDim2.new(1, 0, 1, 0)
label.Position = UDim2.new(0, 0, 0, 0)
label.TextColor3 = Color3.new(255, 255, 255)
label.TextStrokeTransparency = 0
label.FontSize = Enum.FontSize.Size32
label.Font = Enum.Font.SourceSansBold
label.BorderSizePixel = 0
label.TextScaled = true
label.Text = text
end
framesk1 = makeframe(scrn, 0.5, UDim2.new(0.8, 0, 0.93, 0), UDim2.new(0.16, 0, 0.06, 0), skillcolorscheme)
framesk2 = makeframe(scrn, 0.5, UDim2.new(0.8, 0, 0.86, 0), UDim2.new(0.16, 0, 0.06, 0), skillcolorscheme)
framesk3 = makeframe(scrn, 0.5, UDim2.new(0.8, 0, 0.79, 0), UDim2.new(0.16, 0, 0.06, 0), skillcolorscheme)
framesk4 = makeframe(scrn, 0.5, UDim2.new(0.8, 0, 0.72, 0), UDim2.new(0.16, 0, 0.06, 0), skillcolorscheme)
framesk5 = makeframe(scrn, 0.5, UDim2.new(0.8, 0, 0.6, 0), UDim2.new(0.16, 0, 0.06, 0), skillcolorscheme)
bar1 = makeframe(framesk1, 0, UDim2.new(0, 0, 0, 0), UDim2.new(1, 0, 1, 0), skillcolorscheme)
bar2 = makeframe(framesk2, 0, UDim2.new(0, 0, 0, 0), UDim2.new(1, 0, 1, 0), skillcolorscheme)
bar3 = makeframe(framesk3, 0, UDim2.new(0, 0, 0, 0), UDim2.new(1, 0, 1, 0), skillcolorscheme)
bar4 = makeframe(framesk4, 0, UDim2.new(0, 0, 0, 0), UDim2.new(1, 0, 1, 0), skillcolorscheme)
bar5 = makeframe(framesk5, 0, UDim2.new(0, 0, 0, 0), UDim2.new(1, 0, 1, 0), skillcolorscheme)
text1 = makelabel(framesk1, "[Z] Hello!")
text2 = makelabel(framesk2, "[X] Cake")
text3 = makelabel(framesk3, "[C] Confetti")
text4 = makelabel(framesk4, "[V] ZOOP")
text5 = Instance.new("TextLabel", framesk5)
text5.BackgroundTransparency = 1
text5.Size = UDim2.new(1, 0, 1, 0)
text5.Position = UDim2.new(0, 0, 0, 0)
text5.TextColor3 = Color3.new(255, 255, 255)
text5.TextStrokeTransparency = 0
text5.FontSize = Enum.FontSize.Size32
text5.Font = Enum.Font.SourceSansBold
text5.BorderSizePixel = 0
text5.TextScaled = true
text5.Text = "[F] Aim]"
ArtificialHB = Instance.new("BindableEvent", script)
ArtificialHB.Name = "Heartbeat"
script:WaitForChild("Heartbeat")
frame = 0.033333333333333
tf = 0
allowframeloss = false
tossremainder = false
lastframe = tick()
script.Heartbeat:Fire()
game:GetService("RunService").Heartbeat:connect(function(s, p)
tf = tf + s
if frame <= tf then
if allowframeloss then
script.Heartbeat:Fire()
lastframe = tick()
else
for i = 1, math.floor(tf / frame) do
script.Heartbeat:Fire()
end
lastframe = tick()
end
if tossremainder then
tf = 0
else
tf = tf - frame * math.floor(tf / frame)
end
end
end
)
swait = function(num)
if num == 0 or num == nil then
ArtificialHB.Event:wait()
else
for i = 0, num do
ArtificialHB.Event:wait()
end
end
end
CreateWeld = function(Parent, Part0, Part1, C0, C1)
local Weld = Create("Weld")({Parent = Parent, Part0 = Part0, Part1 = Part1, C0 = C0, C1 = C1})
return Weld
end
rayCast = function(Position, Direction, Range, Ignore)
return game:service("Workspace"):FindPartOnRay(Ray.new(Position, Direction.unit * (Range or 999.999)), Ignore)
end
CreateSound = function(id, par, vol, pit)
coroutine.resume(coroutine.create(function()
local sou = Instance.new("Sound", par or workspace)
sou.Volume = vol
sou.Pitch = pit or 1
sou.SoundId = id
swait()
sou:play()
game:GetService("Debris"):AddItem(sou, 6)
end
))
end
local getclosest = function(obj, distance)
local last, lastx = distance + 1, nil
for i,v in pairs(workspace:GetChildren()) do
if v:IsA("Model") and v ~= Character and v:findFirstChild("Humanoid") and v:findFirstChild("Torso") and v:findFirstChild("Humanoid").Health > 0 then
local t = v.Torso
local dist = t.Position - obj.Position.magnitude
if dist <= distance and dist < last then
last = dist
lastx = v
end
end
end
return lastx
end
makeconfetti = function(place)
local cp = Instance.new("Part")
cp.Name = "Effect"
cp.FormFactor = "Custom"
cp.Size = Vector3.new(0, 0, 0)
cp.CanCollide = false
cp.Transparency = 1
cp.CFrame = place.CFrame
cp.Velocity = Vector3.new(math.random() - 0.5, math.random(), math.random() - 0.5).unit * 20
delay(0.25 + math.random() * 0.2, function()
if cp ~= nil then
cp.Velocity = cp.Velocity * 0.1
wait(0.5)
end
if cp ~= nil then
cp.Velocity = Vector3.new(0, -1, 0)
wait(1)
end
if cp ~= nil then
cp.Velocity = Vector3.new(0, -2, 0)
end
end
)
local cbbg = Instance.new("BillboardGui")
cbbg.Adornee = cp
cbbg.Size = UDim2.new(7, 0, 4, 0)
local cil = Instance.new("ImageLabel")
cil.BackgroundTransparency = 1
cil.BorderSizePixel = 0
cil.Size = UDim2.new(1, 0, 1, 0)
cil.Image = "http://www.roblox.com/asset/?id=104606998"
cil.Parent = cbbg
cbbg.Parent = cp
local bf = Instance.new("BodyForce")
bf.force = Vector3.new(0, cp:GetMass() * 196.2, 0)
bf.Parent = cp
game.Debris:AddItem(cp, 7 + math.random())
cp.Parent = game.Workspace
end
Damagefunc = function(Part, hit, minim, maxim, knockback, Type, Property, Delay, HitSound, HitPitch)
if hit.Parent == nil then
return
end
local h = hit.Parent:FindFirstChild("Humanoid")
for _,v in pairs(hit.Parent:children()) do
if v:IsA("Humanoid") then
h = v
end
end
if h ~= nil and hit.Parent.Name ~= Character.Name and hit.Parent:FindFirstChild("Torso") ~= nil then
if hit.Parent:findFirstChild("DebounceHit") ~= nil and hit.Parent.DebounceHit.Value == true then
return
end
local c = Create("ObjectValue")({Name = "creator", Value = game:service("Players").LocalPlayer, Parent = h})
game:GetService("Debris"):AddItem(c, 0.5)
if HitSound ~= nil and HitPitch ~= nil then
CreateSound(HitSound, hit, 1, HitPitch)
end
local Damage = math.random(minim, maxim)
local blocked = false
local block = hit.Parent:findFirstChild("Block")
if block ~= nil and block.className == "IntValue" and block.Value > 0 then
blocked = true
block.Value = block.Value - 1
print(block.Value)
end
if blocked == false then
h.Health = h.Health - Damage
ShowDamage(Part.CFrame * CFrame.new(0, 0, Part.Size.Z / 2).p + Vector3.new(0, 1.5, 0), -Damage, 1.5, Part.BrickColor.Color)
else
h.Health = h.Health - Damage / 2
ShowDamage(Part.CFrame * CFrame.new(0, 0, Part.Size.Z / 2).p + Vector3.new(0, 1.5, 0), -Damage, 1.5, Part.BrickColor.Color)
end
if Type == "Knockdown" then
local hum = hit.Parent.Humanoid
hum.PlatformStand = true
coroutine.resume(coroutine.create(function(HHumanoid)
swait(1)
HHumanoid.PlatformStand = false
end
), hum)
local angle = hit.Position - (Property.Position + Vector3.new(0, 0, 0)).unit
local bodvol = Create("BodyVelocity")({velocity = angle * knockback, P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
local rl = Create("BodyAngularVelocity")({P = 3000, maxTorque = Vector3.new(500000, 500000, 500000) * 50000000000000, angularvelocity = Vector3.new(math.random(-10, 10), math.random(-10, 10), math.random(-10, 10)), Parent = hit})
game:GetService("Debris"):AddItem(bodvol, 0.5)
game:GetService("Debris"):AddItem(rl, 0.5)
else
do
if Type == "Normal" then
local vp = Create("BodyVelocity")({P = 500, maxForce = Vector3.new(math.huge, 0, math.huge), velocity = Property.CFrame.lookVector * knockback + Property.Velocity / 1.05})
if knockback > 0 then
vp.Parent = hit.Parent.Torso
end
game:GetService("Debris"):AddItem(vp, 0.5)
else
do
if Type == "Up" then
local bodyVelocity = Create("BodyVelocity")({velocity = vt(0, 20, 0), P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
game:GetService("Debris"):AddItem(bodyVelocity, 0.5)
else
do
if Type == "DarkUp" then
coroutine.resume(coroutine.create(function()
for i = 0, 1, 0.1 do
swait()
BlockEffect(BrickColor.new("Black"), hit.Parent.Torso.CFrame, 5, 5, 5, 1, 1, 1, 0.08, 1)
end
end
))
local bodyVelocity = Create("BodyVelocity")({velocity = vt(0, 20, 0), P = 5000, maxForce = Vector3.new(8000, 8000, 8000), Parent = hit})
game:GetService("Debris"):AddItem(bodyVelocity, 1)
else
do
if Type == "Snare" then
local bp = Create("BodyPosition")({P = 2000, D = 100, maxForce = Vector3.new(math.huge, math.huge, math.huge), position = hit.Parent.Torso.Position, Parent = hit.Parent.Torso})
game:GetService("Debris"):AddItem(bp, 1)
else
do
if Type == "Freeze" then
local BodPos = Create("BodyPosition")({P = 50000, D = 1000, maxForce = Vector3.new(math.huge, math.huge, math.huge), position = hit.Parent.Torso.Position, Parent = hit.Parent.Torso})
local BodGy = Create("BodyGyro")({maxTorque = Vector3.new(400000, 400000, 400000) * math.huge, P = 20000, Parent = hit.Parent.Torso, cframe = hit.Parent.Torso.CFrame})
hit.Parent.Torso.Anchored = true
coroutine.resume(coroutine.create(function(Part)
swait(1.5)
Part.Anchored = false
end
), hit.Parent.Torso)
game:GetService("Debris"):AddItem(BodPos, 3)
game:GetService("Debris"):AddItem(BodGy, 3)
end
do
local debounce = Create("BoolValue")({Name = "DebounceHit", Parent = hit.Parent, Value = true})
game:GetService("Debris"):AddItem(debounce, Delay)
c = Instance.new("ObjectValue")
c.Name = "creator"
c.Value = Player
c.Parent = h
game:GetService("Debris"):AddItem(c, 0.5)
end
end
end
end
end
end
end
end
end
end
end
end
end
ShowDamage = function(Pos, Text, Time, Color)
local Rate = 0.033333333333333
if not Pos then
local Pos = Vector3.new(0, 0, 0)
end
local Text = Text or ""
local Time = Time or 2
if not Color then
local Color = Color3.new(1, 0, 1)
end
local EffectPart = CreatePart(workspace, "SmoothPlastic", 0, 1, BrickColor.new(Color), "Effect", vt(0, 0, 0))
EffectPart.Anchored = true
local BillboardGui = Create("BillboardGui")({Size = UDim2.new(3, 0, 3, 0), Adornee = EffectPart, Parent = EffectPart})
local TextLabel = Create("TextLabel")({BackgroundTransparency = 1, Size = UDim2.new(1, 0, 1, 0), Text = Text, TextColor3 = Color, TextScaled = true, Font = Enum.Font.ArialBold, Parent = BillboardGui})
game.Debris:AddItem(EffectPart, Time + 0.1)
EffectPart.Parent = game:GetService("Workspace")
delay(0, function()
local Frames = Time / Rate
for Frame = 1, Frames do
wait(Rate)
local Percent = Frame / Frames
EffectPart.CFrame = CFrame.new(Pos) + Vector3.new(0, Percent, 0)
TextLabel.TextTransparency = Percent
end
if EffectPart and EffectPart.Parent then
EffectPart:Destroy()
end
end
)
end
MagniDamage = function(Part, magni, mindam, maxdam, knock, Type)
for _,c in pairs(workspace:children()) do
local hum = c:findFirstChild("Humanoid")
if hum ~= nil then
local head = c:findFirstChild("Torso")
if head ~= nil then
local targ = head.Position - Part.Position
local mag = targ.magnitude
if mag <= magni and c.Name ~= Player.Name then
Damagefunc(head, head, mindam, maxdam, knock, Type, RootPart, 0.1, "http://www.roblox.com/asset/?id=231917784", 1)
end
end
end
end
end
Handle = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Handle", Vector3.new(0.700000048, 0.369999945, 0.280000091))
HandleWeld = CreateWeld(m, Character["Right Arm"], Handle, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.318675995, -0.93935442, -0.100952148, -0.000336287718, -2.69723296e-005, -1.0000006, 0.000396225107, -1.0000006, 2.75748262e-005, -1.00000048, -0.00039631853, 0.000336177269))
CreateMesh("SpecialMesh", Handle, Enum.MeshType.Cylinder, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.5))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(0.700000048, 0.369999945, 0.280000091))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0, 0, 0, 1.00000131, -7.35742219e-007, 1.21101039e-007, -7.35742219e-007, 1.00000131, 1.02765625e-007, 1.21101039e-007, 1.02765625e-007, 1.00000119))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.5))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(1, 1.19999993, 1.20000005))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.885063887, -0.850027084, 0.139083862, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(0.200000018, 0.919999897, 0.929999948))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.65007019, -1.12043953, 1.41934061, 0.000366366556, -0.000121983321, 1.00000107, 1.00000107, -0.000305830443, -0.000366173568, 0.000304477202, 1.00000131, 0.000122066587))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(0.5, 1.10000002, 1.10000002))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Royal purple", "Part", Vector3.new(0.600000024, 0.299999893, 0.300000012))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.685011983, -1.30000305, -0.310913086, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Barrel = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Barrel", Vector3.new(0.299999952, 0.299999952, 0.49999997))
BarrelWeld = CreateWeld(m, Handle, Barrel, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.149612427, -0.839944839, -1.62507761, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Barrel, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(0.5, 0.5, 2))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.15965271, -0.839952469, -1.31507254, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1.10000002, 1.10000002, 2))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.47496772, -1.08996964, -0.560287476, -2.99031944e-005, -1.00000119, -0.000364157662, 1.00000119, -3.11631775e-005, -0.00037874296, 0.00037896217, -0.000363974337, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.159637451, -0.839942932, -1.66506422, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1.29999995, 1.29999995, 2))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Royal purple", "Part", Vector3.new(0.300000012, 0.299999893, 0.300000012))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.38499403, -1.29999924, -0.31072998, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.315048695, -1.19999695, 0.139648438, -2.99031944e-005, -1.00000119, -0.000364157662, 1.00000119, -3.11631775e-005, -0.00037874296, 0.00037896217, -0.000363974337, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1, 1, 2))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Royal purple", "Part", Vector3.new(0.400000006, 0.299999893, 0.300000012))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(1.09998894, 0.985217929, -0.310440063, -1.00000107, 3.09870593e-005, 0.000671288697, -3.00194297e-005, -1.00000107, -0.000640959595, 0.000671499758, -0.000640785322, 1.00000072))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.315003157, -1.15942001, 0.391784668, -1.05658009e-005, -1.00000119, -0.000331618445, 0.866236687, -0.000175954381, 0.49963668, -0.499636561, -0.000281113171, 0.866236448))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1, 1, 2))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Royal purple", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.315113783, -1.3240509, -0.106765747, -3.80144447e-005, -1.00000119, -0.000286904746, 0.86581111, 0.000109338136, -0.500373363, 0.500373662, -0.000267956813, 0.86581111))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1, 1, 2))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(1.23000002, 1.24000001, 1.20000005))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.144668579, -0.849945068, -0.335066319, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Royal purple", "Part", Vector3.new(0.300000012, 0.299999893, 0.300000012))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.985000253, -1.29999733, -0.310958862, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Royal purple", "Part", Vector3.new(2.21000004, 0.299999893, 0.300000012))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.12000227, -1.06999397, -0.380722046, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 0.5, 1))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(1, 0.789999902, 0.709999919))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.140090942, -1.10543823, 1.39955378, 0.000366366556, -0.000121983321, 1.00000107, 1.00000107, -0.000305830443, -0.000366173568, 0.000304477202, 1.00000131, 0.000122066587))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1.04999995, 6, 2.29999995))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.220000029, 0.919999897, 0.929999948))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.459915161, -1.09041786, 1.47965384, 0.000366366556, -0.000121983321, 1.00000107, 1.00000107, -0.000305830443, -0.000366173568, 0.000304477202, 1.00000131, 0.000122066587))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(1.48000002, 0.819999933, 1.20000005))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.424940348, -0.660030365, 0.139541626, -2.97360093e-005, -1.00000131, -1.88207196e-005, 1.00000095, -3.11220283e-005, -0.000637698569, 0.000637928257, -1.86453399e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(1, 0.789999902, 0.709999919))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.140090942, -1.10543823, 1.39955378, 0.000366366556, -0.000121983321, 1.00000107, 1.00000107, -0.000305830443, -0.000366173568, 0.000304477202, 1.00000131, 0.000122066587))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 5, 2.5))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.41492677, -1.12001801, 0.6197052, -2.99031944e-005, -1.00000119, -0.000364157662, 1.00000119, -3.11631775e-005, -0.00037874296, 0.00037896217, -0.000363974337, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1.79999995, 1.79999995, 2))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-1.4149673, -1.11997604, -0.360290527, -2.99031944e-005, -1.00000119, -0.000364157662, 1.00000119, -3.11631775e-005, -0.00037874296, 0.00037896217, -0.000363974337, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1.79999995, 1.79999995, 2))
Part = CreatePart(m, Enum.Material.Neon, 0, 0, "Black", "Part", Vector3.new(0.299999952, 0.299999952, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.15965271, -0.839946747, -1.48507142, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.FileMesh, "http://www.roblox.com/asset/?id=3270017", Vector3.new(0, 0, 0), Vector3.new(1.20000005, 1.20000005, 2))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(0.200000018, 0.919999897, 0.929999948))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.509918213, -1.09041595, 1.4796629, 0.000366366556, -0.000121983321, 1.00000107, 1.00000107, -0.000305830443, -0.000366173568, 0.000304477202, 1.00000131, 0.000122066587))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(0.5, 1.10000002, 1.10000002))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Really black", "Part", Vector3.new(1.18999994, 1.11999989, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.154647827, -0.809949875, -1.31507277, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0.5, "Really black", "Part", Vector3.new(1.13, 1.11999989, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.1746521, -0.809955597, -1.38508785, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0.5, "Really black", "Part", Vector3.new(1.18999994, 1.11999989, 0.49999997))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.154647827, -0.809947968, -1.45508766, 0.000366321998, -0.000366120541, 1.00000095, 1.00000119, -6.16857869e-005, -0.000366114022, 6.04219967e-005, 1.00000119, 0.000366293127))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Sphere, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(1, 1.19999993, 1.20000005))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(0.885063887, -0.850027084, 0.139083862, -2.97294828e-005, -1.00000131, -1.88043923e-005, 1.00000095, -3.11155127e-005, -0.00063769205, 0.000637921738, -1.86290417e-005, 1.00000095))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(0.700000048, 0.369999945, 0.280000091))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.349996567, -0.606202126, 0, 0.866040528, 0.499982536, 0.000292716955, -0.499987632, 0.866041303, 0.000282988942, -0.000108518783, -0.000385537889, 1.00000477))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 0.5))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(0.220000058, 0.619999945, 0.710000098))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.290046692, -0.834992409, 0.184677124, 1.00000131, -7.35742219e-007, 1.21101039e-007, -7.35742219e-007, 1.00000131, 1.02765625e-007, 1.21101039e-007, 1.02765625e-007, 1.00000119))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
Part = CreatePart(m, Enum.Material.SmoothPlastic, 0, 0, "Black", "Part", Vector3.new(2.1500001, 0.819999933, 0.780000031))
PartWeld = CreateWeld(m, Handle, Part, CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1), CFrame.new(-0.409978628, -0.559999466, 0.124420166, -2.96669386e-005, -1.00000143, 6.75041229e-005, 1.00000095, -3.1113872e-005, -0.000724008365, 0.000724240555, 6.76767959e-005, 1.00000083))
CreateMesh("SpecialMesh", Part, Enum.MeshType.Cylinder, "", Vector3.new(0, 0, 0), Vector3.new(1, 1, 1))
BlockEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay, Type)
local prt = CreatePart(workspace, "Neon", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("BlockMesh", prt, "", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
if Type == 1 or Type == nil then
table.insert(Effects, {prt, "Block1", delay, x3, y3, z3, msh})
else
if Type == 2 then
table.insert(Effects, {prt, "Block2", delay, x3, y3, z3, msh})
end
end
end
SphereEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "Neon", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "Sphere", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
RingEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(effect, "Neon", 0, 0, brickcolor, "Effect", vt(0.5, 0.5, 0.5))
prt.Anchored = true
prt.CFrame = cframe
msh = CreateMesh("SpecialMesh", prt, "FileMesh", "http://www.roblox.com/asset/?id=3270017", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 2)
coroutine.resume(coroutine.create(function(Part, Mesh, num)
for i = 0, 1, delay do
swait()
Part.Transparency = i
Mesh.Scale = Mesh.Scale + vt(x3, y3, z3)
end
Part.Parent = nil
end
), prt, msh, (math.random(0, 1) + math.random()) / 5)
end
CylinderEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "SmoothPlastic", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("CylinderMesh", prt, "", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
WaveEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "SmoothPlastic", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://20329976", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
SpecialEffect = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(workspace, "SmoothPlastic", 0, 0, brickcolor, "Effect", Vector3.new())
prt.Anchored = true
prt.CFrame = cframe
local msh = CreateMesh("SpecialMesh", prt, "FileMesh", "rbxassetid://24388358", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Cylinder", delay, x3, y3, z3, msh})
end
BreakEffect = function(brickcolor, cframe, x1, y1, z1)
local prt = CreatePart(workspace, "Neon", 0, 0, brickcolor, "Effect", Vector3.new(0.5, 0.5, 0.5))
prt.Anchored = true
prt.CFrame = cframe * CFrame.fromEulerAnglesXYZ(math.random(-50, 50), math.random(-50, 50), math.random(-50, 50))
local msh = CreateMesh("SpecialMesh", prt, "Sphere", "", Vector3.new(0, 0, 0), Vector3.new(x1, y1, z1))
local num = math.random(10, 50) / 1000
game:GetService("Debris"):AddItem(prt, 10)
table.insert(Effects, {prt, "Shatter", num, prt.CFrame, math.random() - math.random(), 0, math.random(50, 100) / 100})
end
MagicCylinder2 = function(brickcolor, cframe, x1, y1, z1, x3, y3, z3, delay)
local prt = CreatePart(effect, "Neon", 0, 0, brickcolor, "Effect", vt(0.2, 0.2, 0.2))
prt.Anchored = true
prt.CFrame = cframe
msh = CreateMesh("CylinderMesh", prt, "", "", vt(0, 0, 0), vt(x1, y1, z1))
game:GetService("Debris"):AddItem(prt, 5)
Effects[#Effects + 1] = {prt, "Cylinder", delay, x3, y3, z3}
end
MagniCamShake = function(Part, magni, cam, intens)
for _,c in pairs(workspace:children()) do
if game.Players:GetPlayerFromCharacter(c) ~= nil and c:findFirstChild("Torso") ~= nil then
local targ = c.Torso.Position - Part.Position
local mag = targ.magnitude
if mag <= magni then
camshake = script[cam]:Clone()
camshake.Intensity.Value = mag / intens
camshake.Parent = game.Players.LocalPlayer.Backpack
camshake.Disabled = false
end
end
end
end
ShootCannon = function(asd, mindam, maxdam)
local r = {BrickColor.new("Bright violet"), BrickColor.new("Bright green"), BrickColor.new("Really black"), BrickColor.new("Bright blue"), BrickColor.new("Maroon")}
CreateSound("rbxassetid://263623156", asd, 0.5, 0.5)
CreateSound("rbxassetid://263610152", asd, 0.5, 0.5)
CreateSound("rbxassetid://263623139", asd, 0.5, 0.8)
local MainPos = asd.Position
local MainPos2 = mouse.Hit.p
local MouseLook = cf((MainPos + MainPos2) / 2, MainPos2)
num = 30
coroutine.resume(coroutine.create(function()
repeat
wait()
local hit, pos = rayCast(MainPos, MouseLook.lookVector, 10, Character)
local mag = (MainPos - pos).magnitude
MagicCylinder2(r[math.random(1, 3)], CFrame.new((MainPos + pos) / 2, pos) * angles(1.57, 0, 0), 3, mag * 5, 3, 0.5, 0, 0.5, 0.03)
MainPos = MainPos + MouseLook.lookVector * 10
num = num - 1
if hit ~= nil then
num = 0
local ref = CreatePart(effect, "SmoothPlastic", 0, 1, BrickColor.new("Magenta"), "Reference", vt())
ref.Anchored = true
ref.CFrame = cf(pos)
game.Debris:AddItem(ref, 3)
MagniDamage(ref, mag, mindam, maxdam, 1, "Normal")
CreateSound("rbxassetid://263610039", ref, 1, 1)
CreateSound("rbxassetid://263610111", ref, 1, 1)
BlockEffect(r[math.random(1, 2)], cf(pos), 5, 5, 5, 5, 5, 5, 0.05)
SphereEffect(r[math.random(1, 2)], cf(pos), 5, 5, 5, 10, 10, 10, 0.05)
BreakEffect(r[math.random(1, 2)], cf(pos), 1, 10, 1)
BreakEffect(r[math.random(1, 2)], cf(pos), 1, 10, 1)
BreakEffect(r[math.random(1, 2)], cf(pos), 1, 10, 1)
BreakEffect(r[math.random(1, 2)], cf(pos), 1, 10, 1)
RingEffect(r[math.random(1, 2)], cf(pos) * angles(math.random(-50, 50), math.random(-50, 50), math.random(-50, 50)), 5, 5, 5, 5, 5, 0, 0.05)
game:GetService("Debris"):AddItem(ref, 1)
MagniDamage(ref, 10, mindam, maxdam, 10, "Normal")
end
until num <= 0
end
))
end
Confetti = function()
attack = true
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos(sine / 9)) * angles(math.rad(0), math.rad(0), math.rad(-60)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(60)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(180), math.rad(0), math.rad(0)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(0), math.rad(0), math.rad(-40)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos(sine / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos(sine / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
makeconfetti(Barrel)
for i = 1, 30 do
local confetti = CreatePart(workspace, "SmoothPlastic", 0, 0, BrickColor.Random(), "Confetti", vt())
local cmsh = CreateMesh("BlockMesh", confetti, "", "", vt(0, 0, 0), vt(3, 1, 3))
confetti.CFrame = Barrel.CFrame * cf(math.random(-300, 300) / 100, math.random(-300, 300) / 100, math.random(-300, 300) / 100)
confetti.Velocity = RootPart.CFrame.lookVector * math.random(40, 60) + vt(math.random(-100, 100) / 100, 1, math.random(-100, 100) / 100) * math.random(60, 80)
game:GetService("Debris"):AddItem(confetti, 5)
end
CreateSound("http://www.roblox.com/asset/?id=104605494", RootPart, 1, 1)
CreateSound("rbxassetid://263610152", RootPart, 0.5, 0.5)
SphereEffect(BrickColor.new("White"), Barrel.CFrame, 5, 5, 5, 10, 10, 10, 0.05)
MagniDamage(RootPart, 15, -30, -10, "Normal")
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos(sine / 9)) * angles(math.rad(0), math.rad(0), math.rad(-60)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(10), math.rad(0), math.rad(60)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(200), math.rad(0), math.rad(0)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(0), math.rad(0), math.rad(60)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos(sine / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos(sine / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
attack = false
end
Party = function()
attack = true
Humanoid.JumpPower = 250
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos(sine / 9)) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(20), math.rad(0), math.rad(0)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(0), math.rad(0), math.rad(-40)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(0), math.rad(0), math.rad(-40)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos(sine / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos(sine / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
makeconfetti(Barrel)
for i = 1, 30 do
local confetti = CreatePart(workspace, "SmoothPlastic", 0, 0, BrickColor.Random(), "Confetti", vt())
local cmsh = CreateMesh("BlockMesh", confetti, "", "", vt(0, 0, 0), vt(3, 1, 3))
confetti.CFrame = Barrel.CFrame * cf(math.random(-300, 300) / 100, math.random(-300, 300) / 100, math.random(-300, 300) / 100)
confetti.Velocity = RootPart.CFrame.lookVector * math.random(40, 60) + vt(math.random(-100, 100) / 100, 1, math.random(-100, 100) / 100) * math.random(60, 80)
game:GetService("Debris"):AddItem(confetti, 5)
end
Humanoid.Jump = true
CreateSound("http://www.roblox.com/asset/?id=104605494", RootPart, 1, 1)
CreateSound("rbxassetid://263610152", RootPart, 0.5, 0.5)
SphereEffect(BrickColor.Random(), Barrel.CFrame, 5, 5, 5, 10, 10, 10, 0.05)
RingEffect(BrickColor.Random(), RootPart.CFrame * angles(1.47, 0, 0), 5, 5, 5, 1, 1, 3, 0.01)
RingEffect(BrickColor.Random(), RootPart.CFrame * angles(1.47, 0, 0), 8, 8, 8, 2, 2, 3, 0.01)
RingEffect(BrickColor.Random(), RootPart.CFrame * angles(1.47, 0, 0), 9, 9, 9, 3, 3, 3, 0.01)
MagniDamage(RootPart, 30, 30, 50, "Knockdown")
wait(2)
Humanoid.JumpPower = 50
attack = false
end
local aiming = false
Aim = function()
attack = true
aiming = true
Humanoid.WalkSpeed = 0
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos(sine / 9)) * angles(math.rad(0), math.rad(0), math.rad(-60)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(60)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(90), math.rad(0), math.rad(-60)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(90), math.rad(0), math.rad(60)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos(sine / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos(sine / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
end
local blast = false
Shot = function()
Humanoid.WalkSpeed = 16
if blast == false then
blast = true
ShootCannon(Barrel, 20, 30)
end
SphereEffect(BrickColor.new("White"), Barrel.CFrame, 5, 5, 5, 1, 1, 1, 0.05)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos(sine / 9)) * angles(math.rad(0), math.rad(0), math.rad(-60)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(10), math.rad(0), math.rad(60)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(120), math.rad(0), math.rad(-60)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos(sine / 9), -0.5) * angles(math.rad(120), math.rad(0), math.rad(60)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos(sine / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos(sine / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
blast = false
attack = false
aiming = false
end
taunt = function()
attack = true
for i = 0, 1, 0.2 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.8, 0) * angles(math.rad(0), math.rad(0), math.rad(-180)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(-10), math.rad(0), math.rad(0)), 0.3)
end
for i = 0, 1, 0.2 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.8, 0.8, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-130)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(-10), math.rad(0), math.rad(0)), 0.3)
end
for i = 0, 1, 0.2 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.8, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-180)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(-10), math.rad(0), math.rad(0)), 0.3)
end
for i = 0, 1, 0.2 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.8, 0.8, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-130)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(-10), math.rad(0), math.rad(0)), 0.3)
end
for i = 0, 1, 0.2 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.8, 0.2) * angles(math.rad(0), math.rad(0), math.rad(-180)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(-10), math.rad(0), math.rad(0)), 0.3)
end
attack = false
end
EatMuffin = function()
attack = true
CreateSound("http://www.roblox.com/asset/?id=130776108", RootPart, 1, 1)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(30), math.rad(0), math.rad(80)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.8, 0.8, 0.2) * angles(math.rad(-30), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
print("Muffins")
local Muffin = Instance.new("Part")
Muffin.formFactor = 1
Muffin.CanCollide = false
Muffin.Name = "Muffin"
Muffin.Locked = true
Muffin.Size = Vector3.new(1, 1, 1)
Muffin.Parent = effect
local Muffinmesh = Instance.new("SpecialMesh")
Muffinmesh.Parent = Muffin
Muffinmesh.MeshId = "http://www.roblox.com/asset/?id=16211718"
Muffinmesh.TextureId = "http://www.roblox.com/asset/?id=16211592"
Muffinmesh.Scale = Vector3.new(1, 1, 1)
local Muffinweld = Instance.new("Weld")
Muffinweld.Parent = Muffin
Muffinweld.Part0 = Muffin
Muffinweld.Part1 = LeftArm
Muffinweld.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90), 0, math.rad(-60)) * CFrame.new(0, 1, 0.5)
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(30), math.rad(0), math.rad(30)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, 0) * angles(math.rad(90), math.rad(0), math.rad(-50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
for i = 0, 1, 0.1 do
swait()
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0.2) * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(5), math.rad(0), math.rad(0)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5, 0) * angles(math.rad(30), math.rad(0), math.rad(30)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1.5, 0.5, -0.5) * angles(math.rad(90), math.rad(0), math.rad(120)), 0.1)
RH.C0 = clerp(RH.C0, cf(1, -1, 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1, 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
for i = 1, 5 do
wait(0.45)
Character.Humanoid.Health = Character.Humanoid.Health + 5
end
Muffin.Parent = nil
attack = false
end
ob1u = function()
end
ob1d = function()
if attack == true and aiming == true and cooco <= coolcool then
Shot()
coolcool = 0
aiming = false
attack = false
end
end
key = function(k)
k = k:lower()
if attack == false and k == "f" then
Aim()
else
if attack == false and co1 <= cooldown1 and k == "z" then
cooldown1 = 0
taunt()
else
if attack == false and co2 <= cooldown2 and k == "x" then
cooldown2 = 0
EatMuffin()
else
if attack == false and co3 <= cooldown3 and k == "c" then
cooldown3 = 0
Confetti()
else
if attack == false and co4 <= cooldown4 and k == "v" then
cooldown4 = 0
Party()
end
end
end
end
end
end
Bin = Instance.new("HopperBin", game.Players.LocalPlayer.Backpack)
ds = function(mouse)
end
s = function(mouse)
print("Selected")
mouse.Button1Down:connect(function()
ob1d(mouse)
end
)
mouse.Button1Up:connect(function()
ob1u(mouse)
end
)
mouse.KeyDown:connect(key)
end
Bin.Selected:connect(s)
Bin.Deselected:connect(ds)
updateskills = function()
if coolcool <= cooco then
coolcool = coolcool + 0.033333333333333
text5.Text = "Reloading"
else
text5.Text = "[F] Aim"
end
if cooldown1 <= co1 then
cooldown1 = cooldown1 + 0.033333333333333
end
if cooldown2 <= co2 then
cooldown2 = cooldown2 + 0.033333333333333
end
if cooldown3 <= co3 then
cooldown3 = cooldown3 + 0.033333333333333
end
if cooldown4 <= co4 then
cooldown4 = cooldown4 + 0.033333333333333
end
end
while 1 do
swait()
updateskills()
bar4:TweenSize(UDim2.new(1 * (cooldown4 / co4), 0, 1, 0), "Out", "Quad", 0.5)
bar3:TweenSize(UDim2.new(1 * (cooldown3 / co3), 0, 1, 0), "Out", "Quad", 0.5)
bar1:TweenSize(UDim2.new(1 * (cooldown1 / co1), 0, 1, 0), "Out", "Quad", 0.5)
bar2:TweenSize(UDim2.new(1 * (cooldown2 / co2), 0, 1, 0), "Out", "Quad", 0.5)
bar5:TweenSize(UDim2.new(1 * (coolcool / cooco), 0, 1, 0), "Out", "Bounce", 0.5)
Torsovelocity = RootPart.Velocity * Vector3.new(1, 0, 1).magnitude
velocity = RootPart.Velocity.y
sine = sine + change
local hit, pos = rayCast(RootPart.Position, CFrame.new(RootPart.Position, RootPart.Position - Vector3.new(0, 1, 0)).lookVector, 4, Character)
if equipped == true or equipped == false then
if 1 < RootPart.Velocity.y and hit == nil then
Anim = "Jump"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(30), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos((sine) / 9), 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1, 0.5 - 0.1 * math.cos((sine) / 9), -0.5) * angles(math.rad(50), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos((sine) / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(30)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos((sine) / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
else
if RootPart.Velocity.y < -1 and hit == nil then
Anim = "Fall"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(-30), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos((sine) / 9), 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1, 0.5 - 0.1 * math.cos((sine) / 9), -0.5) * angles(math.rad(50), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos((sine) / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos((sine) / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
else
if Torsovelocity.x < 1 or Torsovelocity.z < 1 and hit ~= nil then
Anim = "Idle"
if attack == false then
change = 1
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos((sine) / 9), 0) * angles(math.rad(50), math.rad(0), math.rad(-50)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-1, 0.5 - 0.1 * math.cos((sine) / 9), -0.5) * angles(math.rad(50), math.rad(0), math.rad(50)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos((sine) / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos((sine) / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
else
if 2 < Torsovelocity.x or Torsovelocity.z > 2 and hit ~= nil then
Anim = "Walk"
if attack == false then
RootJoint.C0 = clerp(RootJoint.C0, RootCF * cf(0, 0, 0 - 0.1 * math.cos((sine) / 9)) * angles(math.rad(0), math.rad(0), math.rad(-50)), 0.3)
Torso.Neck.C0 = clerp(Torso.Neck.C0, NeckCF * angles(math.rad(0), math.rad(0), math.rad(50)), 0.3)
RW.C0 = clerp(RW.C0, CFrame.new(1.5, 0.5 - 0.1 * math.cos((sine) / 9), 0) * angles(math.rad(40), math.rad(0), math.rad(-40)), 0.3)
LW.C0 = clerp(LW.C0, CFrame.new(-0.8, 0.5 - 0.1 * math.cos((sine) / 9), -0.5) * angles(math.rad(40), math.rad(0), math.rad(40)), 0.3)
RH.C0 = clerp(RH.C0, cf(1, -1 + 0.1 * math.cos((sine) / 9), 0) * RHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
LH.C0 = clerp(LH.C0, cf(-1, -1 + 0.1 * math.cos((sine) / 9), 0) * LHCF * angles(math.rad(0), math.rad(0), math.rad(0)), 0.3)
end
end
end
end
end
end
if 0 < #Effects then
for e = 1, #Effects do
if Effects[e] ~= nil then
local Thing = Effects[e]
if Thing ~= nil then
local Part = Thing[1]
local Mode = Thing[2]
local Delay = Thing[3]
local IncX = Thing[4]
local IncY = Thing[5]
local IncZ = Thing[6]
if Thing[1].Transparency <= 1 then
if Thing[2] == "Block1" then
Thing[1].CFrame = Thing[1].CFrame * CFrame.fromEulerAnglesXYZ(math.random(-50, 50), math.random(-50, 50), math.random(-50, 50))
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Block2" then
Thing[1].CFrame = Thing[1].CFrame
Mesh = Thing[7]
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Cylinder" then
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Blood" then
Mesh = Thing[7]
Thing[1].CFrame = Thing[1].CFrame * Vector3.new(0, 0.5, 0)
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[4], Thing[5], Thing[6])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Elec" then
Mesh = Thing[1].Mesh
Mesh.Scale = Mesh.Scale + Vector3.new(Thing[7], Thing[8], Thing[9])
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Disappear" then
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
else
if Thing[2] == "Shatter" then
Thing[1].Transparency = Thing[1].Transparency + Thing[3]
Thing[4] = Thing[4] * CFrame.new(0, Thing[7], 0)
Thing[1].CFrame = Thing[4] * CFrame.fromEulerAnglesXYZ(Thing[6], 0, 0)
Thing[6] = Thing[6] + Thing[5]
end
end
end
end
end
end
end
else
Part.Parent = nil
table.remove(Effects, e)
end
end
end
end
end
end
|
--- Originally a #pico8 #tweetcart by @picoter8 on Twitter
-- https://twitter.com/p01/status/1186049861713567744
::_::
cls()
for i=90,4,-4 do
s=6*sin(t()+i/64)
c=6*cos(t()+i/96)
ovalfill(64-i-s,64-i-c,64+i+s,64+i+c,7+i/4)
end
flip()
goto _ |
-- This file supplies the various kinds of pneumatic tubes
local S = minetest.get_translator("pipeworks")
local tubenodes = {}
pipeworks.tubenodes = tubenodes
minetest.register_alias("pipeworks:tube", "pipeworks:tube_000000")
-- now, a function to define the tubes
local REGISTER_COMPATIBILITY = true
local vti = {4, 3, 2, 1, 6, 5}
local default_noctrs = { "pipeworks_tube_noctr.png" }
local default_plain = { "pipeworks_tube_plain.png" }
local default_ends = { "pipeworks_tube_end.png" }
local texture_mt = {
__index = function(table, key)
local size, idx = #table, tonumber(key)
if size > 0 then -- avoid endless loops with empty tables
while idx > size do idx = idx - size end
return table[idx]
end
end
}
local register_one_tube = function(name, tname, dropname, desc, plain, noctrs, ends, short, inv, special, connects, style)
noctrs = noctrs or default_noctrs
setmetatable(noctrs, texture_mt)
plain = plain or default_plain
setmetatable(plain, texture_mt)
ends = ends or default_ends
setmetatable(ends, texture_mt)
short = short or "pipeworks_tube_short.png"
inv = inv or "pipeworks_tube_inv.png"
local outboxes = {}
local outsel = {}
local outimgs = {}
for i = 1, 6 do
outimgs[vti[i]] = plain[i]
end
for _, v in ipairs(connects) do
pipeworks.table_extend(outboxes, pipeworks.tube_boxes[v])
table.insert(outsel, pipeworks.tube_selectboxes[v])
outimgs[vti[v]] = noctrs[v]
end
if #connects == 1 then
local v = connects[1]
v = v-1 + 2*(v%2) -- Opposite side
outimgs[vti[v]] = ends[v]
end
local tgroups = {snappy = 3, tube = 1, tubedevice = 1, not_in_creative_inventory = 1}
local tubedesc = string.format("%s %s", desc, dump(connects))
local iimg = type(plain[1]) == "table" and plain[1].name or plain[1]
local wscale = {x = 1, y = 1, z = 1}
if #connects == 0 then
tgroups = {snappy = 3, tube = 1, tubedevice = 1}
tubedesc = desc
iimg=inv
outimgs = {
short, short,
ends[3],ends[4],
short, short
}
outboxes = { -24/64, -9/64, -9/64, 24/64, 9/64, 9/64 }
outsel = { -24/64, -10/64, -10/64, 24/64, 10/64, 10/64 }
wscale = {x = 1, y = 1, z = 0.01}
end
local rname = string.format("%s_%s", name, tname)
table.insert(tubenodes, rname)
local nodedef = {
description = tubedesc,
drawtype = "nodebox",
tiles = outimgs,
sunlight_propagates = true,
inventory_image = iimg,
wield_image = iimg,
wield_scale = wscale,
paramtype = "light",
selection_box = {
type = "fixed",
fixed = outsel
},
node_box = {
type = "fixed",
fixed = outboxes
},
groups = tgroups,
sounds = default.node_sound_wood_defaults(),
walkable = true,
stack_max = 99,
basename = name,
style = style,
drop = string.format("%s_%s", name, dropname),
tubelike = 1,
tube = {
connect_sides = {front = 1, back = 1, left = 1, right = 1, top = 1, bottom = 1},
priority = 50
},
after_place_node = pipeworks.after_place,
after_dig_node = pipeworks.after_dig,
on_rotate = false,
on_blast = function(pos, intensity)
if not intensity or intensity > 1 + 3^0.5 then
minetest.remove_node(pos)
return {string.format("%s_%s", name, dropname)}
end
minetest.swap_node(pos, {name = "pipeworks:broken_tube_1"})
pipeworks.scan_for_tube_objects(pos)
end,
check_for_pole = pipeworks.check_for_vert_tube,
check_for_horiz_pole = pipeworks.check_for_horiz_tube,
tubenumber = tonumber(tname)
}
if style == "6d" then
nodedef.paramtype2 = "facedir"
end
if special == nil then special = {} end
for key, value in pairs(special) do
--if key == "after_dig_node" or key == "after_place_node" then
-- nodedef[key.."_"] = value
if key == "groups" then
for group, val in pairs(value) do
nodedef.groups[group] = val
end
elseif key == "tube" then
for key, val in pairs(value) do
nodedef.tube[key] = val
end
else
nodedef[key] = pipeworks.table_recursive_replace(value, "#id", tname)
end
end
minetest.register_node(rname, nodedef)
end
local register_all_tubes = function(name, desc, plain, noctrs, ends, short, inv, special, old_registration)
if old_registration then
for xm = 0, 1 do
for xp = 0, 1 do
for ym = 0, 1 do
for yp = 0, 1 do
for zm = 0, 1 do
for zp = 0, 1 do
local connects = {}
if xm == 1 then
connects[#connects+1] = 1
end
if xp == 1 then
connects[#connects+1] = 2
end
if ym == 1 then
connects[#connects+1] = 3
end
if yp == 1 then
connects[#connects+1] = 4
end
if zm == 1 then
connects[#connects+1] = 5
end
if zp == 1 then
connects[#connects+1] = 6
end
local tname = xm..xp..ym..yp..zm..zp
register_one_tube(name, tname, "000000", desc, plain, noctrs, ends, short, inv, special, connects, "old")
end
end
end
end
end
end
else
-- 6d tubes: uses only 10 nodes instead of 64, but the textures must be rotated
local cconnects = {{}, {1}, {1, 2}, {1, 3}, {1, 3, 5}, {1, 2, 3}, {1, 2, 3, 5}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5, 6}}
for index, connects in ipairs(cconnects) do
register_one_tube(name, tostring(index), "1", desc, plain, noctrs, ends, short, inv, special, connects, "6d")
end
if REGISTER_COMPATIBILITY then
local cname = name.."_compatibility"
minetest.register_node(cname, {
drawtype = "airlike",
style = "6d",
basename = name,
inventory_image = inv,
wield_image = inv,
paramtype = "light",
sunlight_propagates = true,
description = S("Pneumatic tube segment (legacy)"),
after_place_node = pipeworks.after_place,
groups = {not_in_creative_inventory = 1, tube_to_update = 1, tube = 1},
tube = {connect_sides = {front = 1, back = 1, left = 1, right = 1, top = 1, bottom = 1}},
drop = name.."_1",
})
table.insert(tubenodes, cname)
for xm = 0, 1 do
for xp = 0, 1 do
for ym = 0, 1 do
for yp = 0, 1 do
for zm = 0, 1 do
for zp = 0, 1 do
local tname = xm..xp..ym..yp..zm..zp
minetest.register_alias(name.."_"..tname, cname)
end
end
end
end
end
end
end
end
end
pipeworks.register_tube = function(name, def, ...)
if type(def) == "table" then
register_all_tubes(name, def.description,
def.plain, def.noctr, def.ends, def.short,
def.inventory_image, def.node_def, def.no_facedir)
else
-- we assert to be the old function with the second parameter being the description
-- function(name, desc, plain, noctrs, ends, short, inv, special, old_registration)
assert(type(def) == "string", "invalid arguments to pipeworks.register_tube")
register_all_tubes(name, def, ...)
end
end
if REGISTER_COMPATIBILITY then
minetest.register_abm({
nodenames = {"group:tube_to_update"},
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local minp = vector.subtract(pos, 1)
local maxp = vector.add(pos, 1)
if table.getn(minetest.find_nodes_in_area(minp, maxp, "ignore")) == 0 then
pipeworks.scan_for_tube_objects(pos)
end
end
})
end
|
--
-- Copyright (c) 2020 Tim Winchester
--
-- 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 utf8slim = {}
require("lists")
local AUTOTRANSLATE_INDICATOR = windower.from_shift_jis(string.char(0xFD))
-- returns the length in bytes needed to hold the character at the given string index
utf8slim.get_char_bytelength = (function(str, index)
local bytelength = nil
local byteval = string.byte(str, index or 1)
if (byteval == nil) then
return nil
elseif (byteval == AUTOTRANSLATE_INDICATOR) then
bytelength = 6
elseif (byteval < 0x80) then
bytelength = 1
elseif (byteval < 0xE0) then
bytelength = 2
elseif (byteval < 0xF0) then
bytelength = 3
elseif (byteval < 0xF8) then
bytelength = 4
elseif (byteval < 0xFC) then
bytelength = 5
elseif (byteval < 0xFF) then
bytelength = 6
end
return bytelength
end)
-- if given "abc", it will return {"a", "b", "c"}, but works on kana/kanji too
utf8slim.explode = (function(str)
local output = L{}
local start_index = 1
local end_index = 1
-- return an empty list if we received an empty string
if (utf8slim.get_char_bytelength(str, start_index) ~= nil) then
repeat
local bytelength = utf8slim.get_char_bytelength(str, start_index)
end_index = start_index + bytelength - 1
local char = string.sub(str, start_index, end_index)
list.append(output, char)
start_index = end_index + 1
until (end_index == #str)
end
return output
end)
return utf8slim |
local IO = require "kong.tools.io"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local spec_helper = require "spec.spec_helpers"
local http_client = require "kong.tools.http_client"
local STUB_GET_URL = spec_helper.STUB_GET_URL
describe("Syslog #ci", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{request_host = "logging.com", upstream_url = "http://mockbin.com"},
{request_host = "logging2.com", upstream_url = "http://mockbin.com"},
{request_host = "logging3.com", upstream_url = "http://mockbin.com"}
},
plugin = {
{name = "syslog", config = {log_level = "info", successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"}, __api = 1},
{name = "syslog", config = {log_level = "err", successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"}, __api = 2},
{name = "syslog", config = {log_level = "warning", successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning"}, __api = 3}
}
}
spec_helper.start_kong()
end)
teardown(function()
spec_helper.stop_kong()
end)
local function do_test(host, expecting_same)
local uuid = utils.random_string()
-- Making the request
local _, status = http_client.get(STUB_GET_URL, nil,
{host = host, sys_log_uuid = uuid}
)
assert.equal(200, status)
local platform, code = IO.os_execute("/bin/uname")
if code ~= 0 then
platform, code = IO.os_execute("/usr/bin/uname")
end
if code == 0 and platform == "Darwin" then
local output, code = IO.os_execute("syslog -k Sender kong | tail -1")
assert.equal(0, code)
local message = {}
for w in string.gmatch(output,"{.*}") do
table.insert(message, w)
end
local log_message = cjson.decode(message[1])
if expecting_same then
assert.equal(uuid, log_message.request.headers.sys_log_uuid)
else
assert.not_equal(uuid, log_message.request.headers.sys_log_uuid)
end
else
if expecting_same then
local output, code = IO.os_execute("find /var/log -type f -mmin -5 2>/dev/null | xargs grep -l "..uuid)
assert.equal(0, code)
assert.truthy(#output > 0)
end
end
end
it("should log to syslog if log_level is lower", function()
do_test("logging.com", true)
end)
it("should not log to syslog if the log_level is higher", function()
do_test("logging2.com", false)
end)
it("should log to syslog if log_level is the same", function()
do_test("logging3.com", true)
end)
end)
|
local SoraConfig = {}
local toml = require "toml"
local util = require "sora.util"
function SoraConfig.new(o)
o = o or {}
return o
end
function SoraConfig:parse(filePath)
filePath = filePath or ngx.var.baseDir .. "/etc/config.toml"
local fileBody = util.loadFile(filePath)
return toml.parse(fileBody)
end
return SoraConfig
|
local Assert = x2c.Assert
---------------------------------------
local function make_enum(data)
x2c.Exporter:InitTypeExporterInfo(data, "Enum")
if data.type and data.type:Type() == "Type" and not data.type.integral then
error("Enums accept only internal integral types as type")
end
if data.values then
local values = data.values
data.values = { }
for i,v in ipairs(values) do
local value
if type(v) == "string" then
value = {
name = v,
}
else
value = v
Assert.Table(v, "Enum")
Assert.String(v.name, "Enum", "Found nameless enum value!")
end
x2c.Exporter:InitTypeExporterMemberInfo(value, "Enum")
local decorated = string.format("%s%s%s",
data.config.enum_value_prefix or "",
value.name,
data.config.enum_value_postfix or ""
)
value.decorated = decorated
data.values[#data.values + 1] = value
end
if #data.values < 1 then
data.values = nil
end
end
data.object_type = "Enum"
local e = x2c.Exporter:MakeEnum(data)
x2c.RegisterType(e, x2c.CurrentNamespace)
return e
end
---------------------------------------
local EnumMeta = { }
function EnumMeta.new(data)
if not data.name then
error("Cannot define nameless enum")
return false
end
if x2c.CurrentNamespace:Exists(data.name) then
return x2c.CurrentNamespace:Get(data.name)
end
data.imported = false
data.namespace = x2c.CurrentNamespace
data.config = table.shallow_clone(data.namespace.config);
data.object_type = "Enum"
data.local_name = string.format("%s%s%s",
data.config.enum_prefix or "",
data.name,
data.config.enum_postfix or ""
)
if data.default then
data.default_value = string.format("%s%s%s",
data.config.enum_value_prefix or "",
data.default,
data.config.enum_value_postfix or ""
)
end
local e = make_enum(data)
info("Defined enum ", e:LocalName(), " in namespace ", e.namespace:DisplayName())
end
function EnumMeta.import(data)
if not data.name then
error("Cannot define nameless enum")
return false
end
if not data.location then
error("Location must be specified while importing enum")
return false
end
if x2c.CurrentNamespace:Exists(data.name) then
return x2c.CurrentNamespace:Get(data.name)
end
data.imported = true
data.namespace = x2c.CurrentNamespace
data.config = table.shallow_clone(data.namespace.config);
data.enum_name = string.format("%s%s%s",
data.config.enum_prefix or "",
data.name,
data.config.enum_postfix or ""
)
data.default_value = data.default
info("Imported enum ", data.enum_name, " in namespace ", data.namespace:DisplayName(), " from ", data.location)
local e = make_enum(data)
end
function EnumMeta.prefix(value)
if type(value) ~= "string" then
error("Invalid enum prefix value")
end
x2c.CurrentNamespace.config.enum_prefix = value
end
function EnumMeta.postfix(value)
if type(value) ~= "string" then
error("Invalid enum postfix value")
end
x2c.CurrentNamespace.config.enum_postfix = value
end
---------------------------------------
local EnumMetaValue = { }
function EnumMetaValue.prefix(value)
if type(value) ~= "string" then
error("Invalid enum value prefix value")
end
x2c.CurrentNamespace.config.enum_value_prefix = value
end
function EnumMetaValue.postfix(value)
if type(value) ~= "string" then
error("Invalid enum value postfix value")
end
x2c.CurrentNamespace.config.enum_value_postfix = value
end
---------------------------------------
x2c.MakeMetaSubObject(EnumMeta, EnumMetaValue, "value")
x2c.MakeMetaObject(EnumMeta, "Enum")
|
--* This Document is AutoGenerate by OrangeFilter, Don't Change it! *
---@meta
---
---[3.2]Serializable[parent:]
---
---@class Serializable
Serializable = {}
return Serializable
|
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local bot = Bot
local client = Client
local discordia = Discordia
Module.Name = "game"
Module.Global = true
function Module:GetConfigTable()
return {
{
Array = true,
Global = true,
Name = "GameList",
Description = "List of games",
Type = bot.ConfigType.String,
Default = {},
Sensitive = true
},
}
end
function Module:OnLoaded()
self.UpdateTimer = Bot:CreateRepeatTimer(3 * 60, -1, function ()
self:UpdateGame()
end)
self:UpdateGame()
return true
end
function Module:OnUnload()
self.UpdateTimer:Stop()
end
function Module:UpdateGame()
local games = self.GlobalConfig.GameList
local newGame = games[math.random(1, #games)]
if (type(newGame) == "function") then
newGame = newGame()
end
client:setGame(newGame)
end |
return {
__tag__ = "test",
id = 102,
value="测试",
} |
local startTime = os.time()
return function ()
local uptime = os.time() - startTime
return ("%dd %dh %dm %ds"):format(
math.floor(uptime / (60 * 60 * 24)),
math.floor(uptime / (60 * 60)) % 24,
math.floor(uptime / 60) % 60,
math.floor(uptime) % 60
)
end |
local x
x = function()
return print(what)
end
local _
_ = function() end
_ = function()
return function()
return function() end
end
end
go(to(the(barn)))
open(function()
return the(function()
return door
end)
end)
open(function()
the(door)
local hello
hello = function()
return my(func)
end
end)
local h
h = function()
return hi
end
eat(function() end, world);
(function() end)()
x = function(...) end
hello()
hello.world()
_ = hello().something
_ = what()["ofefe"]
what()(the()(heck()))
_ = function(a, b, c, d, e) end
_ = function(a, a, a, a, a)
return print(a)
end
_ = function(x)
if x == nil then
x = 23023
end
end
_ = function(x)
if x == nil then
x = function(y)
if y == nil then
y = function() end
end
end
end
end
_ = function(x)
if x == nil then
if something then
x = yeah
else
x = no
end
end
end
local something
something = function(hello, world)
if hello == nil then
hello = 100
end
if world == nil then
world = function(x)
if x == nil then
x = [[yeah cool]]
end
return print("eat rice")
end
end
return print(hello)
end
_ = function(self, x, y) end
_ = function(self, x, y)
self.x, self.y = x, y
end
_ = function(self, x)
if x == nil then
x = 1
end
end
_ = function(self, x, y, z)
if x == nil then
x = 1
end
if z == nil then
z = "hello world"
end
self.x, self.z = x, z
end
x(function()
return
end)
y(function()
return 1
end)
z(function()
return 1, "hello", "world"
end)
k(function()
if yes then
return
else
return
end
end) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.