content
stringlengths 5
1.05M
|
---|
-- Copyright (c) 2018 Redfern, Trevor <[email protected]>
--
-- This software is released under the MIT License.
-- https://opensource.org/licenses/MIT
local tiny = require "ext.tiny-ecs"
local RenderSymbolSystem = tiny.processingSystem()
local settings = require "settings"
RenderSymbolSystem.tiles = settings.symbol_font
RenderSymbolSystem.filter = tiny.requireAll("position", "symbol", "color")
RenderSymbolSystem.is_draw_system = true
function RenderSymbolSystem:process(e, _)
local size = e.size or { width = 1, height = 1 }
for x=0,size.width - 1 do
for y=0,size.height - 1 do
self.tiles:draw(e.symbol, e.position.x + x, e.position.y + y, e.color)
end
end
end
return RenderSymbolSystem
|
--[[
LuCI - Lua Configuration Interface
Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman>
]]--
require "luci.util"
local http = require "luci.http"
local uci = luci.model.uci.cursor()
local docker = require "luci.model.docker"
local dk = docker.new()
local images, networks, containers
local res = dk.images:list()
if res.code <300 then images = res.body else return end
res = dk.networks:list()
if res.code <300 then networks = res.body else return end
res = dk.containers:list({query = {all=true}})
if res.code <300 then containers = res.body else return end
local urlencode = luci.http.protocol and luci.http.protocol.urlencode or luci.util.urlencode
function get_containers()
local data = {}
if type(containers) ~= "table" then return nil end
for i, v in ipairs(containers) do
local index = v.Created .. v.Id
data[index]={}
data[index]["_selected"] = 0
data[index]["_id"] = v.Id:sub(1,12)
data[index]["name"] = v.Names[1]:sub(2)
data[index]["_name"] = '<a href='..luci.dispatcher.build_url("admin/services/docker/container/"..v.Id)..' class="dockerman_link" title="'..translate("Container detail")..'">'.. v.Names[1]:sub(2).."</a>"
data[index]["_status"] = v.Status
if v.Status:find("^Up") then
data[index]["_status"] = '<font color="green">'.. data[index]["_status"] .. "</font>"
else
data[index]["_status"] = '<font color="red">'.. data[index]["_status"] .. "</font>"
end
if (type(v.NetworkSettings) == "table" and type(v.NetworkSettings.Networks) == "table") then
for networkname, netconfig in pairs(v.NetworkSettings.Networks) do
data[index]["_network"] = (data[index]["_network"] ~= nil and (data[index]["_network"] .." | ") or "").. networkname .. (netconfig.IPAddress ~= "" and (": " .. netconfig.IPAddress) or "")
end
end
-- networkmode = v.HostConfig.NetworkMode ~= "default" and v.HostConfig.NetworkMode or "bridge"
-- data[index]["_network"] = v.NetworkSettings.Networks[networkmode].IPAddress or nil
-- local _, _, image = v.Image:find("^sha256:(.+)")
-- if image ~= nil then
-- image=image:sub(1,12)
-- end
if v.Ports then
data[index]["_ports"] = nil
for _,v2 in ipairs(v.Ports) do
data[index]["_ports"] = (data[index]["_ports"] and (data[index]["_ports"] .. ", ") or "") .. (v2.PublicPort and (v2.PublicPort .. ":") or "") .. (v2.PrivatePort and (v2.PrivatePort .."/") or "") .. (v2.Type and v2.Type or "")
end
end
for ii,iv in ipairs(images) do
if iv.Id == v.ImageID then
data[index]["_image"] = iv.RepoTags and iv.RepoTags[1] or (iv.RepoDigests[1]:gsub("(.-)@.+", "%1") .. ":<none>")
end
end
data[index]["_image_id"] = v.ImageID:sub(8,20)
data[index]["_command"] = v.Command
end
return data
end
local c_lists = get_containers()
-- list Containers
-- m = Map("docker", translate("Docker"))
m = SimpleForm("docker", translate("Docker"))
m.template = "dockerman/cbi/xsimpleform"
m.submit=false
m.reset=false
docker_status = m:section(SimpleSection)
docker_status.template = "dockerman/apply_widget"
docker_status.err=docker:read_status()
docker_status.err=docker_status.err and docker_status.err:gsub("\n","<br>"):gsub(" "," ")
if docker_status.err then docker:clear_status() end
c_table = m:section(Table, c_lists, translate("Containers"))
c_table.nodescr=true
-- v.template = "cbi/tblsection"
-- v.sortable = true
container_selecter = c_table:option(Flag, "_selected","")
container_selecter.disabled = 0
container_selecter.enabled = 1
container_selecter.default = 0
container_id = c_table:option(DummyValue, "_id", translate("ID"))
container_id.width="10%"
container_name = c_table:option(DummyValue, "_name", translate("Container Name"))
container_name.rawhtml = true
container_status = c_table:option(DummyValue, "_status", translate("Status"))
container_status.width="15%"
container_status.rawhtml=true
container_ip = c_table:option(DummyValue, "_network", translate("Network"))
container_ip.width="15%"
container_ports = c_table:option(DummyValue, "_ports", translate("Ports"))
container_ports.width="10%"
container_image = c_table:option(DummyValue, "_image", translate("Image"))
container_image.width="10%"
container_command = c_table:option(DummyValue, "_command", translate("Command"))
container_command.width="20%"
container_selecter.write=function(self, section, value)
c_lists[section]._selected = value
end
local start_stop_remove = function(m,cmd)
local c_selected = {}
-- 遍历table中sectionid
local c_table_sids = c_table:cfgsections()
for _, c_table_sid in ipairs(c_table_sids) do
-- 得到选中项的名字
if c_lists[c_table_sid]._selected == 1 then
c_selected[#c_selected+1] = c_lists[c_table_sid].name --container_name:cfgvalue(c_table_sid)
end
end
if #c_selected >0 then
docker:clear_status()
local success = true
for _,cont in ipairs(c_selected) do
docker:append_status("Containers: " .. cmd .. " " .. cont .. "...")
local res = dk.containers[cmd](dk, {id = cont})
if res and res.code >= 300 then
success = false
docker:append_status("code:" .. res.code.." ".. (res.body.message and res.body.message or res.message).. "\n")
else
docker:append_status("done\n")
end
end
if success then docker:clear_status() end
luci.http.redirect(luci.dispatcher.build_url("admin/services/docker/containers"))
end
end
action_section = m:section(Table,{{}})
action_section.notitle=true
action_section.rowcolors=false
action_section.template="cbi/nullsection"
btnnew=action_section:option(Button, "_new")
btnnew.inputtitle= translate("New")
btnnew.template = "dockerman/cbi/inlinebutton"
btnnew.inputstyle = "add"
btnnew.forcewrite = true
btnstart=action_section:option(Button, "_start")
btnstart.template = "dockerman/cbi/inlinebutton"
btnstart.inputtitle=translate("Start")
btnstart.inputstyle = "apply"
btnstart.forcewrite = true
btnrestart=action_section:option(Button, "_restart")
btnrestart.template = "dockerman/cbi/inlinebutton"
btnrestart.inputtitle=translate("Restart")
btnrestart.inputstyle = "reload"
btnrestart.forcewrite = true
btnstop=action_section:option(Button, "_stop")
btnstop.template = "dockerman/cbi/inlinebutton"
btnstop.inputtitle=translate("Stop")
btnstop.inputstyle = "reset"
btnstop.forcewrite = true
btnremove=action_section:option(Button, "_remove")
btnremove.template = "dockerman/cbi/inlinebutton"
btnremove.inputtitle=translate("Remove")
btnremove.inputstyle = "remove"
btnremove.forcewrite = true
btnnew.write = function(self, section)
luci.http.redirect(luci.dispatcher.build_url("admin/services/docker/newcontainer"))
end
btnstart.write = function(self, section)
start_stop_remove(m,"start")
end
btnrestart.write = function(self, section)
start_stop_remove(m,"restart")
end
btnremove.write = function(self, section)
start_stop_remove(m,"remove")
end
btnstop.write = function(self, section)
start_stop_remove(m,"stop")
end
return m
|
return {
init_effect = "",
name = "DOA联动 fever BUFF",
time = 3,
color = "blue",
picture = "",
desc = "",
stack = 1,
id = 8761,
last_effect = "Health",
effect_list = {}
}
|
-----------------------------------
-- Area: Western Altepa Desert
-- Mob: Cactuar
-- Note: Place holder for Cactuar_Cantautor
-----------------------------------
local ID = require("scripts/zones/Western_Altepa_Desert/IDs")
require("scripts/globals/regimes")
require("scripts/globals/mobs")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 136, 2, tpz.regime.type.FIELDS)
end
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob, ID.mob.CACTUAR_CANTAUTOR_PH, 5, math.random(3600,43200)) -- 1 to 12 hours
end
|
local M = {}
function M.udgj_label(url, text)
local upper = true
label.set_text(url, text)
timer.delay(0.3, true, function()
upper = not upper
if upper then
text = string.upper(text)
else
text = string.lower(text)
end
label.set_text(url, text)
end)
end
function M.udgj_text(node, text)
local upper = true
gui.set_text(node, text)
timer.delay(0.3, true, function()
upper = not upper
if upper then
text = string.upper(text)
else
text = string.lower(text)
end
gui.set_text(node, text)
end)
end
return M |
-- Operators on a internal stack(`internal/stack.lua`)
-- When a `requireDependency` happens, we push the required
-- dependency onto the top of the stack; and when it finishes being
-- evaled, we pop it off from the stack.
return function(options)
local Utils = options.Utils
local Operators = {}
local function getInterfaceDotPath(package, demandingVersionNotion)
return
package
and package.provisions
and package.provisions[
demandingVersionNotion[4] or "default"
]
or "init"
end
local function makeChunkName(package, filePath)
return string.format("%s@%s@%s:%s",
package.name,
package.fork,
package.version,
filePath
)
end
function Operators.require(stack, dotPath)
local top = stack.top()
if not top.loaded[dotPath] then
local filename = Utils.path.convertDotPathToSlashPath(dotPath)
local file = assert(top.open(filename))
local evaled = assert(Utils.lang.evalOpenedFileAndClose(
file,
makeChunkName(top, filename),
_G
))()
top.loaded[dotPath] = evaled
end
return top.loaded[dotPath]
end
local function pushAndLocateDependency(stack, dependencyName)
local versionNotion = stack.top().dependencies[dependencyName]
assert(versionNotion, "Dependency not registered!")
stack.push(versionNotion)
local newTop = stack.top()
local dotPath = getInterfaceDotPath(newTop, versionNotion)
assert(dotPath, "Entry point interface not registered!")
return dotPath, newTop
end
function Operators.requireDependencyFile(stack, dependencyName)
local dotPath, newTop = pushAndLocateDependency(stack, dependencyName)
local filename = Utils.path.convertDotPathToSlashPath(dotPath)
local file = assert(newTop.open(filename))
stack.pop()
return file
end
function Operators.requireDependency(stack, dependencyName)
local dotPath, newTop = pushAndLocateDependency(stack, dependencyName)
if not newTop.loaded[dotPath] then
local filename = Utils.path.convertDotPathToSlashPath(dotPath)
local file = assert(newTop.open(filename))
local evaled = assert(Utils.lang.evalOpenedFileAndClose(
file,
makeChunkName(newTop, filename),
_G
))()
newTop.loaded[dotPath] = evaled
end
stack.pop()
return newTop.loaded[dotPath]
end
return Operators
end
|
require "test-setup"
require "lunit"
local Cairo = require "oocairo"
module("test.general", lunit.testcase, package.seeall)
function test_support_flags ()
for _, feature in ipairs{
"HAS_PDF_SURFACE", "HAS_PNG_FUNCTIONS", "HAS_PS_SURFACE",
"HAS_SVG_SURFACE", "HAS_USER_FONT"
} do
assert_boolean(Cairo[feature], "flag for feature " .. feature)
end
end
-- vi:ts=4 sw=4 expandtab
|
------------------------------------------------------------------------
--[[ RandomSampler ]]--
-- DataSet iterator
-- Randomly samples batches from a dataset.
------------------------------------------------------------------------
local RandomSampler, parent = torch.class("dp.RandomSampler", "dp.Sampler")
--Returns an iterator over samples for one epoch
function RandomSampler:sampleEpoch(dataset)
dataset = dp.RandomSampler.toDataset(dataset)
local nSample = dataset:nSample()
local epochSize = self._epoch_size or nSample
self._start = self._start or 1
local nSampled = 0
local stop
-- build iterator
return function(batch)
if nSampled >= epochSize then
return
end
batch = batch or dataset:sample(self._batch_size)
-- inputs and targets
dataset:sample(batch, self._batch_size)
-- metadata
batch:setup{
batch_iter=nSampled, batch_size=self._batch_size,
n_sample=self._batch_size
}
batch = self._ppf(batch)
nSampled = nSampled + self._batch_size
self._start = self._start + self._batch_size
if self._start >= nSample then
self._start = 1
end
self:collectgarbage()
return batch, math.min(nSampled, epochSize), epochSize
end
end
-- used with datasets that support asynchronous iterators like ImageClassSet
function RandomSampler:sampleEpochAsync(dataset)
dataset = dp.Sampler.toDataset(dataset)
local nSample = dataset:nSample()
local epochSize = self._epoch_size or nSample
self._start = self._start or 1
local nSampledPut = 0
local nSampledGet = 0
-- build iterator
local sampleBatch = function(batch, putOnly)
if nSampledGet >= epochSize then
return
end
if nSampledPut < epochSize then
-- up values
local uvbatchsize = self._batch_size
local uvstart = self._start
dataset:sampleAsyncPut(batch, self._batch_size, nil,
function(batch)
local indices = batch:indices() or torch.Tensor()
-- metadata
batch:setup{batch_iter=uvstop, batch_size=batch:nSample()}
batch = self._ppf(batch)
end)
nSampledPut = nSampledPut + self._batch_size
self._start = self._start + self._batch_size
if self._start >= nSample then
self._start = 1
end
end
if not putOnly then
batch = dataset:asyncGet()
nSampledGet = nSampledGet + self._batch_size
self:collectgarbage()
return batch, math.min(nSampledGet, epochSize), epochSize
end
end
assert(dataset.isAsync, "expecting asynchronous dataset")
-- empty the async queue
dataset:synchronize()
-- fill task queue with some batch requests
for tidx=1,dataset.nThread do
sampleBatch(nil, true)
end
return sampleBatch
end
|
--
-- Name: codelite/codelite_workspace.lua
-- Purpose: Generate a CodeLite workspace.
-- Author: Ryan Pusztai
-- Modified by: Andrea Zanellato
-- Manu Evans
-- Created: 2013/05/06
-- Copyright: (c) 2008-2015 Jason Perkins and the Premake project
--
local p = premake
local project = p.project
local workspace = p.workspace
local tree = p.tree
local codelite = p.modules.codelite
codelite.workspace = {}
local m = codelite.workspace
--
-- Generate a CodeLite workspace
--
function m.generate(wks)
p.utf8()
--
-- Header
--
p.w('<?xml version="1.0" encoding="UTF-8"?>')
local tagsdb = ""
-- local tagsdb = "./" .. wks.name .. ".tags"
p.push('<CodeLite_Workspace Name="%s" Database="%s" SWTLW="No">', wks.name, tagsdb)
--
-- Project list
--
local tr = workspace.grouptree(wks)
tree.traverse(tr, {
onleaf = function(n)
local prj = n.project
-- Build a relative path from the workspace file to the project file
local prjpath = p.filename(prj, ".project")
prjpath = path.getrelative(prj.workspace.location, prjpath)
if (prj.name == wks.startproject) then
p.w('<Project Name="%s" Path="%s" Active="Yes"/>', prj.name, prjpath)
else
p.w('<Project Name="%s" Path="%s"/>', prj.name, prjpath)
end
end,
onbranchenter = function(n)
p.push('<VirtualDirectory Name="%s">', n.name)
end,
onbranchexit = function(n)
p.pop('</VirtualDirectory>')
end,
})
--
-- Configurations
--
-- count the number of platforms
local platformsPresent = {}
local numPlatforms = 0
for cfg in workspace.eachconfig(wks) do
local platform = cfg.platform
if platform and not platformsPresent[platform] then
numPlatforms = numPlatforms + 1
platformsPresent[platform] = true
end
end
if numPlatforms >= 2 then
codelite.workspace.multiplePlatforms = true
end
-- for each workspace config
p.push('<BuildMatrix>')
for cfg in workspace.eachconfig(wks) do
local cfgname = codelite.cfgname(cfg)
p.push('<WorkspaceConfiguration Name="%s" Selected="yes">', cfgname)
local tr = workspace.grouptree(wks)
tree.traverse(tr, {
onleaf = function(n)
local prj = n.project
p.w('<Project Name="%s" ConfigName="%s"/>', prj.name, cfgname)
end
})
p.pop('</WorkspaceConfiguration>')
end
p.pop('</BuildMatrix>')
p.pop('</CodeLite_Workspace>')
end
|
local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
local packer_ok, packer = pcall(require, "packer")
if not packer_ok then return end
packer.init {
git = {clone_timeout = 300},
max_jobs = 50,
display = {
open_fn = function()
return require("packer.util").float {border = "single"}
end
}
}
-- Auto compile when there are changes in plugins.lua
vim.cmd "autocmd BufWritePost plugins.lua PackerCompile"
|
require 'cutorch'
require 'cunn'
require 'cudnn'
require 'nngraph'
require 'composition/composition_models.CompositionModel'
require 'composition/composition_models.HeadOnly'
require 'composition/composition_models.ModifierOnly'
require 'composition/composition_models.Addition'
require 'composition/composition_models.Multiplication'
require 'iterators.BatchIterator'
local composition_tests = torch.TestSuite()
local tester = torch.Tester()
local gpuid = 1
print('using CUDA on GPU ' .. gpuid .. '...')
cutorch.setDevice(gpuid)
print('Running on device: ' .. cutorch.getDeviceProperties(cutorch.getDevice()).name)
function composition_tests.Addition()
local sz = 5
local config = {batchSize = 2}
local composition_model = torch.Addition(sz * 2, sz)
local mlp = composition_model:architecture(config)
mlp:cuda()
local u = torch.Tensor({{1,2,3,4,5},{2,3,4,5,6}}):cuda()
local v = torch.Tensor({{6,7,8,9,10}, {7,8,9,10,11}}):cuda()
local input = {u, v}
local output = mlp:forward(input)
local expected_output = torch.Tensor(2,5):cuda()
expected_output[1] = torch.Tensor{7,9,11,13,15}
expected_output[2] = torch.Tensor{9,11,13,15,17}
tester:eq(output, expected_output, "output and expected_output should be equal")
end
function composition_tests.Head()
local sz = 5
local config = {batchSize = 2}
local composition_model = torch.HeadOnly(sz * 2, sz)
local mlp = composition_model:architecture(config)
mlp:cuda()
local u = torch.Tensor({{1,2,3,4,5},{2,3,4,5,6}}):cuda()
local v = torch.Tensor({{6,7,8,9,10}, {7,8,9,10,11}}):cuda()
local input = {u, v}
local output = mlp:forward(input)
local expected_output = torch.Tensor(2,5):cuda()
expected_output[1] = torch.Tensor{6,7,8,9,10}
expected_output[2] = torch.Tensor{7,8,9,10,11}
tester:eq(output, expected_output, "output and expected_output should be equal")
end
function composition_tests.Modifier()
local sz = 5
local config = {batchSize = 2}
local composition_model = torch.ModifierOnly(sz * 2, sz)
local mlp = composition_model:architecture(config)
mlp:cuda()
local u = torch.Tensor({{1,2,3,4,5},{2,3,4,5,6}}):cuda()
local v = torch.Tensor({{6,7,8,9,10}, {7,8,9,10,11}}):cuda()
local input = {u, v}
local output = mlp:forward(input)
local expected_output = torch.Tensor(2,5):cuda()
expected_output[1] = torch.Tensor{1,2,3,4,5}
expected_output[2] = torch.Tensor{2,3,4,5,6}
tester:eq(output, expected_output, "output and expected_output should be equal")
end
function composition_tests.Multiplication()
local sz = 5
local config = {batchSize = 2}
local composition_model = torch.Multiplication(sz * 2, sz)
local mlp = composition_model:architecture(config)
mlp:cuda()
local u = torch.Tensor({{1,2,3,4,5},{2,3,4,5,6}}):cuda()
local v = torch.Tensor({{6,7,8,9,10}, {7,8,9,10,11}}):cuda()
local input = {u, v}
local output = mlp:forward(input)
local expected_output = torch.Tensor(2,5):cuda()
expected_output[1] = torch.Tensor{6,14,24,36,50}
expected_output[2] = torch.Tensor{14,24,36,50,66}
tester:eq(output, expected_output, "output and expected_output should be equal")
end
tester:add(composition_tests)
tester:run()
|
function instructions()
showTextScreen([[jEM FELL THROUGH A PORTAL TO A
STRANGE, ALIEN WORLD.
hER COLLEAGUES - vAN AND eSS -
ARE WORKING TO GET BACK HOME.
hELP jEM EXPLORE THIS WORLD
AND PROTECT HER FRIENDS.
- jUMP WITH 🅾️.
- wHIP WITH ❎.
- tRY WHIPPING EVERYTHING.
- wHEN ADJUSTING DEVICES:
🅾️ CHANGES TYPE, ARROWS AIM.
- oN GRAPPLE POINT:
❎ TO ENTER ADJUST MODE.;3;25]])
end |
local budki = {
{2493.79,-1684.33,13.51,354.9, numer=1},
{1126.34,-2031.77,69.89,270.1, numer=2},
{1638.51,1309.58,12.16,270, numer=3},
{-2134.01,928.08,80.00,90,numer=4},
{-2410.52,-607.04,132.69,36, numer=5},
{-253.35,2592.72,63.57,180, numer=6},
}
budka_object = {}
budka_marker = {}
addEventHandler("onClientResourceStart", resourceRoot,function()
for i,v in ipairs(budki) do
budka_object[v.numer]=createObject(1216, v[1], v[2], v[3]-0.5, 0,0, v[4]-180)
budka_marker[v.numer]=createColSphere(v[1], v[2], v[3], 1)
local text = createElement("text")
setElementPosition(text, v[1], v[2], v[3]+1)
setElementData(text, "text", "Budka telefoniczna")
--setElementData(budka_marker[v.numer], "budkanumer", v.numer)
--budki[i].blip=createBlip(v.locb[1], v.locb[2], v.locb[3], 56, 1, 0, 0, 0, 255, 100,100)
end
end) |
local utils = {}
utils.Cuda = require('onmt.utils.Cuda')
utils.Dict = require('onmt.utils.Dict')
utils.SubDict = require('onmt.utils.SubDict')
utils.FileReader = require('onmt.utils.FileReader')
utils.Tensor = require('onmt.utils.Tensor')
utils.Table = require('onmt.utils.Table')
utils.String = require('onmt.utils.String')
utils.Memory = require('onmt.utils.Memory')
utils.MemoryOptimizer = require('onmt.utils.MemoryOptimizer')
utils.Parallel = require('onmt.utils.Parallel')
utils.Features = require('onmt.utils.Features')
utils.Logger = require('onmt.utils.Logger')
utils.Profiler = require('onmt.utils.Profiler')
utils.ExtendedCmdLine = require('onmt.utils.ExtendedCmdLine')
utils.CrayonLogger = require('onmt.utils.CrayonLogger')
return utils
|
chemistry = {}
chemistry.substances = {}
chemistry.reactions = {}
chemistry.nodes = {}
local modpath = minetest.get_modpath("chemistry")
dofile(modpath.."/api.lua")
dofile(modpath.."/flask.lua")
dofile(modpath.."/workbench.lua")
dofile(modpath.."/substances.lua")
|
require( "engine.client.camera" )
require( "game.shared.construction" )
local gui = gui
local map = map
local _G = _G
local require = require
local construction = construction
local r_draw_position = convar( "r_draw_position", "0", nil, nil,
"Draws position" )
module( "game.client" )
function draw()
if ( not _G.localplayer._initialized ) then
return
end
-- Draw panels to worldspace
gui.preDrawWorld()
-- Draw world
map.drawWorld()
end
function load( arg )
require "game.shared"
end
function onMainMenuActivate()
end
function onMainMenuClose()
end
function tick( timestep )
end
function shutdown()
construction.clear()
end
function update( dt )
end
|
print(type(true))
print(type(false))
print(type(nil))
|
-- Training of ED models.
if opt.opt == 'SGD' then
optimState = {
learningRate = opt.lr,
momentum = 0.9,
learningRateDecay = 5e-7
}
optimMethod = optim.sgd
elseif opt.opt == 'ADAM' then -- See: http://cs231n.github.io/neural-networks-3/#update
optimState = {
learningRate = opt.lr,
}
optimMethod = optim.adam
elseif opt.opt == 'ADADELTA' then -- See: http://cs231n.github.io/neural-networks-3/#update
-- Run with default parameters, no need for learning rate and other stuff
optimState = {}
optimConfig = {}
optimMethod = optim.adadelta
elseif opt.opt == 'ADAGRAD' then -- See: http://cs231n.github.io/neural-networks-3/#update
optimMethod = optim.adagrad
optimState = {
learningRate = opt.lr
}
else
error('unknown optimization method')
end
----------------------------------------------------------------------
-- Each batch is one document, so we test/validate/save the current model after each set of
-- 5000 documents. Since aida-train contains 946 documents, this is equivalent with 5 full epochs.
num_batches_per_epoch = 5000
function train_and_test()
print('\nDone testing for ' .. banner)
print('Params serialized = ' .. params_serialized)
-- epoch tracker
epoch = 1
local processed_so_far = 0
local f_bs = 0
local gradParameters_bs = nil
while true do
local time = sys.clock()
print('\n')
print('One epoch = ' .. (num_batches_per_epoch / 1000) .. ' full passes over AIDA-TRAIN in our case.')
print(green('==> TRAINING EPOCH #' .. epoch .. ' <=='))
print_net_weights()
local processed_mentions = 0
for batch_index = 1,num_batches_per_epoch do
-- Read one mini-batch from one data_thread:
local inputs, targets = get_minibatch()
local num_mentions = targets:size(1)
processed_mentions = processed_mentions + num_mentions
local model, _ = get_model(num_mentions)
model:training()
-- Retrieve parameters and gradients:
-- extracts and flattens all model's parameters into a 1-dim vector
parameters,gradParameters = model:getParameters()
gradParameters:zero()
-- Just in case:
collectgarbage()
collectgarbage()
-- Reset gradients
gradParameters:zero()
-- Evaluate function for complete mini batch
local outputs = model:forward(inputs)
assert(outputs:size(1) == num_mentions and outputs:size(2) == max_num_cand)
local f = criterion:forward(outputs, targets)
-- Estimate df/dW
local df_do = criterion:backward(outputs, targets)
model:backward(inputs, df_do)
if opt.batch_size == 1 or batch_index % opt.batch_size == 1 then
gradParameters_bs = gradParameters:clone():zero()
f_bs = 0
end
gradParameters_bs:add(gradParameters)
f_bs = f_bs + f
if opt.batch_size == 1 or batch_index % opt.batch_size == 0 then
gradParameters_bs:div(opt.batch_size)
f_bs = f_bs / opt.batch_size
-- Create closure to evaluate f(X) and df/dX
local feval = function(x)
return f_bs, gradParameters_bs
end
-- Optimize on current mini-batch
optimState.learningRate = opt.lr
optimMethod(feval, parameters, optimState)
-- Regularize the f_network with projected SGD.
regularize_f_network()
end
-- Display progress
processed_so_far = processed_so_far + num_mentions
if processed_so_far > 100000000 then
processed_so_far = processed_so_far - 100000000
end
xlua.progress(processed_so_far, 100000000)
end
-- Measure time taken
time = sys.clock() - time
time = time / processed_mentions
print("\n==> time to learn 1 sample = " .. (time*1000) .. 'ms')
-- Test:
test(epoch)
print('\nDone testing for ' .. banner)
print('Params serialized = ' .. params_serialized)
-- Save the current model:
if opt.save then
local filename = opt.root_data_dir .. 'generated/ed_models/' .. params_serialized .. '|ep=' .. epoch
print('==> saving model to '..filename)
torch.save(filename, pack_saveable_weights())
end
-- Next epoch
epoch = epoch + 1
end
end
|
Player = game:GetService("Players").olefson
Character = Player.Character
PlayerGui = Player.PlayerGui
Backpack = Player.Backpack
Torso = Character.Torso
Head = Character.Head
LeftArm = Character["Left Arm"]
LeftLeg = Character["Left Leg"]
RightArm = Character["Right Arm"]
RightLeg = Character["Right Leg"]
LS = Torso["Left Shoulder"]
LH = Torso["Left Hip"]
RS = Torso["Right Shoulder"]
RH = Torso["Right Hip"]
attack = false
attacktype = 1
damage = 3
oridamage = 3
--player
player = nil
--save shoulders
RSH, LSH = nil, nil
--welds
RW, LW = Instance.new("Weld"), Instance.new("Weld")
--what anim
anim = "none"
unsheathed = false
tornadoing = false
if Character:findFirstChild("Main Weapons",true) ~= nil then
Character:findFirstChild("Main Weapons",true).Parent = nil
end
--[[Models and Parts]]--
local modelzorz = Instance.new("Model")
modelzorz.Name = "Main Weapons"
modelzorz.Parent = Character
local model1 = Instance.new("Model")
model1.Name = "GunSword" --Yes I know. This is from Squall from FF7 right? Well I didn't copied this from him.
model1.Parent = modelzorz
local model2 = Instance.new("Model")
model2.Name = "BlastCannon"
model2.Parent = nil
local model3 = Instance.new("Model")
model3.Name = "LaserRifle"
model3.Parent = nil
local model4 = Instance.new("Model")
model4.Name = "Tornado Skates"
model4.Parent = nil
local prt1 = Instance.new("Part")
prt1.formFactor = 1
prt1.Parent = model1
prt1.CanCollide = false
prt1.BrickColor = BrickColor.new("Dark stone grey")
prt1.Name = "Handle1"
prt1.Size = Vector3.new(1,1,1)
prt1.Position = Torso.Position
local prt2 = Instance.new("Part")
prt2.formFactor = 1
prt2.Parent = model1
prt2.CanCollide = false
prt2.BrickColor = BrickColor.new("Medium stone grey")
prt2.Name = "Handle2"
prt2.Size = Vector3.new(1,1,1)
prt2.Position = Torso.Position
local prt3 = Instance.new("Part")
prt3.formFactor = 1
prt3.Reflectance = 0.05
prt3.Parent = model1
prt3.CanCollide = false
prt3.BrickColor = BrickColor.new("Black")
prt3.Name = "Blade1"
prt3.Size = Vector3.new(1,4,1)
prt3.Position = Torso.Position
local prt4 = Instance.new("Part")
prt4.formFactor = 1
prt4.Reflectance = 0.05
prt4.Parent = model1
prt4.CanCollide = false
prt4.BrickColor = BrickColor.new("Black")
prt4.Name = "Blade2"
prt4.Size = Vector3.new(1,1,1)
prt4.Position = Torso.Position
local prt5 = Instance.new("Part")
prt5.formFactor = 1
prt5.Parent = model1
prt5.CanCollide = false
prt5.BrickColor = BrickColor.new("Medium stone grey")
prt5.Name = "Barrel"
prt5.Size = Vector3.new(1,1,1)
prt5.Position = Torso.Position
local prt6 = Instance.new("Part")
prt6.formFactor = 1
prt6.Parent = model1
prt6.CanCollide = false
prt6.BrickColor = BrickColor.new("Black")
prt6.Name = "Shell1" --I had a REALLY, hard time CFraming all these shells >.<
prt6.Size = Vector3.new(1,1,1)
prt6.Position = Torso.Position
local prt7 = Instance.new("Part")
prt7.formFactor = 1
prt7.Parent = model1
prt7.CanCollide = false
prt7.BrickColor = BrickColor.new("Black")
prt7.Name = "Shell2"
prt7.Size = Vector3.new(1,1,1)
prt7.Position = Torso.Position
local prt8 = Instance.new("Part")
prt8.formFactor = 1
prt8.Parent = model1
prt8.CanCollide = false
prt8.BrickColor = BrickColor.new("Black")
prt8.Name = "Shell3"
prt8.Size = Vector3.new(1,1,1)
prt8.Position = Torso.Position
local prt9 = Instance.new("Part")
prt9.formFactor = 1
prt9.Parent = model1
prt9.CanCollide = false
prt9.BrickColor = BrickColor.new("Black")
prt9.Name = "Shell4"
prt9.Size = Vector3.new(1,1,1)
prt9.Position = Torso.Position
local prt10 = Instance.new("Part")
prt10.formFactor = 1
prt10.Parent = model1
prt10.CanCollide = false
prt10.BrickColor = BrickColor.new("Black")
prt10.Name = "Shell5"
prt10.Size = Vector3.new(1,1,1)
prt10.Position = Torso.Position
local prt11 = Instance.new("Part")
prt11.formFactor = 1
prt11.Parent = model1
prt11.CanCollide = false
prt11.BrickColor = BrickColor.new("Black")
prt11.Name = "Shell6"
prt11.Size = Vector3.new(1,1,1)
prt11.Position = Torso.Position
local prt12 = Instance.new("Part")
prt12.formFactor = 1
prt12.Parent = model1
prt12.CanCollide = false
prt12.BrickColor = BrickColor.new("Medium stone grey")
prt12.Name = "Gun1"
prt12.Size = Vector3.new(1,2,1)
prt12.Position = Torso.Position
local prt13 = Instance.new("Part")
prt13.formFactor = 1
prt13.Parent = model1
prt13.CanCollide = false
prt13.BrickColor = BrickColor.new("Medium stone grey")
prt13.Name = "Gun2"
prt13.Size = Vector3.new(1,1,1)
prt13.Position = Torso.Position
local prt13a = Instance.new("Part")
prt13a.formFactor = 1
prt13a.Parent = model1
prt13a.CanCollide = false
prt13a.BrickColor = BrickColor.new("Black")
prt13a.Name = "Gun3"
prt13a.Size = Vector3.new(1,1,1)
prt13a.Position = Torso.Position
local prt14 = Instance.new("Part")
prt14.formFactor = 1
prt14.Parent = model1
prt14.CanCollide = false
prt14.BrickColor = BrickColor.new("Medium stone grey")
prt14.Name = "Trigger1"
prt14.Size = Vector3.new(1,1,1)
prt14.Position = Torso.Position
local prt15 = Instance.new("Part")
prt15.formFactor = 1
prt15.Parent = model1
prt15.CanCollide = false
prt15.BrickColor = BrickColor.new("Medium stone grey")
prt15.Name = "Trigger2"
prt15.Size = Vector3.new(1,1,1)
prt15.Position = Torso.Position
local prt16 = Instance.new("Part")
prt16.formFactor = 1
prt16.Parent = model2
prt16.Reflectance = 0.2
prt16.CanCollide = false
prt16.BrickColor = BrickColor.new("Black")
prt16.Name = "CannonHandle1"
prt16.Size = Vector3.new(1,2,1)
prt16.Position = Torso.Position
local prt17 = Instance.new("Part")
prt17.formFactor = 1
prt17.Parent = model2
prt17.Reflectance = 0.2
prt17.CanCollide = false
prt17.BrickColor = BrickColor.new("Black")
prt17.Name = "CannonHandle2"
prt17.Size = Vector3.new(1,1,1)
prt17.Position = Torso.Position
local prt18 = Instance.new("Part")
prt18.formFactor = 1
prt18.Parent = model2
prt18.Reflectance = 0.2
prt18.CanCollide = false
prt18.BrickColor = BrickColor.new("Black")
prt18.Name = "CannonPart1"
prt18.Size = Vector3.new(1,2,1)
prt18.Position = Torso.Position
local prt19 = Instance.new("Part")
prt19.formFactor = 1
prt19.Parent = model2
prt19.Reflectance = 0.2
prt19.CanCollide = false
prt19.BrickColor = BrickColor.new("Black")
prt19.Name = "CannonPart2"
prt19.Size = Vector3.new(1,2,1)
prt19.Position = Torso.Position
local prt20 = Instance.new("Part")
prt20.formFactor = 1
prt20.Parent = model2
prt20.Reflectance = 0.2
prt20.CanCollide = false
prt20.BrickColor = BrickColor.new("White")
prt20.Name = "CannonHandle3"
prt20.Size = Vector3.new(1,2,1)
prt20.Position = Torso.Position
local prt21 = Instance.new("Part")
prt21.formFactor = 1
prt21.Parent = model2
prt21.Reflectance = 0.2
prt21.CanCollide = false
prt21.BrickColor = BrickColor.new("Black")
prt21.Name = "CannonPart3"
prt21.Size = Vector3.new(1,2,1)
prt21.Position = Torso.Position
local prt22 = Instance.new("Part")
prt22.formFactor = 1
prt22.Parent = model2
prt22.Reflectance = 0.2
prt22.CanCollide = false
prt22.BrickColor = BrickColor.new("Black")
prt22.Name = "CannonPart4"
prt22.Size = Vector3.new(1,2,1)
prt22.Position = Torso.Position
local prt23 = Instance.new("Part")
prt23.formFactor = 1
prt23.Parent = model2
prt23.Reflectance = 0.2
prt23.CanCollide = false
prt23.BrickColor = BrickColor.new("Medium stone grey")
prt23.Name = "CannonPart5"
prt23.Size = Vector3.new(1,1,1)
prt23.Position = Torso.Position
local prt24 = Instance.new("Part")
prt24.formFactor = 1
prt24.Parent = model2
prt24.Reflectance = 0
prt24.CanCollide = false
prt24.BrickColor = BrickColor.new("Black")
prt24.Name = "CannonPart6"
prt24.Size = Vector3.new(1,1,1)
prt24.Position = Torso.Position
local prt25 = Instance.new("Part")
prt25.formFactor = 1
prt25.Parent = model2
prt25.Reflectance = 0.2
prt25.CanCollide = false
prt25.BrickColor = BrickColor.new("Medium stone grey")
prt25.Name = "CannonPart7"
prt25.Size = Vector3.new(1,2,1)
prt25.Position = Torso.Position
local prt26 = Instance.new("Part")
prt26.formFactor = 1
prt26.Parent = model2
prt26.Reflectance = 0.2
prt26.CanCollide = false
prt26.BrickColor = BrickColor.new("Medium stone grey")
prt26.Name = "CannonPart8"
prt26.Size = Vector3.new(1,1,1)
prt26.Position = Torso.Position
local prt27 = Instance.new("Part")
prt27.formFactor = 1
prt27.Parent = model2
prt27.Reflectance = 0
prt27.CanCollide = false
prt27.BrickColor = BrickColor.new("Black")
prt27.Name = "CannonPart9"
prt27.Size = Vector3.new(1,1,1)
prt27.Position = Torso.Position
local prt28 = Instance.new("Part")
prt28.formFactor = 1
prt28.Parent = model2
prt28.Reflectance = 0
prt28.CanCollide = false
prt28.BrickColor = BrickColor.new("Black")
prt28.Name = "CannonPart10"
prt28.Size = Vector3.new(1,1,1)
prt28.Position = Torso.Position
local prt29 = Instance.new("Part")
prt29.formFactor = 1
prt29.Parent = model2
prt29.Reflectance = 0.2
prt29.CanCollide = false
prt29.BrickColor = BrickColor.new("Black")
prt29.Name = "CannonPart11"
prt29.Size = Vector3.new(1,2,1)
prt29.Position = Torso.Position
local prt30 = Instance.new("Part")
prt30.formFactor = 1
prt30.Parent = model2
prt30.Reflectance = 0
prt30.CanCollide = false
prt30.BrickColor = BrickColor.new("Bright red")
prt30.Name = "CannonPart12"
prt30.Size = Vector3.new(1,2,1)
prt30.Position = Torso.Position
local prt31 = Instance.new("Part")
prt31.formFactor = 1
prt31.Parent = model2
prt31.Reflectance = 0
prt31.CanCollide = false
prt31.BrickColor = BrickColor.new("Black")
prt31.Name = "CannonPart13"
prt31.Size = Vector3.new(1,2,1)
prt31.Position = Torso.Position
local prt32 = Instance.new("Part")
prt32.formFactor = 1
prt32.Parent = model3
prt32.Reflectance = 0
prt32.CanCollide = false
prt32.BrickColor = BrickColor.new("Bright blue")
prt32.Name = "LRhandle1"
prt32.Size = Vector3.new(1,1,1)
prt32.Position = Torso.Position
local prt32a = Instance.new("Part")
prt32a.formFactor = 1
prt32a.Parent = model3
prt32a.Reflectance = 0
prt32a.CanCollide = false
prt32a.BrickColor = BrickColor.new("Black")
prt32a.Name = "LRhandle1a"
prt32a.Size = Vector3.new(1,1,1)
prt32a.Position = Torso.Position
local prt33 = Instance.new("Part")
prt33.formFactor = 1
prt33.Parent = model3
prt33.Reflectance = 0
prt33.CanCollide = false
prt33.BrickColor = BrickColor.new("Bright blue")
prt33.Name = "LRhandle2"
prt33.Size = Vector3.new(1,1,1)
prt33.Position = Torso.Position
local prt34 = Instance.new("Part")
prt34.formFactor = 1
prt34.Parent = model3
prt34.Reflectance = 0
prt34.CanCollide = false
prt34.BrickColor = BrickColor.new("Bright blue")
prt34.Name = "LRPart1"
prt34.Size = Vector3.new(1,2,1)
prt34.Position = Torso.Position
local prt35 = Instance.new("Part")
prt35.formFactor = 1
prt35.Parent = model3
prt35.Reflectance = 0
prt35.CanCollide = false
prt35.BrickColor = BrickColor.new("Bright blue")
prt35.Name = "LRPart2"
prt35.Size = Vector3.new(1,1,1)
prt35.Position = Torso.Position
local prt36 = Instance.new("Part")
prt36.formFactor = 1
prt36.Parent = model3
prt36.Reflectance = 0
prt36.Reflectance = 0.2
prt36.CanCollide = false
prt36.BrickColor = BrickColor.new("White")
prt36.Name = "LRPart3"
prt36.Size = Vector3.new(1,1,1)
prt36.Position = Torso.Position
local prt37 = Instance.new("Part")
prt37.formFactor = 1
prt37.Parent = model3
prt37.Reflectance = 0
prt37.Reflectance = 0.2
prt37.CanCollide = false
prt37.BrickColor = BrickColor.new("New Yeller")
prt37.Name = "LRPart4"
prt37.Size = Vector3.new(1,1,1)
prt37.Position = Torso.Position
local prt38 = Instance.new("Part")
prt38.formFactor = 1
prt38.Parent = model3
prt38.Reflectance = 0
prt38.CanCollide = false
prt38.BrickColor = BrickColor.new("White")
prt38.Name = "LRDesign1"
prt38.Size = Vector3.new(1,1,1)
prt38.Position = Torso.Position
local prt39 = Instance.new("Part")
prt39.formFactor = 1
prt39.Parent = model3
prt39.Reflectance = 0
prt39.CanCollide = false
prt39.BrickColor = BrickColor.new("Bright blue")
prt39.Name = "LRDesign2"
prt39.Size = Vector3.new(1,1,1)
prt39.Position = Torso.Position
local prt40 = Instance.new("Part")
prt40.formFactor = 1
prt40.Parent = model3
prt40.Reflectance = 0
prt40.Transparency = 0.4
prt40.CanCollide = false
prt40.BrickColor = BrickColor.new("Medium stone grey")
prt40.Name = "TSPart1"
prt40.Size = Vector3.new(1,1,1)
prt40.Position = Torso.Position
local msh1 = Instance.new("BlockMesh")
msh1.Parent = prt1
msh1.Scale = Vector3.new(0.5,2,0.5)
local msh2 = Instance.new("BlockMesh")
msh2.Parent = prt2
msh2.Scale = Vector3.new(1,1,0.7)
local msh3 = Instance.new("BlockMesh")
msh3.Parent = prt3
msh3.Scale = Vector3.new(0.7,0.8,0.12)
local msh4 = Instance.new("SpecialMesh")
msh4.Parent = prt4
msh4.MeshType = "Wedge"
msh4.Scale = Vector3.new(0.12, 1, 1.1)
local msh5 = Instance.new("CylinderMesh")
msh5.Parent = prt5
msh5.Scale = Vector3.new(1,1,1)
local msh6 = Instance.new("CylinderMesh")
msh6.Parent = prt6
msh6.Scale = Vector3.new(1.1,1.1,0.3)
local msh7 = Instance.new("CylinderMesh")
msh7.Parent = prt7
msh7.Scale = Vector3.new(1.1,1.1,0.3)
local msh8 = Instance.new("CylinderMesh")
msh8.Parent = prt8
msh8.Scale = Vector3.new(1.1,1.1,0.3)
local msh9 = Instance.new("CylinderMesh")
msh9.Parent = prt9
msh9.Scale = Vector3.new(1.1,1.1,0.3)
local msh10 = Instance.new("CylinderMesh")
msh10.Parent = prt10
msh10.Scale = Vector3.new(1.1,1.1,0.3)
local msh11 = Instance.new("CylinderMesh")
msh11.Parent = prt11
msh11.Scale = Vector3.new(1.1,1.1,0.3)
local msh12 = Instance.new("CylinderMesh")
msh12.Parent = prt12
msh12.Scale = Vector3.new(1.2,1,0.4)
local msh13 = Instance.new("CylinderMesh")
msh13.Parent = prt13
msh13.Scale = Vector3.new(0.5,0.5,0.5)
local msh13a = Instance.new("CylinderMesh")
msh13a.Parent = prt13a
msh13a.Scale = Vector3.new(0.4,0.51,0.4)
local msh14 = Instance.new("SpecialMesh")
msh14.Parent = prt14
msh14.MeshId = "http://www.roblox.com/asset/?id=3270017"
msh14.Scale = Vector3.new(0.5,0.5,0.5)
local msh15 = Instance.new("BlockMesh")
msh15.Parent = prt15
msh15.Scale = Vector3.new(0.1,0.4,0.1)
local msh16 = Instance.new("BlockMesh")
msh16.Parent = prt16
msh16.Scale = Vector3.new(0.5,0.6,0.5)
local msh17 = Instance.new("BlockMesh")
msh17.Parent = prt17
msh17.Scale = Vector3.new(0.6,0.3,0.6)
local msh18 = Instance.new("BlockMesh")
msh18.Parent = prt18
msh18.Scale = Vector3.new(0.7,0.5,0.7)
local msh19 = Instance.new("BlockMesh")
msh19.Parent = prt19
msh19.Scale = Vector3.new(0.7,0.8,0.8)
local msh20 = Instance.new("BlockMesh")
msh20.Parent = prt20
msh20.Scale = Vector3.new(0.6,0.8,0.7)
local msh21 = Instance.new("BlockMesh")
msh21.Parent = prt21
msh21.Scale = Vector3.new(0.7,0.65,0.7)
local msh22 = Instance.new("BlockMesh")
msh22.Parent = prt22
msh22.Scale = Vector3.new(0.7,1.2,0.7)
local msh23 = Instance.new("CylinderMesh")
msh23.Parent = prt23
msh23.Scale = Vector3.new(0.5,0.5,0.5)
local msh24 = Instance.new("CylinderMesh")
msh24.Parent = prt24
msh24.Scale = Vector3.new(0.4,0.51,0.4)
local msh25 = Instance.new("CylinderMesh")
msh25.Parent = prt25
msh25.Scale = Vector3.new(0.5,0.9,0.5)
local msh26 = Instance.new("CylinderMesh")
msh26.Parent = prt26
msh26.Scale = Vector3.new(0.4,0.5,0.4)
local msh27 = Instance.new("CylinderMesh")
msh27.Parent = prt27
msh27.Scale = Vector3.new(0.3,0.51,0.3)
local msh28 = Instance.new("CylinderMesh")
msh28.Parent = prt28
msh28.Scale = Vector3.new(0.6,0.51,0.6)
local msh29 = Instance.new("BlockMesh")
msh29.Parent = prt29
msh29.Scale = Vector3.new(0.7,0.65,1)
local msh30 = Instance.new("CylinderMesh")
msh30.Parent = prt30
msh30.Scale = Vector3.new(1,0.65,1.2)
local msh31 = Instance.new("BlockMesh")
msh31.Parent = prt31
msh31.Scale = Vector3.new(0.9,0.9,0.5)
local msh32 = Instance.new("CylinderMesh")
msh32.Parent = prt32
msh32.Scale = Vector3.new(1.5,1.5,1.5)
local msh32a = Instance.new("CylinderMesh")
msh32a.Parent = prt32a
msh32a.Scale = Vector3.new(1,1.6,1)
local msh33 = Instance.new("BlockMesh")
msh33.Parent = prt33
msh33.Scale = Vector3.new(1.1,1.1,1.1)
local msh34 = Instance.new("BlockMesh")
msh34.Parent = prt34
msh34.Scale = Vector3.new(1.4,1.1,1.4)
local msh35 = Instance.new("SpecialMesh")
msh35.MeshType = "Wedge"
msh35.Parent = prt35
msh35.Scale = Vector3.new(1.4,1.3,1.4)
local msh36 = Instance.new("CylinderMesh")
msh36.Parent = prt36
msh36.Scale = Vector3.new(1.3,1.2,1.3)
local msh37 = Instance.new("SpecialMesh")
msh37.MeshType = "Sphere"
msh37.Parent = prt37
msh37.Scale = Vector3.new(0.8,0.8,0.8)
local msh38 = Instance.new("BlockMesh")
msh38.Parent = prt38
msh38.Scale = Vector3.new(1.5,0.7,1.5)
local msh39 = Instance.new("CylinderMesh")
msh39.Parent = prt39
msh39.Scale = Vector3.new(0.7,1.3,0.7)
local msh40 = Instance.new("BlockMesh")
msh40.Parent = prt40
msh40.Scale = Vector3.new(0.5,0.5,0.5)
local wld1 = Instance.new("Weld")
wld1.Parent = prt1
wld1.Part0 = prt1
wld1.Part1 = Torso
wld1.C0 = CFrame.fromEulerAnglesXYZ(0,0,-0.5) * CFrame.new(0.3,-1.55, -0.75)
local wld2 = Instance.new("Weld")
wld2.Parent = prt2
wld2.Part0 = prt2
wld2.Part1 = prt1
wld2.C0 = CFrame.fromEulerAnglesXYZ(0,0,0.5) * CFrame.new(0,1,0)
local wld3 = Instance.new("Weld")
wld3.Parent = prt3
wld3.Part0 = prt3
wld3.Part1 = prt2
wld3.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,1.7,0)
local wld4 = Instance.new("Weld")
wld4.Parent = prt4
wld4.Part0 = prt4
wld4.Part1 = prt3
wld4.C0 = CFrame.fromEulerAnglesXYZ(math.rad(180),math.rad(90),0) * CFrame.new(0.2,2,0)
local wld5 = Instance.new("Weld")
wld5.Parent = prt5
wld5.Part0 = prt5
wld5.Part1 = prt2
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.4,0.5,0)
local wld6 = Instance.new("Weld")
wld6.Parent = prt6
wld6.Part0 = prt6
wld6.Part1 = prt5
wld6.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.4,0,0)
local wld7 = Instance.new("Weld")
wld7.Parent = prt7
wld7.Part0 = prt7
wld7.Part1 = prt5
wld7.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,0,-0.3)
local wld8 = Instance.new("Weld")
wld8.Parent = prt8
wld8.Part0 = prt8
wld8.Part1 = prt5
wld8.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.2,0,-0.3)
local wld9 = Instance.new("Weld")
wld9.Parent = prt9
wld9.Part0 = prt9
wld9.Part1 = prt5
wld9.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.4,0,0)
local wld10 = Instance.new("Weld")
wld10.Parent = prt10
wld10.Part0 = prt10
wld10.Part1 = prt5
wld10.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.2,0,0.3)
local wld11 = Instance.new("Weld")
wld11.Parent = prt11
wld11.Part0 = prt11
wld11.Part1 = prt5
wld11.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,0,0.3)
local wld12 = Instance.new("Weld")
wld12.Parent = prt12
wld12.Part0 = prt12
wld12.Part1 = prt3
wld12.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld13 = Instance.new("Weld")
wld13.Parent = prt13
wld13.Part0 = prt13
wld13.Part1 = prt12
wld13.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,1.3,0)
local wld13a = Instance.new("Weld")
wld13a.Parent = prt13a
wld13a.Part0 = prt13a
wld13a.Part1 = prt13
wld13a.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld14 = Instance.new("Weld")
wld14.Parent = prt14
wld14.Part0 = prt14
wld14.Part1 = prt2
wld14.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.5,-0.4,0)
local wld15 = Instance.new("Weld")
wld15.Parent = prt15
wld15.Part0 = prt15
wld15.Part1 = prt14
wld15.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.rad(120)) * CFrame.new(0,0,0)
local wld16 = Instance.new("Weld")
wld16.Parent = prt16
wld16.Part0 = prt16
wld16.Part1 = Torso
wld16.C0 = CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0) * CFrame.new(0,-0.2,-0.2)
local wld17 = Instance.new("Weld")
wld17.Parent = prt17
wld17.Part0 = prt17
wld17.Part1 = prt16
wld17.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0.45,0)
local wld18 = Instance.new("Weld")
wld18.Parent = prt18
wld18.Part0 = prt18
wld18.Part1 = prt16
wld18.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,-1,0)
local wld19 = Instance.new("Weld")
wld19.Parent = prt19
wld19.Part0 = prt19
wld19.Part1 = prt18
wld19.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,-0.4,-0.45)
local wld20 = Instance.new("Weld")
wld20.Parent = prt20
wld20.Part0 = prt20
wld20.Part1 = prt19
wld20.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0.5)
local wld21 = Instance.new("Weld")
wld21.Parent = prt21
wld21.Part0 = prt21
wld21.Part1 = prt19
wld21.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,1.1,0.25)
local wld22 = Instance.new("Weld")
wld22.Parent = prt22
wld22.Part0 = prt22
wld22.Part1 = prt18
wld22.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,-0.4,1.1)
local wld23 = Instance.new("Weld")
wld23.Parent = prt23
wld23.Part0 = prt23
wld23.Part1 = prt22
wld23.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,-1.3,0)
local wld24 = Instance.new("Weld")
wld24.Parent = prt24
wld24.Part0 = prt24
wld24.Part1 = prt23
wld24.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld25 = Instance.new("Weld")
wld25.Parent = prt25
wld25.Part0 = prt25
wld25.Part1 = prt18
wld25.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,0.3,1.1)
local wld26 = Instance.new("Weld")
wld26.Parent = prt26
wld26.Part0 = prt26
wld26.Part1 = prt25
wld26.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,-1,0)
local wld27 = Instance.new("Weld")
wld27.Parent = prt27
wld27.Part0 = prt27
wld27.Part1 = prt26
wld27.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld28 = Instance.new("Weld")
wld28.Parent = prt28
wld28.Part0 = prt28
wld28.Part1 = prt25
wld28.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld29 = Instance.new("Weld")
wld29.Parent = prt29
wld29.Part0 = prt29
wld29.Part1 = prt21
wld29.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0.8)
local wld30 = Instance.new("Weld")
wld30.Parent = prt30
wld30.Part0 = prt30
wld30.Part1 = prt29
wld30.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,0,-0.2)
local wld31 = Instance.new("Weld")
wld31.Parent = prt31
wld31.Part0 = prt31
wld31.Part1 = prt18
wld31.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0,-0.4,0.5)
local wld32 = Instance.new("Weld")
wld32.Parent = prt32
wld32.Part0 = prt32
wld32.Part1 = RightArm
wld32.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.rad(90)) * CFrame.new(0,1.2,0)
local wld32a = Instance.new("Weld")
wld32a.Parent = prt32a
wld32a.Part0 = prt32a
wld32a.Part1 = prt32
wld32a.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld33 = Instance.new("Weld")
wld33.Parent = prt33
wld33.Part0 = prt33
wld33.Part1 = RightArm
wld33.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.rad(90)) * CFrame.new(0,0.6,0)
local wld34 = Instance.new("Weld")
wld34.Parent = prt34
wld34.Part0 = prt34
wld34.Part1 = prt32
wld34.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.rad(90)) * CFrame.new(-1,0,0)
local wld35 = Instance.new("Weld")
wld35.Parent = prt35
wld35.Part0 = prt35
wld35.Part1 = prt34
wld35.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,-2,0)
local wld36 = Instance.new("Weld")
wld36.Parent = prt36
wld36.Part0 = prt36
wld36.Part1 = prt35
wld36.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0,0)
local wld37 = Instance.new("Weld")
wld37.Parent = prt37
wld37.Part0 = prt37
wld37.Part1 = prt36
wld37.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,-0.8,0)
local wld38 = Instance.new("Weld")
wld38.Parent = prt38
wld38.Part0 = prt38
wld38.Part1 = prt34
wld38.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,0.1,0)
local wld39 = Instance.new("Weld")
wld39.Parent = prt39
wld39.Part0 = prt39
wld39.Part1 = prt38
wld39.C0 = CFrame.fromEulerAnglesXYZ(0,0,math.rad(90)) * CFrame.new(0,0,-0.4)
local wld40 = Instance.new("Weld")
wld40.Parent = prt40
wld40.Part0 = prt40
wld40.Part1 = LeftLeg
wld40.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0,1,0)
if (script.Parent.className ~= "HopperBin") then
Tool = Instance.new("HopperBin")
Tool.Parent = Backpack
Tool.Name = "AccountMoniter's GunBlade" --Yes. MY, GunBlade.
Tool.TextureId = "" --Haven't made a picture for it yet. I soon will when i'm done with every weapon :3
script.Parent = Tool
end
Bin = script.Parent
--[[Main Functions]]--
function unequipweld()
wld1.Part1 = Torso
wld1.C0 = CFrame.fromEulerAnglesXYZ(0,0,-0.5) * CFrame.new(0.3,-1.55, -0.75)
end
function unequipweld2()
wld16.Part1 = Torso
wld16.C0 = CFrame.fromEulerAnglesXYZ(math.rad(-90),0,0) * CFrame.new(0,-0.2,-0.2)
end
function equipweld()
wld1.Part1 = LeftArm
wld1.C1 = CFrame.fromEulerAnglesXYZ(0, 0, 0) * CFrame.new(0, 0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.7, -1.57) * CFrame.new(0, 1, 0)
end
function equipweld2()
wld16.Part1 = LeftArm
wld16.C1 = CFrame.fromEulerAnglesXYZ(0, 0, 0) * CFrame.new(0, 0,0)
wld16.C0 = CFrame.fromEulerAnglesXYZ(math.rad(90),0,0) * CFrame.new(0, 1, 0)
end
function hideanim()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(3.5*i,0,1*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
--wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), math.rad(720)*i, -1.57) * CFrame.new(0, 1, 0)
end
unequipweld()
wait(0.2)
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-3.5*i+3.5,0,-1*i+1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function equipanim()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(3.5*i,0,1*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
equipweld()
wait(0.1)
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-3.5*i+3.5,0,-1*i+1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wait(0.3)
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(1*i,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function oneslash()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(2*i+1,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.7*i-0.7, -1.57) * CFrame.new(0, 1, 0)
end
ss(prt1,1)
local con = prt3.Touched:connect(OT)
local con2 = prt4.Touched:connect(OT)
for i = 0 , 1 , 0.1 do
wait(0)
effect()
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-3.5*i+3,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -1*i, -1.57) * CFrame.new(0, 1, 0)
end
con:disconnect()
con2:disconnect()
end
function twoslash()
ss(prt1,1)
local con = prt3.Touched:connect(OT)
local con2 = prt4.Touched:connect(OT)
for i = 0 , 1 , 0.1 do
wait(0)
effect()
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(3*i-0.5,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 2*i-1, -1.57) * CFrame.new(0, 1, 0)
end
con:disconnect()
con2:disconnect()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-1.5*i+2.5,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -1.7*i+1, -1.57) * CFrame.new(0, 1, 0)
end
end
function unload() --Possibly the hardest attack made for the GunBlade >.<
for i = 0 , 1 , 0.15 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.4*i,0.5*i,-0.5*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
local bullet1 = Instance.new("Part")
bullet1.formFactor = 1
bullet1.Parent = model1
bullet1.CanCollide = false
bullet1.BrickColor = BrickColor.new("New Yeller")
bullet1.Name = "Bullet1"
bullet1.Size = Vector3.new(1,1,1)
bullet1.Position = Torso.Position
local bullet2 = Instance.new("Part")
bullet2.formFactor = 1
bullet2.Parent = model1
bullet2.CanCollide = false
bullet2.BrickColor = BrickColor.new("New Yeller")
bullet2.Name = "Bullet2"
bullet2.Size = Vector3.new(1,1,1)
bullet2.Position = Torso.Position
local bullet3 = Instance.new("Part")
bullet3.formFactor = 1
bullet3.Parent = model1
bullet3.CanCollide = false
bullet3.BrickColor = BrickColor.new("New Yeller")
bullet3.Name = "Bullet3"
bullet3.Size = Vector3.new(1,1,1)
bullet3.Position = Torso.Position
local bullet4 = Instance.new("Part")
bullet4.formFactor = 1
bullet4.Parent = model1
bullet4.CanCollide = false
bullet4.BrickColor = BrickColor.new("New Yeller")
bullet4.Name = "Bullet4"
bullet4.Size = Vector3.new(1,1,1)
bullet4.Position = Torso.Position
local bullet5 = Instance.new("Part")
bullet5.formFactor = 1
bullet5.Parent = model1
bullet5.CanCollide = false
bullet5.BrickColor = BrickColor.new("New Yeller")
bullet5.Name = "Bullet5"
bullet5.Size = Vector3.new(1,1,1)
bullet5.Position = Torso.Position
local bullet6 = Instance.new("Part")
bullet6.formFactor = 1
bullet6.Parent = model1
bullet6.CanCollide = false
bullet6.BrickColor = BrickColor.new("New Yeller")
bullet6.Name = "Bullet6"
bullet6.Size = Vector3.new(1,1,1)
bullet6.Position = Torso.Position
local bulmesh1 = Instance.new("CylinderMesh")
bulmesh1.Parent = bullet1
bulmesh1.Scale = Vector3.new(1.1,1.1,0.3)
local bulmesh2 = Instance.new("CylinderMesh")
bulmesh2.Parent = bullet2
bulmesh2.Scale = Vector3.new(1.1,1.1,0.3)
local bulmesh3 = Instance.new("CylinderMesh")
bulmesh3.Parent = bullet3
bulmesh3.Scale = Vector3.new(1.1,1.1,0.3)
local bulmesh4 = Instance.new("CylinderMesh")
bulmesh4.Parent = bullet4
bulmesh4.Scale = Vector3.new(1.1,1.1,0.3)
local bulmesh5 = Instance.new("CylinderMesh")
bulmesh5.Parent = bullet5
bulmesh5.Scale = Vector3.new(1.1,1.1,0.3)
local bulmesh6 = Instance.new("CylinderMesh")
bulmesh6.Parent = bullet6
bulmesh6.Scale = Vector3.new(1.1,1.1,0.3)
local bulweld1 = Instance.new("Weld")
bulweld1.Parent = bullet1
bulweld1.Part0 = bullet1
bulweld1.Part1 = RightArm
bulweld1.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,1,0.3)
local bulweld2 = Instance.new("Weld")
bulweld2.Parent = bullet2
bulweld2.Part0 = bullet2
bulweld2.Part1 = RightArm
bulweld2.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,1,0)
local bulweld3 = Instance.new("Weld")
bulweld3.Parent = bullet3
bulweld3.Part0 = bullet3
bulweld3.Part1 = RightArm
bulweld3.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,1,-0.3)
local bulweld4 = Instance.new("Weld")
bulweld4.Parent = bullet4
bulweld4.Part0 = bullet4
bulweld4.Part1 = RightArm
bulweld4.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.2,1,0.3)
local bulweld5 = Instance.new("Weld")
bulweld5.Parent = bullet5
bulweld5.Part0 = bullet5
bulweld5.Part1 = RightArm
bulweld5.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.2,1,0)
local bulweld6 = Instance.new("Weld")
bulweld6.Parent = bullet6
bulweld6.Part0 = bullet6
bulweld6.Part1 = RightArm
bulweld6.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(-0.2,1,-0.3)
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.1*i+1,1*i,0.7*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.7*i+1.5,0.5,-0.7*i) * CFrame.fromEulerAnglesXYZ(2*i-0.4,-0.5*i+0.5,-0.5*i-0.5)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet1.Parent = nil
prt6.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet2.Parent = nil
prt7.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet3.Parent = nil
prt8.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet4.Parent = nil
prt9.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet5.Parent = nil
prt10.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet6.Parent = nil
prt11.BrickColor = BrickColor.new("New Yeller")
reloadsound(prt1,1)
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.1*i-0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.47*i+0.1+1,-1*i+1,-0.7*i+0.7)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.8*i+0.8,0.5,-0.3*i-0.7) * CFrame.fromEulerAnglesXYZ(0.3*i+1.6,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt9.BrickColor = BrickColor.new("Black")
shootsound(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt10.BrickColor = BrickColor.new("Black")
shootsound(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i+1,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt11.BrickColor = BrickColor.new("Black")
shootsound(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i+2,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt6.BrickColor = BrickColor.new("Black")
shootsound(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i+3,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt7.BrickColor = BrickColor.new("Black")
shootsound(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i+4,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bulletshoot()
boomeffect()
prt8.BrickColor = BrickColor.new("Black")
shootsound2(prt1,1.2)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i+5,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i+0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.57*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5*i,0.5,1*i-1) * CFrame.fromEulerAnglesXYZ(-1.9*i+1.9,0,1*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function sniper()
for i = 0 , 1 , 0.15 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.4*i,0.5*i,-0.5*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
local bullet1 = Instance.new("Part")
bullet1.formFactor = 1
bullet1.Parent = model1
bullet1.Reflectance = 0.2
bullet1.CanCollide = false
bullet1.BrickColor = BrickColor.new("New Yeller")
bullet1.Name = "Bullet1"
bullet1.Size = Vector3.new(1,1,1)
bullet1.Position = Torso.Position
local bulmesh1 = Instance.new("CylinderMesh")
bulmesh1.Parent = bullet1
bulmesh1.Scale = Vector3.new(1.1,1.1,0.3)
local bulweld1 = Instance.new("Weld")
bulweld1.Parent = bullet1
bulweld1.Part0 = bullet1
bulweld1.Part1 = RightArm
bulweld1.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,1,0.3)
sparkles1 = Instance.new("Sparkles")
sparkles1.Name = "Sparkles1"
sparkles1.Color = Color3.new(1,1,0)
sparkles1.Parent = bullet1
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.1*i+1,1*i,0.7*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.7*i+1.5,0.5,-0.7*i) * CFrame.fromEulerAnglesXYZ(2*i-0.4,-0.5*i+0.5,-0.5*i-0.5)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet1.Parent = nil
prt9.BrickColor = BrickColor.new("New Yeller")
prt9.Reflectance = 0.2
sparkles1.Parent = prt9
snipersound(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.07 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.1*i-0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.47*i+0.1+1,-1*i+1,-0.7*i+0.7)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.8*i+0.8,0.5,-0.3*i-0.7) * CFrame.fromEulerAnglesXYZ(0.3*i+1.6,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
local lazor = Instance.new("Part")
lazor.formFactor = 1
lazor.Parent = workspace
lazor.Transparency = 0.5
lazor.CanCollide = false
lazor.BrickColor = BrickColor.new("Bright red")
lazor.Name = "Lazorz"
lazor.Size = Vector3.new(1,1,1)
lazor.Position = Torso.Position
local lazmsh = Instance.new("CylinderMesh")
lazmsh.Parent = lazor
lazmsh.Scale = Vector3.new(1.1,1340,0.3)
coroutine.resume(coroutine.create(function()
while lazor.Parent ~= nil do
wait()
lazor.CFrame = prt13.CFrame * CFrame.new(0,-800,0)
end
end))
wait(0.5)
for i = 0 , 1 , 0.07 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.05*i+0.1-0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
end
wait(0.2)
sniperbulletshoot()
boomeffect()
prt9.BrickColor = BrickColor.new("Black")
prt9.Reflectance = 0
sparkles1.Parent = nil
lazor.Parent = nil
snipersound2(prt1,1)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i+0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.57*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5*i,0.5,1*i-1) * CFrame.fromEulerAnglesXYZ(-1.9*i+1.9,0,1*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function kerbewmshot()
for i = 0 , 1 , 0.15 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.4*i,0.5*i,-0.5*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
local bullet1 = Instance.new("Part")
bullet1.formFactor = 1
bullet1.Parent = model1
bullet1.CanCollide = false
bullet1.BrickColor = BrickColor.new("Bright red")
bullet1.Name = "Bullet1"
bullet1.Size = Vector3.new(1,1,1)
bullet1.Position = Torso.Position
local bulmesh1 = Instance.new("CylinderMesh")
bulmesh1.Parent = bullet1
bulmesh1.Scale = Vector3.new(1.1,1.1,0.3)
local bulweld1 = Instance.new("Weld")
bulweld1.Parent = bullet1
bulweld1.Part0 = bullet1
bulweld1.Part1 = RightArm
bulweld1.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.2,1,0.3)
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.1*i+1,1*i,0.7*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.7*i+1.5,0.5,-0.7*i) * CFrame.fromEulerAnglesXYZ(2*i-0.4,-0.5*i+0.5,-0.5*i-0.5)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
bullet1.Parent = nil
prt9.BrickColor = BrickColor.new("Bright red")
rocketreload(prt1,1)
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(-0.6*i+1.6,0,0.3*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.3 do
wait(0)
RW.C0 = CFrame.new(0.8,0.5,-0.7) * CFrame.fromEulerAnglesXYZ(0.6*i-0.6+1.6,0,-0.3*i+0.3-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.07 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.1*i-0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.47*i+0.1+1,-1*i+1,-0.7*i+0.7)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.8*i+0.8,0.5,-0.3*i-0.7) * CFrame.fromEulerAnglesXYZ(0.3*i+1.6,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wait(0.5)
bewmshot()
boomeffect()
prt9.BrickColor = BrickColor.new("Black")
rocketshoot(prt1,1)
for i = 0 , 1 , 0.2 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.5*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(0.5*i+1.9,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.2 do
wait(0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,1*i,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.07,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-0.5*i+2.4,0,-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.1 do
wait(0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -0.5*i+0.5-0.7, -1.57) * CFrame.new(0, 1, 0)
wld5.C0 = CFrame.fromEulerAnglesXYZ(0,0,0) * CFrame.new(0.4,0.5,0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.57*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5*i,0.5,1*i-1) * CFrame.fromEulerAnglesXYZ(-1.9*i+1.9,0,1*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function crush()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(0.5*i-1.5,0.5,-0.5*i) * CFrame.fromEulerAnglesXYZ(0.5*i+1,0,0.7*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-0.5*i+1.5,0.5,-0.5*i) * CFrame.fromEulerAnglesXYZ(1.5*i,0,-0.7*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 1.2*i-0.7, -1.57) * CFrame.new(0, 1, 0)
end
for i = 0 , 1 , 0.1 do
wait(0)
prt1.Reflectance = prt1.Reflectance + 0.1
prt2.Reflectance = prt2.Reflectance + 0.1
prt3.Reflectance = prt3.Reflectance + 0.1
prt4.Reflectance = prt4.Reflectance + 0.1
prt5.Reflectance = prt5.Reflectance + 0.1
prt6.Reflectance = prt6.Reflectance + 0.1
prt7.Reflectance = prt7.Reflectance + 0.1
prt8.Reflectance = prt8.Reflectance + 0.1
prt9.Reflectance = prt9.Reflectance + 0.1
prt10.Reflectance = prt10.Reflectance + 0.1
prt11.Reflectance = prt11.Reflectance + 0.1
prt12.Reflectance = prt12.Reflectance + 0.1
prt13.Reflectance = prt13.Reflectance + 0.1
prt13a.Reflectance = prt13a.Reflectance + 0.1
prt14.Reflectance = prt14.Reflectance + 0.1
prt15.Reflectance = prt15.Reflectance + 0.1
end
wait(0.3)
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-0.5*i-1,0.5,0.5*i-0.5) * CFrame.fromEulerAnglesXYZ(1*i+1.5,0,-0.7*i+0.7)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0.5*i+1,0.5,0.5*i-0.5) * CFrame.fromEulerAnglesXYZ(-0.5*i+1.5,0,0.7*i-0.7)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.5, -1.57) * CFrame.new(0, 1, 0)
end
local con = prt3.Touched:connect(fixOT)
local con2 = prt4.Touched:connect(fixOT)
crushsounds(prt1)
for i = 0 , 1 , 0.2 do
wait(0)
effect()
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-1.8*i+2.5,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-2*i+1,0,0)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), -1.5*i+0.5, -1.57) * CFrame.new(0, 1, 0)
end
con:disconnect()
con2:disconnect()
wait(0.3)
for i = 0 , 1 , 0.1 do
wait(0)
prt1.Reflectance = prt1.Reflectance - 0.1
prt2.Reflectance = prt2.Reflectance - 0.1
prt3.Reflectance = prt3.Reflectance - 0.1
prt4.Reflectance = prt4.Reflectance - 0.1
prt5.Reflectance = prt5.Reflectance - 0.1
prt6.Reflectance = prt6.Reflectance - 0.1
prt7.Reflectance = prt7.Reflectance - 0.1
prt8.Reflectance = prt8.Reflectance - 0.1
prt9.Reflectance = prt9.Reflectance - 0.1
prt10.Reflectance = prt10.Reflectance - 0.1
prt11.Reflectance = prt11.Reflectance - 0.1
prt12.Reflectance = prt12.Reflectance - 0.1
prt13.Reflectance = prt13.Reflectance - 0.1
prt13a.Reflectance = prt13a.Reflectance - 0.1
prt14.Reflectance = prt14.Reflectance - 0.1
prt15.Reflectance = prt15.Reflectance - 0.1
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(0.3*i+0.7,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(1*i-1,0,0)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
wld1.C0 = CFrame.fromEulerAnglesXYZ(-math.rad(90), 0.3*i-1, -1.57) * CFrame.new(0, 1, 0)
end
end
function elecshoot()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(3.5*i,0,1*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
unequipweld()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(1*i+3.5,0,0.1*i+1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
model2.Parent = modelzorz
wld16.Parent = prt16
wld17.Parent = prt17
wld18.Parent = prt18
wld19.Parent = prt19
wld20.Parent = prt20
wld21.Parent = prt21
wld22.Parent = prt22
wld23.Parent = prt23
wld24.Parent = prt24
wld25.Parent = prt25
wld26.Parent = prt26
wld27.Parent = prt27
wld28.Parent = prt28
wld29.Parent = prt29
wld30.Parent = prt30
wld31.Parent = prt31
local c = model2:children()
for i=1,#c do
c[i].Transparency = 1
end
coroutine.resume(coroutine.create(function()
local c = model2:children()
for i = 0,1,0.1 do
wait()
prt16.Transparency = prt16.Transparency - 0.1
prt17.Transparency = prt17.Transparency - 0.1
prt18.Transparency = prt18.Transparency - 0.1
prt19.Transparency = prt19.Transparency - 0.1
prt20.Transparency = prt20.Transparency - 0.1
prt21.Transparency = prt21.Transparency - 0.1
prt22.Transparency = prt22.Transparency - 0.1
prt23.Transparency = prt23.Transparency - 0.1
prt24.Transparency = prt24.Transparency - 0.1
prt25.Transparency = prt25.Transparency - 0.1
prt26.Transparency = prt26.Transparency - 0.1
prt27.Transparency = prt27.Transparency - 0.1
prt28.Transparency = prt28.Transparency - 0.1
prt29.Transparency = prt29.Transparency - 0.1
prt30.Transparency = prt30.Transparency - 0.1
prt31.Transparency = prt31.Transparency - 0.1
end
end))
prt30.BrickColor = BrickColor.new("Bright blue")
equipweld2()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-2.93*i+4.5,0,-1.1*i+1.1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(-1.5*i+1.5,0.5,-1*i) * CFrame.fromEulerAnglesXYZ(1*i,0,-2*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wait(0.3)
boomeffect2()
cannonsound(prt24,0.7)
elecshot()
for i = 0 , 1 , 0.15 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(1*i+1.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(2*i+1,0,1*i-2)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
for i = 0 , 1 , 0.15 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-1*i+2.57,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(0,0.5,-1) * CFrame.fromEulerAnglesXYZ(-2*i+3,0,-1*i-1)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wait(0.5)
coroutine.resume(coroutine.create(function()
for i = 0,1,0.1 do
wait()
prt16.Transparency = prt16.Transparency + 0.1
prt17.Transparency = prt17.Transparency + 0.1
prt18.Transparency = prt18.Transparency + 0.1
prt19.Transparency = prt19.Transparency + 0.1
prt20.Transparency = prt20.Transparency + 0.1
prt21.Transparency = prt21.Transparency + 0.1
prt22.Transparency = prt22.Transparency + 0.1
prt23.Transparency = prt23.Transparency + 0.1
prt24.Transparency = prt24.Transparency + 0.1
prt25.Transparency = prt25.Transparency + 0.1
prt26.Transparency = prt26.Transparency + 0.1
prt27.Transparency = prt27.Transparency + 0.1
prt28.Transparency = prt28.Transparency + 0.1
prt29.Transparency = prt29.Transparency + 0.1
prt30.Transparency = prt30.Transparency + 0.1
prt31.Transparency = prt31.Transparency + 0.1
end
end))
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(2.93*i+1.57,0,1.1*i)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5*i,0.5,1*i-1) * CFrame.fromEulerAnglesXYZ(-1*i+1,0,2*i-2)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
model2.Parent = nil
unequipweld2()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-1*i+4.5,0,-0.1*i+1.1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
equipweld()
for i = 0 , 1 , 0.07 do
wait(0)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-2.5*i+3.5,0,-1*i+1)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function laz0rshoot() --TROLOLOL
for i = 0 , 1 , 0.07 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(math.rad(180)*i,0,0)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wld32a.Parent = prt32a
wld33.Parent = prt33
wld34.Parent = prt34
wld35.Parent = prt35
wld36.Parent = prt36
wld37.Parent = prt37
wld38.Parent = prt38
wld39.Parent = prt39
model3.Parent = modelzorz
local c = model3:children()
for i=1,#c do
c[i].Transparency = 1
end
for i=1,#c do
for q = 0,1,0.2 do
wait()
c[i].Transparency = c[i].Transparency - 0.2
end
end
for i = 0 , 1 , 0.07 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-math.rad(90)*i+math.rad(180),0,0)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
laz0rshot()
wait(0.5)
coroutine.resume(coroutine.create(function()
local c = model3:children()
for i=1,#c do
wait()
coroutine.resume(coroutine.create(function()
for q = 0,1,0.2 do
wait()
c[i].Transparency = c[i].Transparency + 0.2
end
end))
end
model3.Parent = nil
end))
for i = 0 , 1 , 0.07 do
wait(0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-math.rad(90)*i+math.rad(90),0,0)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
end
function tornadoskates()
model4.Parent = modelzorz
wld40.Parent = prt40
prt40.Transparency = 1
for i = 0 , 0.4 , 0.1 do
wait(0)
prt40.Transparency = prt40.Transparency - 0.1
end
end
function OT(hit)
if hit.Parent == nil then return end
local hum = hit.Parent:findFirstChild("Humanoid")
if hum ~= nil and hum ~= Character.Humanoid then
hum:TakeDamage(damage)
end
end
function fixOT(hit)
if hit.Parent == nil then return end
local hum = hit.Parent:findFirstChild("Humanoid")
if hum ~= nil and hum ~= Character.Humanoid then
hum:TakeDamage(damage)
hum.WalkSpeed = 16
hum.MaxHealth = 100
c = hum.Parent:GetChildren()
for i = 1,#c do
if c[i].className == "Part" then
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://www.roblox.com/asset/?id=2974000"
SlashSound.Parent = prt1
SlashSound.Volume = 0.1
SlashSound.Pitch = 1.1
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
c[i].Transparency = 0
c[i].Reflectance = 0
end
if c[i].className == "ForceField" then
c[i]:Remove()
end
end
end
end
function ss(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "rbxasset://sounds\\swordslash.wav"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
end
function sss(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://www.roblox.com/asset/?id=2248511"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
end
function uss(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "rbxasset://sounds\\unsheath.wav"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
end
function reloadsound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209834"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
end
function shootsound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209803"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(0.3)
SlashSound:Stop()
wait(1)
SlashSound.Parent = nil
end))
end
function shootsound2(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209803"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(1)
SlashSound.Parent = nil
end))
end
function snipersound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209881"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function snipersound2(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209875"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function rocketreload(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209813"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function rocketshoot(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209821"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function rocketbewmsound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209236"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function crushsounds(parent)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209268"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = 1
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209588"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = 1
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209596"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = 0.7
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function cannonsound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://roblox.com/asset/?id=10209257"
SlashSound.Parent = parent
SlashSound.Volume = .7
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function elecsound(parent,pitch)
local SlashSound = Instance.new("Sound")
SlashSound.SoundId = "http://www.roblox.com/asset/?id=2800815"
SlashSound.Parent = parent
SlashSound.Volume = 1
SlashSound.Pitch = pitch
SlashSound:play()
coroutine.resume(coroutine.create(function()
wait(3)
SlashSound.Parent = nil
end))
end
function effect()
local clone = prt3:clone()
clone.Parent = workspace
clone.Anchored = true
clone.Transparency = 0.5
clone.Reflectance = 0
clone.Mesh.Scale = clone.Mesh.Scale + Vector3.new(0.1,0.1,0.1)
clone.BrickColor = BrickColor.new("White")
coroutine.resume(coroutine.create(function()
wait(0.25)
clone.Parent = nil
end))
local cloneb = prt4:clone()
cloneb.Parent = workspace
cloneb.Anchored = true
cloneb.Transparency = 0.5
cloneb.Reflectance = 0
cloneb.Mesh.Scale = cloneb.Mesh.Scale + Vector3.new(0.1,0.1,0.1)
cloneb.BrickColor = BrickColor.new("White")
coroutine.resume(coroutine.create(function()
wait(0.25)
cloneb.Parent = nil
end))
end
DBHit=function(hit,DB) --credits to turdulator for making this function :D
if hit.Parent==nil then
return
end
h=hit.Parent:FindFirstChild("Humanoid")
t=hit.Parent:FindFirstChild("Torso")
if h~=nil and t~=nil then
if h.Parent==Character then
return
end
h:TakeDamage(5)
vl=Instance.new("BodyVelocity")
vl.P=4500
vl.maxForce=Vector3.new(math.huge,math.huge,math.huge)
velocity=Vector3.new(Torso.Velocity.x,0,Torso.Velocity.z)
vl.velocity=velocity*1.05+Vector3.new(0,3,0)
vl.Parent=t
game:GetService("Debris"):AddItem(vl,.2)
rl=Instance.new("BodyAngularVelocity")
rl.P=3000
rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000
rl.angularvelocity=Vector3.new(math.random(-20,20),math.random(-20,20),math.random(-20,20))
rl.Parent=t
game:GetService("Debris"):AddItem(rl,.2)
else
if hit.CanCollide==false then
return
end
MagicCom:disconnect()
-- DBExplode(DB)
end
end
function boomeffect()
local mesh = Instance.new("SpecialMesh")
mesh.MeshType = "Sphere"
mesh.Scale = Vector3.new(0.2,0,0.2)
local shell = Instance.new("Part")
mesh.Parent = shell
shell.Anchored = true
shell.formFactor = 1
shell.Size = Vector3.new(2,2,2)
shell.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(math.rad(90),0,math.random(-50,50))
shell.Parent = game.workspace
shell.Transparency = 0
shell.BrickColor = BrickColor.new("Bright yellow")
shell.CanCollide = false
coroutine.resume(coroutine.create(function()
for i = 0 , 1 , 0.2 do
wait(0.1)
mesh.Scale = mesh.Scale + Vector3.new(0,0.3,0)
shell.Transparency = shell.Transparency + 0.2
end
shell.Transparency = 1
shell.Parent = nil
end))
local mesh2 = Instance.new("SpecialMesh")
mesh2.MeshType = "Sphere"
mesh2.Scale = Vector3.new(0.2,0,0.2)
local shell2 = Instance.new("Part")
mesh2.Parent = shell2
shell2.Anchored = true
shell2.formFactor = 1
shell2.Size = Vector3.new(2,2,2)
shell2.CFrame = shell.CFrame * CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(0,0,math.rad(90))
shell2.Parent = game.workspace
shell2.Transparency = 0
shell2.BrickColor = BrickColor.new("Bright yellow")
shell2.CanCollide = false
coroutine.resume(coroutine.create(function()
for i = 0 , 1 , 0.2 do
wait(0.1)
mesh2.Scale = mesh2.Scale + Vector3.new(0,0.3,0)
shell2.Transparency = shell2.Transparency + 0.2
end
shell2.Transparency = 1
shell2.Parent = nil
end))
local mesh3 = Instance.new("SpecialMesh")
mesh3.MeshType = "Sphere"
mesh3.Scale = Vector3.new(0.2,0,0.2)
local shell3 = Instance.new("Part")
mesh3.Parent = shell3
shell3.Anchored = true
shell3.formFactor = 1
shell3.Size = Vector3.new(2,2,2)
shell3.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0)
shell3.Parent = game.workspace
shell3.Transparency = 0
shell3.BrickColor = BrickColor.new("Bright yellow")
shell3.CanCollide = false
coroutine.resume(coroutine.create(function()
for i = 0 , 1 , 0.2 do
wait(0.1)
mesh3.Scale = mesh3.Scale + Vector3.new(0,0.3,0)
shell3.Transparency = shell3.Transparency + 0.2
end
shell3.Transparency = 1
shell3.Parent = nil
end))
end
function boomeffect2()
local mesh = Instance.new("SpecialMesh")
mesh.Scale = Vector3.new(0.2,0,0.2)
mesh.MeshId = "http://www.roblox.com/asset/?id=1323306"
local shell = Instance.new("Part")
mesh.Parent = shell
shell.Anchored = true
shell.formFactor = 1
shell.Size = Vector3.new(2,2,2)
shell.CFrame = prt23.CFrame * CFrame.new(0,0.35,0)
shell.Parent = game.workspace
shell.Transparency = 0
shell.BrickColor = BrickColor.new("Bright blue")
shell.CanCollide = false
coroutine.resume(coroutine.create(function()
for i = 0 , 1 , 0.2 do
wait(0.1)
mesh.Scale = mesh.Scale + Vector3.new(0.3,0.5,0.3)
shell.CFrame = shell.CFrame * CFrame.new(0,0.3,0)
shell.Transparency = shell.Transparency + 0.2
end
shell.Transparency = 1
shell.Parent = nil
end))
end
DBHit1=function(hit,DB) --credits to turdulator for making this function :D
if hit.Parent==nil then
return
end
h=hit.Parent:FindFirstChild("Humanoid")
t=hit.Parent:FindFirstChild("Torso")
if h~=nil and t~=nil then
if h.Parent==Character then
return
end
h:TakeDamage(5)
vl=Instance.new("BodyVelocity")
vl.P=4500
vl.maxForce=Vector3.new(math.huge,math.huge,math.huge)
velocity=Vector3.new(Torso.Velocity.x,0,Torso.Velocity.z)
vl.velocity=velocity*1.05+Vector3.new(0,3,0)
vl.Parent=t
game:GetService("Debris"):AddItem(vl,.2)
rl=Instance.new("BodyAngularVelocity")
rl.P=3000
rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000
rl.angularvelocity=Vector3.new(math.random(-20,20),math.random(-20,20),math.random(-20,20))
rl.Parent=t
game:GetService("Debris"):AddItem(rl,.2)
else
if hit.CanCollide==false then
return
end
MagicCom:disconnect()
-- DBExplode(DB)
end
end
function bulletshoot()
local freakingbullet = prt6:Clone()
freakingbullet.formFactor = 1
freakingbullet.Parent = workspace
freakingbullet.CanCollide = false
freakingbullet.BrickColor = BrickColor.new("New Yeller")
freakingbullet.Name = "Bullet6"
freakingbullet.Size = Vector3.new(1,1,1)
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
local freakingbulmsh = Instance.new("CylinderMesh")
freakingbulmsh.Parent = freakingbullet
freakingbulmsh.Scale = Vector3.new(1.1,0.8,0.3)
local force = Instance.new("BodyForce")
force.Parent = freakingbullet
force.force = Vector3.new(0,240,0)
coroutine.resume(coroutine.create(function()
while freakingbullet.Parent ~= nil do --I use this function instead of the touch function :3
wait()
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - freakingbullet.Position;
local mag = targ.magnitude;
if mag <= 4 and c[i].Name ~= Player.Name then
hum:TakeDamage(15)
v=Instance.new("BodyVelocity")
v.P=1000
v.maxForce=Vector3.new(math.huge,0,math.huge)
v.velocity=Torso.CFrame.lookVector*25+Torso.Velocity/1.05
v.Parent=hum.Parent.Torso
coroutine.resume(coroutine.create(function()
wait(0.3)
v.Parent = nil
end))
game:GetService("Debris"):AddItem(v,.1)
freakingbullet.Parent = nil
-- hum:TakeDamage(damage.Value + damageboost)
end
end
end
end
end
end))
--[[freakingbullet.Touched:connect(function(hit) kill(b,hit) end) --Freaking touched function wont work >:U
function kill(brick,hit)
if hit.Parent:FindFirstChild("Humanoid") ~= nil and hit.Parent.Name ~= "Dr4gOnh4ck3rz2" and hit.Name ~= "Base" and hit.Parent.Name ~= "AccountMoniter" then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 5
freakingbullet.Parent = nil
end
end]]
coroutine.resume(coroutine.create(function()
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
for i = 0,5,0.1 do
wait()
--freakingbullet.Touched:connect(function(hit) kill(b,hit) end)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
end
freakingbullet.Parent = nil
end))
end
function sniperbulletshoot()
local freakingbullet = prt6:Clone()
freakingbullet.formFactor = 1
freakingbullet.Reflectance = 0.2
freakingbullet.Parent = workspace
freakingbullet.CanCollide = false
freakingbullet.BrickColor = BrickColor.new("New Yeller")
freakingbullet.Name = "Bullet6"
freakingbullet.Size = Vector3.new(1,1,1)
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
local freakingbulmsh = Instance.new("CylinderMesh")
freakingbulmsh.Parent = freakingbullet
freakingbulmsh.Scale = Vector3.new(1.1,0.8,0.3)
local force = Instance.new("BodyForce")
force.Parent = freakingbullet
force.force = Vector3.new(0,240,0)
sparkles = Instance.new("Sparkles")
sparkles.Name = "Sparkles"
sparkles.Color = Color3.new(1,1,0)
sparkles.Parent = freakingbullet
coroutine.resume(coroutine.create(function()
while freakingbullet.Parent ~= nil do --I use this function instead of the touch function :3
wait()
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - freakingbullet.Position;
local mag = targ.magnitude;
if mag <= 4 and c[i].Name ~= Player.Name then
hum:TakeDamage(50)
freakingbullet.Parent = nil
-- hum:TakeDamage(damage.Value + damageboost)
end
end
end
end
end
end))
--[[freakingbullet.Touched:connect(function(hit) kill(b,hit) end) --Freaking touched function wont work >:U
function kill(brick,hit)
if hit.Parent:FindFirstChild("Humanoid") ~= nil and hit.Parent.Name ~= "Dr4gOnh4ck3rz2" and hit.Name ~= "Base" and hit.Parent.Name ~= "AccountMoniter" then
hit.Parent.Humanoid.Health = hit.Parent.Humanoid.Health - 5
freakingbullet.Parent = nil
end
end]]
coroutine.resume(coroutine.create(function()
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
for i = 0,10,0.1 do
wait()
--freakingbullet.Touched:connect(function(hit) kill(b,hit) end)
freakingbullet.Velocity = Torso.CFrame.lookVector * 250
end
freakingbullet.Parent = nil
end))
end
function bewmshot()
local freakingbullet = prt6:Clone()
freakingbullet.formFactor = 1
freakingbullet.Parent = workspace
freakingbullet.CanCollide = false
freakingbullet.BrickColor = BrickColor.new("Bright red")
freakingbullet.Name = "Bullet6"
freakingbullet.Size = Vector3.new(1,1,1)
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
local freakingbulmsh = Instance.new("CylinderMesh")
freakingbulmsh.Parent = freakingbullet
freakingbulmsh.Scale = Vector3.new(1.1,0.8,0.3)
local force = Instance.new("BodyForce")
force.Parent = freakingbullet
force.force = Vector3.new(0,240,0)
coroutine.resume(coroutine.create(function()
while freakingbullet.Parent ~= nil do --I use this function instead of the touch function :3
wait()
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - freakingbullet.Position;
local mag = targ.magnitude;
if mag <= 4 and c[i].Name ~= Player.Name then
hum:TakeDamage(20)
freakingbullet.Parent = nil
DBHit(hum.Parent.Torso,freakingbullet)
local bewm = Instance.new("Explosion")
bewm.Parent = workspace
bewm.BlastPressure = 0
bewm.Position = hum.Parent.Torso.Position
rocketbewmsound(prt1,1.2)
-- coroutine.resume(coroutine.create(function()
wait(0.5)
rocketbewmsound(prt1,1.2)
hum:TakeDamage(10)
DBHit(hum.Parent.Torso,freakingbullet)
local bewm = Instance.new("Explosion")
bewm.Parent = workspace
bewm.BlastPressure = 0
bewm.Position = hum.Parent.Torso.Position + Vector3.new(math.random(-5,5),math.random(-5,5),math.random(-5,5))
wait(0.5)
rocketbewmsound(prt1,1.2)
hum:TakeDamage(10)
DBHit(hum.Parent.Torso,freakingbullet)
local bewm = Instance.new("Explosion")
bewm.Parent = workspace
bewm.BlastPressure = 0
bewm.Position = hum.Parent.Torso.Position + Vector3.new(math.random(-5,5),math.random(-5,5),math.random(-5,5))
wait(0.5)
rocketbewmsound(prt1,1.2)
hum:TakeDamage(10)
DBHit(hum.Parent.Torso,freakingbullet)
local bewm = Instance.new("Explosion")
bewm.Parent = workspace
bewm.BlastPressure = 0
bewm.Position = hum.Parent.Torso.Position + Vector3.new(math.random(-5,5),math.random(-5,5),math.random(-5,5))
-- end))
-- hum:TakeDamage(damage.Value + damageboost)
end
end
end
end
end
end))
coroutine.resume(coroutine.create(function()
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt13.CFrame * CFrame.new(0,-0.5,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
for i = 0,5,0.1 do
wait()
--freakingbullet.Touched:connect(function(hit) kill(b,hit) end)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
end
freakingbullet.Parent = nil
end))
end
function elecshot()
local freakingbullet = prt6:Clone()
freakingbullet.formFactor = 1
freakingbullet.Parent = workspace
freakingbullet.CanCollide = false
freakingbullet.BrickColor = BrickColor.new("Bright blue")
freakingbullet.Name = "Bullet6"
freakingbullet.Size = Vector3.new(1,1,1)
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = Torso.CFrame --* CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(math.rad(90),0,0)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
local freakingbulmsh = Instance.new("CylinderMesh")
freakingbulmsh.Parent = freakingbullet
freakingbulmsh.Scale = Vector3.new(1.6,1.3,0.8)
local force = Instance.new("BodyForce")
force.Parent = freakingbullet
force.force = Vector3.new(0,235,0)
coroutine.resume(coroutine.create(function()
while freakingbullet.Parent ~= nil do --I use this function instead of the touch function :3
wait()
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - freakingbullet.Position;
local mag = targ.magnitude;
if mag <= 5 and c[i].Name ~= Player.Name then
hum:TakeDamage(20)
coroutine.resume(coroutine.create(function()
for i = 0,6 do
wait(0.2)
hum:TakeDamage(3)
local me = Instance.new("SpecialMesh")
me.MeshType = "Sphere"
local wave = Instance.new("Part")
me.Parent = wave
wave.formFactor = 1
wave.Parent = workspace
wave.CanCollide = false
wave.Anchored = true
wave.BrickColor = BrickColor.new("Bright blue")
wave.Name = "Waveh"
wave.Size = Vector3.new(1,1,1)
wave.Position = Torso.Position
wave.CFrame = hum.Parent.Torso.CFrame * CFrame.new(math.random(-5,5),math.random(-5,5),math.random(-5,5))
elecsound(wave,1.5)
coroutine.resume(coroutine.create(function()
for i = 0,1,0.1 do
wait()
me.Scale = me.Scale + Vector3.new(1,1,1)
wave.Transparency = wave.Transparency + 0.1
end
wave.Parent = nil
end))
DBHit(hum.Parent.Torso,freakingbullet)
end
end))
freakingbullet.Parent = nil
end
end
end
end
end
end))
coroutine.resume(coroutine.create(function()
freakingbullet.Position = Torso.Position
freakingbullet.CFrame = prt24.CFrame * CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(0,0,0)
for i = 0,5,0.1 do
wait()
--freakingbullet.Touched:connect(function(hit) kill(b,hit) end)
freakingbullet.Velocity = Torso.CFrame.lookVector * 100
end
freakingbullet.Parent = nil
end))
end
function laz0rshot()
local laz0rhed = Instance.new("Part")
laz0rhed.formFactor = 1
laz0rhed.Parent = workspace
laz0rhed.CanCollide = false
laz0rhed.BrickColor = BrickColor.new("New Yeller")
laz0rhed.Name = "HeadOfTehLaz0r"
laz0rhed.Size = Vector3.new(3,1,3)
laz0rhed.Position = Torso.Position
laz0rhed.CFrame = prt37.CFrame * CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(math.rad(90),0,0)
local lazmsh = Instance.new("SpecialMesh")
lazmsh.MeshType = "Sphere"
lazmsh.Parent = laz0rhed
lazmsh.Scale = Vector3.new(0,0,0)
local lazwel = Instance.new("Weld")
lazwel.Parent = laz0rhed
lazwel.Part0 = laz0rhed
lazwel.Part1 = prt37
for i = 0 , 1 , 0.01 do
wait(0)
lazmsh.Scale = lazmsh.Scale + Vector3.new(0.01,0.04,0.01)
LW.C0 = CFrame.new(-1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(-0.5*i+1,0,0)
LW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
RW.C0 = CFrame.new(1.5,0.5,0) * CFrame.fromEulerAnglesXYZ(math.rad(90),0.5*i,-0.1*i)
RW.C1 = CFrame.new(0, 0.5, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
end
wait(0.3)
print(lazmsh.Scale)
laz0rhed.Parent = nil
local tehlaz0r = Instance.new("Part")
tehlaz0r.formFactor = 1
tehlaz0r.Parent = workspace
tehlaz0r.CanCollide = false
tehlaz0r.BrickColor = BrickColor.new("New Yeller")
tehlaz0r.Name = "LAAAAAAAAAAAAAAAZ0R"
tehlaz0r.Size = Vector3.new(3,5,3)
tehlaz0r.Position = Torso.Position
tehlaz0r.CFrame = prt37.CFrame --* CFrame.new(0,0,0) * CFrame.fromEulerAnglesXYZ(math.rad(90),0,0)
tehlaz0r.Velocity = Torso.CFrame.lookVector * 50
--[[v=Instance.new("BodyVelocity")
v.P=3000
v.maxForce=Vector3.new(math.huge,math.huge,math.huge)
v.velocity=Vector3.new(Torso.Velocity.x,0,Torso.Velocity.z)
v.Parent=tehlaz0r]]
local TLM = Instance.new("CylinderMesh")
TLM.Parent = tehlaz0r
TLM.Scale = lazmsh.Scale - Vector3.new(0,3.5,0)
lazwel.Part0 = laz0rhed
lazwel.Part1 = tehlaz0r
lazwel.C0 = CFrame.new(0, 4, 0) * CFrame.fromEulerAnglesXYZ(0,0,0)
local force = Instance.new("BodyForce")
force.Parent = tehlaz0r
force.force = Vector3.new(0,8480,0)
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - tehlaz0r.Position;
local mag = targ.magnitude;
if mag <= 3 and c[i].Name ~= Player.Name then
coroutine.resume(coroutine.create(function()
for i = 0,1,0.1 do
wait()
DBHit(head.Parent.Torso,tehlaz0r)
end
end))
end
end
end
end
coroutine.resume(coroutine.create(function()
wait(20)
tehlaz0r.Parent = nil
end))
coroutine.resume(coroutine.create(function()
while tehlaz0r.Parent ~= nil do
wait(0)
local lazclon = tehlaz0r:Clone()
lazclon.Anchored = true
lazclon.Parent = workspace
local c = game.Workspace:GetChildren();
for i = 1, #c do
local hum = c[i]:findFirstChild("Humanoid")
if hum ~= nil and hum.Health ~= 0 then
local head = c[i]:findFirstChild("Head");
if head ~= nil then
local targ = head.Position - lazclon.Position;
local mag = targ.magnitude;
if mag <= 3 and c[i].Name ~= Player.Name then
coroutine.resume(coroutine.create(function()
for i = 0,1,0.1 do
wait()
DBHit1(head,lazclon)
end
end))
end
end
end
end
coroutine.resume(coroutine.create(function()
wait(3)
for i = 0,1,0.1 do
wait()
lazclon.Transparency = lazclon.Transparency + 0.1
end
lazclon.Parent = nil
end))
end
end))
print(TLM.Scale)
end
--[[Tool Functions]]--
hold = false
function ob1d(mouse)
hold = true
oneslash()
if hold == true then
twoslash()
end
end
function ob1u(mouse)
hold = false
end
buttonhold = false
function key(key)
if attack == true then return end
if key == "q" then
unload()
end
if key == "e" then
sniper()
end
if key == "r" then
kerbewmshot()
end
if key == "f" then
crush()
end
if key == "z" then
elecshoot()
end
if key == "x" then
laz0rshoot()
end
if key == "c" then
cycloneskates()
end
end
function key2(key)
charging2 = false
tornadoing = false
end
function s(mouse)
mouse.Button1Down:connect(function() ob1d(mouse) end)
mouse.Button1Up:connect(function() ob1u(mouse) end)
mouse.KeyDown:connect(key)
mouse.KeyUp:connect(key2)
unsheathed = true
player = Player
ch = Character
RSH = ch.Torso["Right Shoulder"]
LSH = ch.Torso["Left Shoulder"]
--
RSH.Parent = nil
LSH.Parent = nil
--
RW.Part0 = ch.Torso
RW.C0 = CFrame.new(1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.3, 0, -0.5)
RW.C1 = CFrame.new(0, 0.5, 0)
RW.Part1 = ch["Right Arm"]
RW.Parent = ch.Torso
--_G.R = RW
--
LW.Part0 = ch.Torso
LW.C0 = CFrame.new(-1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.7, 0, 0.8)
LW.C1 = CFrame.new(0, 0.5, 0)
LW.Part1 = ch["Left Arm"]
LW.Parent = ch.Torso
--_G.L = LW
--
equipanim()
end
function ds(mouse)
unsheathed = false
hideanim()
Character.Humanoid.WalkSpeed = 16
RW.Parent = nil
LW.Parent = nil
RSH.Parent = player.Character.Torso
LSH.Parent = player.Character.Torso
end
Bin.Selected:connect(s)
Bin.Deselected:connect(ds)
function onRunning(speed)
if skill == true then return end
end
Character.Humanoid.Running:connect(onRunning)
while true do
wait(0)
end
-- lego |
object_draft_schematic_furniture_wod_ns_potted_plant_scem_04 = object_draft_schematic_furniture_shared_wod_ns_potted_plant_scem_04:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_furniture_wod_ns_potted_plant_scem_04, "object/draft_schematic/furniture/wod_ns_potted_plant_scem_04.iff")
|
-- messages
|
function init(virtual)
if not virtual then
energy.init()
-- tile mods to pull
self.pullTypes = entity.configParameter("pullTypes") or {}
-- tile mods not worth replacing
self.trashTypes = entity.configParameter("trashTypes") or {}
self.cleanupLocs = {}
self.nullMod = "grass"
self.pullInterval = 1
self.pullTimer = self.pullInterval
self.findInterval = 10
self.findTimer = self.findInterval
self.range = 100
findOres()
self.energyCost = 100
self.needleMinPos = math.pi / 2.1
self.needleRange = math.pi / 1.16
storage.state = storage.state or false
checkNodes()
end
end
function die()
energy.die()
end
function onInteraction(args)
if not entity.isInboundNodeConnected(0) then
storage.state = not storage.state
updateAnimationState()
end
end
function main()
energy.update()
cleanupMods()
if self.findTimer > 0 then
self.findTimer = self.findTimer - entity.dt()
elseif storage.state then
findOres()
self.findTimer = self.findInterval
end
if self.pullTimer > 0 then
self.pullTimer = self.pullTimer - entity.dt()
elseif storage.state and energy.consumeEnergy(self.energyCost) then
pullOres()
self.pullTimer = self.pullInterval
end
updateAnimationState()
end
function onInboundNodeChange(args)
checkNodes()
end
function onNodeConnectionChange()
checkNodes()
end
function checkNodes()
entity.setInteractive(not entity.isInboundNodeConnected(0))
if entity.isInboundNodeConnected(0) then
storage.state = entity.getInboundNodeLevel(0)
end
updateAnimationState()
end
function updateAnimationState()
if entity.animationState("magnetState") ~= "pulse" then
if storage.state then
if energy.getEnergy() < energy.getCapacity() then
entity.setAnimationState("magnetState", "charge")
else
entity.setAnimationState("magnetState", "on")
end
else
entity.setAnimationState("magnetState", "off")
end
end
setNeedlePos()
end
function setNeedlePos()
local angle = self.needleMinPos - self.needleRange * ((energy.getEnergy() / energy.getCapacity()) + (math.random() * 0.04))
entity.rotateGroup("needle", angle)
end
function findOres()
local pos1 = entity.toAbsolutePosition({-self.range, -self.range})
local pos2 = entity.toAbsolutePosition({self.range, 5})
-- world.logInfo("finding ores in area from %s to %s", pos1, pos2)
self.oreLocs = {}
for x=pos1[1], pos2[1] do
for y=pos1[2], pos2[2] do
local mod = world.mod({x, y}, "foreground")
if mod and self.pullTypes[mod] then
--world.logInfo("found %s at %d, %d", mod, x, y)
self.oreLocs[#self.oreLocs + 1] = {position={x, y}, mod=mod, active=true}
end
end
end
table.sort(self.oreLocs, compareDistance)
end
function compareDistance(a, b)
return world.magnitude(entity.position(), a.position) < world.magnitude(entity.position(), b.position)
end
function math.round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function pullOres()
entity.setAnimationState("magnetState", "pulse")
for i, ore in ipairs(self.oreLocs) do
if ore.active then
if world.mod(ore.position, "foreground") == ore.mod then
local relPos = {ore.position[1] - entity.position()[1], ore.position[2] - entity.position()[2]}
local magnitude = math.sqrt((relPos[1] ^ 2) + (relPos[2] ^ 2)) * 1.2
local jitter = {math.random() * 0.8 - 0.4, math.random() * 0.8 - 0.4}
local newPos = {math.round(ore.position[1] - (relPos[1] / magnitude) + jitter[1]), math.round(ore.position[2] - (relPos[2] / magnitude) + jitter[2])}
local prevMod = world.mod(newPos, "foreground")
if newPos ~= ore.position and world.material(newPos, "foreground") and not self.pullTypes[prevMod] then
if world.placeMod(newPos, "foreground", ore.mod) then
if prevMod and not self.trashTypes[prevMod] then
world.placeMod(ore.position, "foreground", prevMod)
else
markForCleanup(ore.position)
end
ore.position = newPos
end
end
else
ore.active = false
end
end
end
end
function markForCleanup(pos)
world.placeMod(pos, "foreground", self.nullMod)
self.cleanupLocs[#self.cleanupLocs + 1] = pos
end
function cleanupMods()
if #self.cleanupLocs > 0 then
local finalLocs = {}
-- world.logInfo("cleaning up null mods at %s", self.cleanupLocs)
for i, pos in ipairs(self.cleanupLocs) do
if world.mod(pos, "foreground") == self.nullMod then
finalLocs[#finalLocs + 1] = pos
end
end
self.cleanupLocs = {}
if #finalLocs > 0 then
world.damageTiles(finalLocs, "foreground", entity.position(), "plantish", 0.01)
end
end
end |
local resultFlag = "0"
local n = tonumber(ARGV[1])
local key = KEYS[1]
local goodsInfo = redis.call("HMGET",key,"totalCount","seckillCount")
local total = tonumber(goodsInfo[1])
local alloc = tonumber(goodsInfo[2])
if not total then
return resultFlag
end
if total >= alloc + n then
local ret = redis.call("HINCRBY",key,"seckillCount",n)
return tostring(ret)
end
return resultFlag |
serverVersion = "0.0.1"
hotUpdateVersion = "1.1.1"
|
local factory
for _,tycoon in pairs(game.Workspace.Tycoons:GetChildren()) do
if tycoon.Factory.Player.Value == game.Players.LocalPlayer then
factory = tycoon.Factory
end
end
local lastCounter
factory.PlacedItems.Finished.ChildAdded:Connect(function(obj)
if obj.Name == "Counter4" then
lastCounter = obj
end
end)
while true do
game.Workspace.Events.ItemPurchase:InvokeServer(0,"cda",0)
game.Workspace.Events.Building.PlaceObject:InvokeServer({Workspace.Furniture.Counter4,false,Vector3.new(0,-10,0),90,"cda"})
factory.RestaurantHandler.RemoveFurniture:InvokeServer(lastCounter,3)
end |
local result_new = require("opentelemetry.trace.sampling.result").new
local _M = {
}
local mt = {
__index = _M
}
function _M.new()
return setmetatable({}, mt)
end
function _M.should_sample(self, parameters)
return result_new(0, parameters.parent_ctx.trace_state)
end
function _M.description(self)
return "AlwaysOffSampler"
end
return _M |
local getFrameIndex
local chatPrint
local filterDefaults = {
['locale'] = 'default',
['printframe'] = 1,
}
local perCharacterFilter = {
['printframe'] = true,
}
function chatPrint(text, cRed, cGreen, cBlue, cAlpha, holdTime)
--local frameIndex = DFLootDictionary.Config.GetFrameIndex();
if (cRed and cGreen and cBlue) then
if (DEFAULT_CHAT_FRAME) then
DEFAULT_CHAT_FRAME:AddMessage(text, cRed, cGreen, cBlue, cAlpha, holdTime);
end
else
if (DEFAULT_CHAT_FRAME) then
DEFAULT_CHAT_FRAME:AddMessage(text, 1.0, 0.5, 0.25);
end
end
end
function split(str, at)
local splut = {};
if (type(str) ~= "string") then return nil end
if (not str) then str = "" end
if (not at)
then table.insert(splut, str)
else
for n, c in string.gfind(str, '([^%'..at..']*)(%'..at..'?)') do
table.insert(splut, n);
if (c == '') then break end
end
end
return splut;
end
DFLootDictionary.Util = {
GetFilterDefaults = getFilterDefaults,
GetFrameIndex = getFrameIndex,
ChatPrint = chatPrint,
strSplit = split
}
|
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if IsControlPressed(1, 323) then --Start holding X
TaskHandsUp(GetPlayerPed(-1), 1000, -1, -1, true) -- Perform animation.
end
end
end) |
return require('custom_example2')
|
require("moonsc").import_tags()
-- A simple test that onexit handlers work.
-- var1 should be incremented when we leave s0
return _scxml{ initial="s0",
_datamodel{
_data{ id="var1", expr="0" },
},
_state{ id="s0",
_onexit{ _assign{ location="var1", expr="var1+1" }},
_transition{ target="s1" },
},
_state{ id="s1",
_transition{ cond="var1==1", target="pass" },
_transition{ target="fail" },
},
_final{id='pass'},
_final{id='fail'},
}
|
---------------------------------------------------------------------------------------------------
-- Proposal:
-- https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0204-same-app-from-multiple-devices.md
-- Description:
-- Two mobile applications with the same appNames and different appIds from different mobiles send
-- SubscribeWayPoints requests and receive OnWayPointChange notifications.
--
-- Preconditions:
-- 1) SDL and HMI are started
-- 2) Mobiles №1 and №2 are connected to SDL
--
-- Steps:
-- 1) Mobile №1 App1 requested Subscribe on WayPoints
-- Check:
-- SDL sends Navigation.SubscribeWayPoints(appId_1) to HMI
-- SDL receives Navigation.SubscribeWayPoints("SUCCESS") response from HMI
-- SDL sends SubscribeWayPoints("SUCCESS") response to Mobile №1
-- SDL sends OnHashChange with updated hashId to Mobile №1
-- 2) HMI sent OnWayPointChange notification
-- Check:
-- SDL sends OnWayPointChange notification to Mobile №1
-- SDL does NOT send OnWayPointChange to Mobile №2
-- 3) Mobile №2 App2 requested Subscribe on WayPoints
-- Check:
-- SDL sends Navigation.SubscribeWayPoints(appId_1) to HMI
-- SDL sends SubscribeWayPoints("SUCCESS") response to Mobile №2
-- SDL sends OnHashChange with updated hashId to Mobile №2
-- 4) HMI sent OnWayPointChange notification
-- Check:
-- SDL sends OnWayPointChange notification to Mobile №1 and to Mobile №2
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/TheSameApp/commonTheSameApp')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Data ]]
local devices = {
[1] = { host = "1.0.0.1", port = config.mobilePort },
[2] = { host = "192.168.100.199", port = config.mobilePort }
}
local appParams = {
[1] = { appName = "Test Application", appID = "0001", fullAppID = "0000001" },
[2] = { appName = "Test Application", appID = "00022", fullAppID = "00000022" }
}
local wayPointsGroup = {
rpcs = {
GetWayPoints = { hmi_levels = {"BACKGROUND", "FULL", "LIMITED"} },
SubscribeWayPoints = { hmi_levels = {"BACKGROUND", "FULL", "LIMITED"} },
UnsubscribeWayPoints = { hmi_levels = {"BACKGROUND", "FULL", "LIMITED"} },
OnWayPointChange = { hmi_levels = {"BACKGROUND", "FULL", "LIMITED"} }
}
}
local pWayPoints = { locationName = "Location Name", coordinate = { latitudeDegrees = 1.1, longitudeDegrees = 1.1 }}
--[[ Local Functions ]]
local function modifyWayPointGroupInPT(pt)
pt.policy_table.functional_groupings["DataConsent-2"].rpcs = common.json.null
pt.policy_table.functional_groupings["WayPoints"] = wayPointsGroup
pt.policy_table.app_policies[appParams[1].fullAppID] = common.cloneTable(pt.policy_table.app_policies["default"])
pt.policy_table.app_policies[appParams[1].fullAppID].groups = {"Base-4", "WayPoints"}
pt.policy_table.app_policies[appParams[2].fullAppID] = common.cloneTable(pt.policy_table.app_policies["default"])
pt.policy_table.app_policies[appParams[2].fullAppID].groups = {"Base-4", "WayPoints"}
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Prepare preloaded PT", common.modifyPreloadedPt, {modifyWayPointGroupInPT})
runner.Step("Start SDL and HMI", common.start)
runner.Step("Connect two mobile devices to SDL", common.connectMobDevices, {devices})
runner.Step("Register App1 from device 1", common.registerAppEx, { 1, appParams[1], 1 })
runner.Step("Register App2 from device 2", common.registerAppEx, { 2, appParams[2], 2 })
runner.Step("Activate App 1", common.app.activate, { 1 })
runner.Title("Test")
runner.Step("App1 from Mobile 1 requests SubscribeWayPoints", common.sendSubscribeWayPoints, { 1, true })
runner.Step("HMI sends OnWayPointChange - App 1 receives", common.sendOnWayPointChange, { 1, 2, 1, pWayPoints })
runner.Step("Activate App 2", common.app.activate, { 2 })
runner.Step("App2 from Mobile 2 requests SubscribeWayPoints", common.sendSubscribeWayPoints, { 2 })
runner.Step("HMI sends OnWayPointChange - Apps 1 and 2 receive", common.sendOnWayPointChange, { 2, 1, 2, pWayPoints })
runner.Title("Postconditions")
runner.Step("Remove mobile devices", common.clearMobDevices, {devices})
runner.Step("Stop SDL", common.postconditions)
|
function EFFECT:Init( data )
local posoffset = data:GetOrigin()
local emitter = ParticleEmitter( posoffset )
for i = 0,5 do
local p = emitter:Add( "particle/particle_smokegrenade", posoffset )
p:SetVelocity( math.random(12,16) * math.sqrt(i) * data:GetNormal() * 3 + 2 * VectorRand() )
p:SetAirResistance(400)
p:SetStartAlpha( math.Rand( 255, 255 ) )
p:SetEndAlpha( 0 )
p:SetDieTime( math.Rand( 0.5, 1.5 ) )
p:SetStartSize( math.Rand( 5, 8 ) *math.Clamp(i,1,4) * 0.166 )
p:SetEndSize( math.Rand( 16, 24 ) * math.sqrt(math.Clamp(i,1,4)) * 0.166 )
p:SetRoll( math.Rand( -25, 25 ) )
p:SetRollDelta( math.Rand( -0.05, 0.05 ) )
p:SetColor( 135, 135, 135 )
end
if GetTFAGasEnabled() then
local p = emitter:Add( "sprites/heatwave", posoffset )
p:SetVelocity( 50 * data:GetNormal() + 0.5 * VectorRand() )
p:SetAirResistance( 200 )
p:SetStartSize( math.random(12.5,17.5) )
p:SetEndSize( 2 )
p:SetDieTime( math.Rand(0.15, 0.225) )
p:SetRoll( math.Rand(-180,180) )
p:SetRollDelta( math.Rand(-0.75,0.75) )
end
emitter:Finish()
end
function EFFECT:Think( )
return false
end
function EFFECT:Render()
return false
end |
function HandleUnrankCommand(Split, Player)
-- Also handles the /deop command
local Response
local PlayerName = Split[2]
local InformLoadRank = function(OtherPlayer)
local AuthorName = "the server console"
if Player then
AuthorName = "\"" .. Player:GetName() .. "\""
end
OtherPlayer:SendMessageInfo("You were unranked by " .. AuthorName)
OtherPlayer:LoadRank()
end
if not PlayerName then
Response = SendMessage(Player, "Usage: " .. Split[1] .. " <player>")
else
-- Translate the PlayerName to a UUID:
local PlayerUUID = GetPlayerUUID(PlayerName)
if not PlayerUUID or string.len(PlayerUUID) ~= 32 then
Response = SendMessage(Player, "There is no player with the name \"" .. PlayerName .. "\"")
else
-- Unrank the player:
cRankManager:RemovePlayerRank(PlayerUUID)
-- Let the player know:
SafeDoWithPlayer(PlayerName, InformLoadRank)
Response = SendMessage(Player, "Player \"" .. PlayerName .. "\" is now in the default rank")
end
end
return true, Response
end
function HandleConsoleUnrank(Split)
return HandleUnrankCommand(Split)
end
|
local function read(domain, address, bytes)
local methods = {
[1] = memory.readbyte,
[2] = memory.readdword
}
if (methods[bytes]) then
return methods[bytes](address)
end
return 0
end
function wram(address, bytes)
return read('WRAM', address, bytes);
end
function rom(address, bytes)
return read('CARTROM', address, bytes);
end |
--
-- racewar_server.lua
--
Racewar = {}
Racewar.__index = Racewar
local chooseTeamDisplay = nil
local chooseTeamLines = {}
local newsDisplay = nil -- messages go here instead of the chatbox
local newsDisplayLines = {}
local statusDisplay = nil -- Score and rounds left
local statusDisplayLines = {}
local playerlist = {} -- All Players
local teamlist = {} -- All teams
local teamdata = {} -- team={score=0,blah=0}
local newsText = { "", "", "", }
local roundCurrent = 0 -- eg 1,2,3
local roundsTotal = 0 -- eg 3
local bRoundJustEnded = false
---------------------------------------------------------------------------
--
-- Events
--
--
---------------------------------------------------------------------------
addEventHandler('onResourceStart', g_ResRoot,
function()
Racewar.startup()
for _,player in ipairs(getElementsByType('player')) do
Racewar.handlePlayerJoin(player)
end
end
)
addEventHandler('onResourceStop', g_Root,
function(resource)
if 'map' == getResourceInfo(resource,'type') then
Racewar.setBigMessage('')
end
end
)
addEvent('onMapStarting')
addEventHandler('onMapStarting', g_Root,
function(mapInfo)
Racewar.setModeAndMap( mapInfo.modename, mapInfo.name )
end
)
addEvent('onPlayerFinish')
addEventHandler('onPlayerFinish', g_Root,
function(rank, time)
Racewar.playerFinished( source, rank )
end
)
addEventHandler('onResourceStop', g_ResRoot,
function()
Racewar.shutdown()
end
)
addEventHandler('onPlayerJoined', g_Root,
function()
Racewar.handlePlayerJoin(source)
end
)
addEventHandler('onPlayerQuit', g_Root,
function()
Racewar.handlePlayerQuit(source)
end
)
addEvent('onPostFinish', true)
addEventHandler('onPostFinish', g_Root,
function()
Racewar.roundEnd()
end
)
---------------------------------------------------------------------------
--
-- Commands
--
--
---------------------------------------------------------------------------
addCommandHandler('teamname',
function(player,command,...)
Racewar.startChangeTeamNameVote(player, table.concat({...}, " ") )
end
)
addCommandHandler('newwar',
function(player,command,...)
Racewar.startNewWarVote(player, table.concat({...}, " ") )
end
)
---------------------------------------------------------------------------
--
-- Startup / shutdown
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.startup()
---------------------------------------------------------------------------
function Racewar.startup()
cacheSettings()
Racewar.output( 'Startup' )
teamlist = {}
teamlist[1] = createTeam ( "Red", 255, 0, 0 )
teamlist[2] = createTeam ( "Blue", 0, 0, 255 )
teamlist[3] = createTeam ( "Green", 0, 255, 0 )
teamdata = {}
for _,team in ipairs(teamlist) do
teamdata[team] = {}
teamdata[team].score = 0
end
Racewar.updateChooseTeamDisplay()
Racewar.updateNewsDisplay()
Racewar.updateStatusDisplay()
end
---------------------------------------------------------------------------
-- Racewar.shutdown()
---------------------------------------------------------------------------
function Racewar.shutdown()
Racewar.output( 'Shutdown' )
-- Remove display
Racewar.destroyChooseTeamDisplay()
-- Remove teams
table.each( teamlist, destroyElement )
teamlist = {}
teamdata = {}
end
---------------------------------------------------------------------------
-- Racewar.initializeNewWar()
---------------------------------------------------------------------------
function Racewar.initializeNewWar()
roundCurrent = 1
roundsTotal = g_Settings.numrounds
if teamlist then
table.each( teamlist, setTeamScore, 0 )
end
Racewar.updateStatusDisplay()
end
---------------------------------------------------------------------------
--
-- Map loading
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.setModeAndMap() -- Called when a new map has been loaded
---------------------------------------------------------------------------
function Racewar.setModeAndMap( raceModeName, mapName )
if raceModeName == 'Sprint' then
Racewar.roundStart()
end
end
---------------------------------------------------------------------------
--
-- Points
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- convertPoints -- To look like something else, so it doesn't clash with other point systems
---------------------------------------------------------------------------
function convertPoints(pts)
return g_Settings.ptsprefix .. pts .. g_Settings.ptspostfix
end
---------------------------------------------------------------------------
--
-- Players
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.handlePlayerJoin()
---------------------------------------------------------------------------
function Racewar.handlePlayerJoin( player )
if isInPlayerList(player) then
return
end
addToPlayerList(player)
setTimer(
function()
if isInPlayerList(player) then
Racewar.playerChooseTeam(player)
end
end,
3000, 1 )
end
---------------------------------------------------------------------------
-- Racewar.playerFinished() -- Update team points
---------------------------------------------------------------------------
function Racewar.playerFinished( player, rank )
local team = getPlayerTeam(player)
if team then
local othercount = 0
-- count up others not finished who are not on the player's team
for _,other in ipairs(playerlist) do
if not isPlayerFinished(other) and team ~= getPlayerTeam(other) then
othercount = othercount + 1
end
end
--Racewar.outputChat( 'You beat ' .. othercount .. ' player' .. (othercount==1 and '' or 's') .. ' from other teams', player )
local pointsEarned = othercount -- getPlayerCount() - rank + 1
Racewar.output( convertPoints(pointsEarned) .. " for '"..getTeamName(team).."' by "..getPlayerName(player) )
addTeamScore(team,pointsEarned)
Racewar.updateStatusDisplay()
end
end
---------------------------------------------------------------------------
-- Racewar.handlePlayerQuit()
---------------------------------------------------------------------------
function Racewar.handlePlayerQuit( player )
Racewar.changePlayerTeam( player, 0 )
textDisplayRemoveObserver( chooseTeamDisplay, player )
textDisplayRemoveObserver( newsDisplay, player )
textDisplayRemoveObserver( statusDisplay, player )
removeFromPlayerList(player)
end
---------------------------------------------------------------------------
--
-- Rounds
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.roundStart()
---------------------------------------------------------------------------
function Racewar.roundStart()
local bNextRound = roundCurrent > 0 and bRoundJustEnded
local bRoundRestarted = roundCurrent > 0 and not bRoundJustEnded
local bNextWar = roundCurrent == 0 or bNextRound and roundCurrent >= roundsTotal
if bNextWar then
Racewar.initializeNewWar()
Racewar.output( 'Starting ' .. roundsTotal .. ' round war' )
elseif bRoundRestarted then
Racewar.output( 'Restarting round ' .. roundCurrent )
elseif bNextRound then
roundCurrent = roundCurrent + 1
Racewar.output( 'Starting round ' .. roundCurrent )
end
Racewar.updateStatusDisplay()
bRoundJustEnded = false
bRoundJustStarted = true
end
---------------------------------------------------------------------------
-- Racewar.roundEnd()
---------------------------------------------------------------------------
function Racewar.roundEnd()
if not bRoundJustStarted or roundCurrent == 0 then
return
end
if roundCurrent >= roundsTotal then
-- Show congrats message
local ordered = getTeamsScoreSorted()
local bestteam = ordered[1]
local secondteam = ordered[2]
if getTeamScore(bestteam) > getTeamScore(secondteam) then
local congrats = getTeamName(bestteam) .. ' won the war'
local teamplayers = ''
local counter = 0
--for i=1,30 do
for _, player in ipairs(getPlayersInTeam(bestteam)) do
counter = counter + 1
if teamplayers ~= '' then
if counter % 6 == 0 then
teamplayers = teamplayers .. '\n'
else
teamplayers = teamplayers .. ', '
end
end
teamplayers = teamplayers .. getPlayerName(player)
end
--end
Racewar.output(congrats)
local r,g,b = getTeamColor(bestteam)
Racewar.setBigMessage( congrats, teamplayers, r,g,b )
else
Racewar.setBigMessage( 'War draw', '', 230,230,230 )
end
end
bRoundJustEnded = true
bRoundJustStarted = false
end
---------------------------------------------------------------------------
--
-- Status Display
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.updateStatusDisplay()
---------------------------------------------------------------------------
function Racewar.updateStatusDisplay()
if not statusDisplay then
statusDisplay = textCreateDisplay()
local x=0.90
local y=0.01 + 0.15
statusDisplayLines[1] = textCreateTextItem ( ' RACEWAR Standings', x, y, 'low', 255, 255, 160, 255, 1.2, 'center' )
y = y + 0.017
statusDisplayLines[2] = textCreateTextItem ( ' Round 1 of 3', x, y, 'low', 160, 160, 160, 255, 1.0, 'center' )
y = y + 0.014
statusDisplayLines[3] = textCreateTextItem ( '1st 40 pts Red team', x, y, 'low', 240, 240, 240, 255, 1.4, 'center' )
y = y + 0.02
statusDisplayLines[4] = textCreateTextItem ( '2nd 10 pts Green team', x, y, 'low', 230, 230, 230, 255, 1.2, 'center' )
y = y + 0.019
statusDisplayLines[5] = textCreateTextItem ( '3rd 4 pts Blue team', x, y, 'low', 220, 220, 220, 255, 1.0, 'center' )
statusDisplayLines[6] = textCreateTextItem ( '', 0.5, 0.6, 'low', 220, 220, 220, 255, 4.0, 'center' )
statusDisplayLines[7] = textCreateTextItem ( '', 0.5, 0.7, 'low', 220, 220, 220, 255, 1.2, 'center' )
for i,line in ipairs(statusDisplayLines) do
textDisplayAddText ( statusDisplay, line )
end
end
if roundCurrent == 0 then
textItemSetText ( statusDisplayLines[2], '' )
textItemSetText ( statusDisplayLines[3], 'Starts next map' )
textItemSetText ( statusDisplayLines[4], '' )
textItemSetText ( statusDisplayLines[5], '' )
else
textItemSetText ( statusDisplayLines[2], ' Round ' .. roundCurrent .. ' of ' .. roundsTotal .. '' )
-- Order teams by points
local ordered = getTeamsScoreSorted()
local rank = 1
local rankNext = 1
for idx=1,#ordered do
local team = ordered[idx]
local r,b,g = getTeamColor(team)
local grey = 250-idx*10
r = math.lerp(r,grey,0.75)
g = math.lerp(g,grey,0.75)
b = math.lerp(b,grey,0.75)
local score = getTeamScore(team)
local name = getTeamName(team)
local pos = idx==1 and '1st' or idx==2 and '2nd' or idx==3 and '3rd'
local rankText = rank .. ( (rank < 10 or rank > 20) and ({ [1] = 'st', [2] = 'nd', [3] = 'rd' })[rank % 10] or 'th' )
textItemSetText ( statusDisplayLines[2+idx], rankText..' '..convertPoints(score)..' '..name )
textItemSetColor ( statusDisplayLines[2+idx], r,b,g,255 )
rankNext = rankNext + 1
if idx >= #ordered or getTeamScore(ordered[idx+1]) < score then
rank = rankNext
end
end
end
end
---------------------------------------------------------------------------
-- Racewar.destroyStatusDisplay()
---------------------------------------------------------------------------
function Racewar.destroyStatusDisplay()
for i,line in ipairs(statusDisplayLines) do
textDisplayRemoveText ( statusDisplay, line )
textDestroyTextItem( line )
end
statusDisplayLines = {}
textDestroyDisplay( statusDisplay )
statusDisplay = nil
end
---------------------------------------------------------------------------
-- Racewar.setBigMessage()
---------------------------------------------------------------------------
function Racewar.setBigMessage(line1,line2,r,g,b)
textItemSetText ( statusDisplayLines[6], line1 or '' )
textItemSetText ( statusDisplayLines[7], line2 or '' )
textItemSetColor ( statusDisplayLines[6], r or 255,g or 255,b or 255,255 )
textItemSetColor ( statusDisplayLines[7], r or 255,g or 255,b or 255,210 )
end
---------------------------------------------------------------------------
--
-- News area
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.ouputNews()
---------------------------------------------------------------------------
function Racewar.ouputNews(text)
table.remove( newsText, 1 )
table.insert( newsText, text )
Racewar.updateNewsDisplay()
end
---------------------------------------------------------------------------
-- Racewar.updateNewsDisplay()
---------------------------------------------------------------------------
function Racewar.updateNewsDisplay()
if not newsDisplay then
newsDisplay = textCreateDisplay()
local x=0.85
local y=0.182 + 0.1
newsDisplayLines[1] = textCreateTextItem ( '1', x, y+0.000, 'low', 255, 255, 240, 132, 1, 'left' )
newsDisplayLines[2] = textCreateTextItem ( '2', x, y+0.015, 'low', 255, 255, 240, 162, 1, 'left' )
newsDisplayLines[3] = textCreateTextItem ( '3', x, y+0.030, 'low', 255, 255, 240, 192, 1, 'left' )
for i,line in ipairs(newsDisplayLines) do
textDisplayAddText ( newsDisplay, line )
end
end
textItemSetText ( newsDisplayLines[1], newsText[1] )
textItemSetText ( newsDisplayLines[2], newsText[2] )
textItemSetText ( newsDisplayLines[3], newsText[3] )
end
---------------------------------------------------------------------------
-- Racewar.destroyNewsDisplay()
---------------------------------------------------------------------------
function Racewar.destroyNewsDisplay()
for i,line in ipairs(newsDisplayLines) do
textDisplayRemoveText ( newsDisplay, line )
textDestroyTextItem( line )
end
newsDisplayLines = {}
textDestroyDisplay( newsDisplay )
newsDisplay = nil
end
---------------------------------------------------------------------------
--
-- Choosing teams
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.playerChooseTeam()
---------------------------------------------------------------------------
function Racewar.playerChooseTeam( player )
textDisplayAddObserver( chooseTeamDisplay, player )
bindKey ( player, "1", "down", Racewar.playerTeamChosen, 1 )
bindKey ( player, "2", "down", Racewar.playerTeamChosen, 2 )
bindKey ( player, "3", "down", Racewar.playerTeamChosen, 3 )
bindKey ( player, "F3", "down", Racewar.playerTeamChosen, 0 )
end
---------------------------------------------------------------------------
-- Racewar.playerTeamChosen()
---------------------------------------------------------------------------
function Racewar.playerTeamChosen( player, key, keyState, teamIndex )
textDisplayRemoveObserver( chooseTeamDisplay, player )
unbindKey ( player, "1", "down", Racewar.playerTeamChosen )
unbindKey ( player, "2", "down", Racewar.playerTeamChosen )
unbindKey ( player, "3", "down", Racewar.playerTeamChosen )
unbindKey ( player, "F3", "down", Racewar.playerTeamChosen )
if not getPlayerTeam(player) then
Racewar.outputChat( convertPoints(1) .." per enemy team player you beat to the finish line.", player )
end
Racewar.changePlayerTeam( player, teamIndex )
bindKey ( player, "F3", "down", Racewar.playerChooseTeam )
end
---------------------------------------------------------------------------
-- Racewar.changePlayerTeam()
---------------------------------------------------------------------------
function Racewar.changePlayerTeam( player, newTeamIndex )
local newTeam = teamlist[newTeamIndex]
local oldTeam = getPlayerTeam(player)
if newTeam ~= oldTeam then
if newTeam then
setPlayerTeam(player, newTeam )
Racewar.output( getPlayerName(player) .. " has joined '" .. getTeamName(newTeam).. "'" )
textDisplayAddObserver( newsDisplay, player )
textDisplayAddObserver( statusDisplay, player )
elseif oldTeam then
setPlayerTeam(player, nil )
Racewar.output( getPlayerName(player) .. " has left '" .. getTeamName(oldTeam).. "'")
textDisplayRemoveObserver( newsDisplay, player )
end
end
end
---------------------------------------------------------------------------
-- Racewar.updateChooseTeamDisplay()
---------------------------------------------------------------------------
function Racewar.updateChooseTeamDisplay()
if not chooseTeamDisplay then
local x=0.8
local y=0.282
chooseTeamDisplay = textCreateDisplay()
chooseTeamLines[1] = textCreateTextItem ( 'R A C E W A R', x, y+0.000, 'low', 255, 0, 0, 255, 3, 'center' )
chooseTeamLines[2] = textCreateTextItem ( 'Select your team', x, y+0.070, 'low', 255, 255, 0, 255, 2, 'center' )
chooseTeamLines[3] = textCreateTextItem ( 'Press 1 to join A', x, y+0.119, 'low', 255, 255, 255, 255, 1.4, 'center' )
chooseTeamLines[4] = textCreateTextItem ( 'Press 2 to join B', x, y+0.149, 'low', 255, 255, 255, 255, 1.4, 'center' )
chooseTeamLines[5] = textCreateTextItem ( 'Press 3 to join C', x, y+0.178, 'low', 255, 255, 255, 255, 1.4, 'center' )
chooseTeamLines[6] = textCreateTextItem ( 'Press F3 not to join a team', x, y+0.209, 'low', 200, 200, 200, 255, 1.4, 'center' )
chooseTeamLines[7] = textCreateTextItem ( 'Press F3 to change team later', x, y+0.239, 'low', 200, 200, 0, 255, 1.4, 'center' )
chooseTeamLines[8] = textCreateTextItem ( 'Press F9 for help', x, y+0.269, 'low', 200, 200, 0, 255, 1.4, 'center' )
for i,line in ipairs(chooseTeamLines) do
textDisplayAddText ( chooseTeamDisplay, line )
end
end
textItemSetText ( chooseTeamLines[3], "Press 1 to join '" ..getTeamName(teamlist[1]).. "'" )
textItemSetText ( chooseTeamLines[4], "Press 2 to join '" ..getTeamName(teamlist[2]).. "'" )
textItemSetText ( chooseTeamLines[5], "Press 3 to join '" ..getTeamName(teamlist[3]).. "'" )
end
---------------------------------------------------------------------------
-- Racewar.destroyChooseTeamDisplay()
---------------------------------------------------------------------------
function Racewar.destroyChooseTeamDisplay()
for i,line in ipairs(chooseTeamLines) do
textDisplayRemoveText ( chooseTeamDisplay, line )
textDestroyTextItem( line )
end
chooseTeamLines = {}
textDestroyDisplay( chooseTeamDisplay )
chooseTeamDisplay = nil
end
----------------------------------------------------------------------------
--
-- Changing Team Name
--
--
--
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-- Racewar.startChangeTeamNameVote
----------------------------------------------------------------------------
function Racewar.startChangeTeamNameVote(player, newName)
local team = getPlayerTeam(player)
if not team then
Racewar.outputChat( 'You are not in a team.', player )
return
end
newName = tostring(newName)
if newName:len() < 3 or newName:len() > 50 then
Racewar.outputChat( 'Team name must be between 3 and 50 characters long.', player )
return
end
local result, code = exports.votemanager:startPoll({})
if code == 10 then -- pollAlreadyRunning = 10
Racewar.outputChat( "Can't change team name while a vote is running.", player )
return
end
exports.votemanager:stopPoll()
-- Actual vote started here
local pollDidStart = exports.votemanager:startPoll {
title="Do you want to change the team name to '" .. newName.. "'",
percentage=51,
timeout=10,
allowchange=true,
adjustwidth=50,
visibleTo=team,
[1]={'Yes', 'teamNameVoteResult', team, true, team, newName },
[2]={'No', 'teamNameVoteResult', team, false;default=true},
}
end
----------------------------------------------------------------------------
-- event teamNameVoteResult -- Called from the votemanager when the poll has completed
----------------------------------------------------------------------------
addEvent('teamNameVoteResult')
addEventHandler('teamNameVoteResult', getRootElement(),
function( votedYes, team, newName )
if votedYes and team and newName then
Racewar.output( "Team '"..getTeamName(team).."' is now called '"..newName.."'" )
setTeamName(team,newName)
Racewar.updateChooseTeamDisplay()
Racewar.updateStatusDisplay()
else
Racewar.outputChat( 'Team name vote result was [No].', team )
end
end
)
----------------------------------------------------------------------------
--
-- Start new war vote
--
--
--
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-- Racewar.startNewWarVote
----------------------------------------------------------------------------
function Racewar.startNewWarVote(player)
local result, code = exports.votemanager:startPoll({})
if code == 10 then -- pollAlreadyRunning = 10
Racewar.outputChat( "Can't start a new war vote while another vote is running.", player )
return
end
exports.votemanager:stopPoll()
-- Actual vote started here
local pollDidStart = exports.votemanager:startPoll {
title="Do you want to start a new war?",
percentage=51,
timeout=10,
allowchange=true,
adjustwidth=50,
visibleTo=getRootElement(),
[1]={'Yes', 'newWarVoteResult', getRootElement(), true},
[2]={'No', 'newWarVoteResult', getRootElement(), false;default=true},
}
end
----------------------------------------------------------------------------
-- event teamNameVoteResult -- Called from the votemanager when the poll has completed
----------------------------------------------------------------------------
addEvent('newWarVoteResult')
addEventHandler('newWarVoteResult', getRootElement(),
function( votedYes )
if votedYes then
Racewar.initializeNewWar()
Racewar.output( 'Starting new ' .. roundsTotal .. ' round war' )
else
Racewar.outputChat( 'New war vote result was [No].', g_Root )
end
end
)
---------------------------------------------------------------------------
--
-- Player List
--
--
--
---------------------------------------------------------------------------
function addToPlayerList( player )
table.insert(playerlist,player)
end
function removeFromPlayerList( player )
table.removevalue(playerlist,player)
end
function isInPlayerList( player )
return table.find(playerlist,player)
end
---------------------------------------------------------------------------
--
-- Team Score
--
--
--
---------------------------------------------------------------------------
function getTeamScore( team )
return teamdata[team].score
end
function setTeamScore( team, score )
teamdata[team].score = score
end
function addTeamScore( team, score )
teamdata[team].score = teamdata[team].score + score
end
function getTeamsScoreSorted()
local ordered = table.deepcopy(teamlist)
table.sort(ordered, function(a,b) return(getTeamScore(a) > getTeamScore(b)) end)
return ordered
end
---------------------------------------------------------------------------
--
-- Misc
--
--
--
---------------------------------------------------------------------------
---------------------------------------------------------------------------
-- Racewar.output()
---------------------------------------------------------------------------
function Racewar.output(text)
--outputChatBox ( "#C0C0C0Racewar: #FFFF00" .. text, getRootElement(), 255, 255, 255, true )
Racewar.ouputNews(text)
end
function Racewar.outputChat(text,visibleTo)
outputChatBox ( "#C0C0C0Racewar: #FFFF00" .. text, visibleTo or getRootElement(), 255, 255, 255, true )
end
function isPlayerFinished(player)
return getElementData(player, 'race.finished')
end
---------------------------------------------------------------------------
--
-- Settings
--
--
--
---------------------------------------------------------------------------
function cacheSettings()
g_Settings = {}
g_Settings.numrounds = getNumber('numrounds','3')
g_Settings.ptsprefix = getString('ptsprefix','$')
g_Settings.ptspostfix = getString('ptspostfix',',000')
end
-- Initial cache
addEventHandler('onResourceStart', g_ResRoot,
function()
cacheSettings()
end
)
-- React to admin panel changes
addEvent ( "onSettingChange" )
addEventHandler('onSettingChange', g_ResRoot,
function(name, oldvalue, value, playeradmin)
cacheSettings()
Racewar.updateStatusDisplay()
end
)
|
require"cdlua"
require"iupluacd"
require"iuplua"
--main canvas
canva = iup.canvas {size = "200x100"}
--vertical box
vbox = iup.vbox{ canva }
--main dialog
dlg = iup.dialog{vbox; title="test-1.0"}
--responsible for creating the CD canvas
function canva:map_cb()
canvas = cd.CreateCanvas(cd.IUP, self)
self.canvas = canvas
end
--retrieves the CD canvas associated to IupCanvas control and destroys it
function dlg:close_cb()
canva = canva
canvas = canva.canvas
canvas:Kill()
self:destroy()
return iup.IGNORE
end
--responsible for drawing the image on canvas
function canva:action()
canvas = self.canvas
canvas:Activate()
canvas:Clear()
canva:button_cb(_, _, 0, 0, _)
end
--use to draw elements
function draw(self,xmin,xmax,ymin,ymax)
canvas:Clear()
width, height = canvas:GetSize() --use to get the size of canvas
print("width="..width.." height="..height)
canvas = self.canvas
canvas:Foreground (cd.BLUE)
canvas:Box (xmin, xmax, ymin,ymax) --use to draw box on canvas
canvas:Foreground(cd.EncodeColor(255, 32, 140))
canvas:Line(0, height, 100, height-100) --use to draw line on canvas
end
--the function is called when a mouse button is pressed
function canva:button_cb(b, e, x, y, r)
print ("Button: " .. "Button="..tostring(b).." Pressed="..tostring(e).." X="..tostring(x).." Y="..tostring(y) )
local canvas = self.canvas
width, height = canvas:GetSize() --use to get the size of canvas
draw(self,x-10,x+10,height-y-10,height-y+10)
end
--call when size is change
function canva:resize_cb(w, h)
print("Width="..w.." Height="..h)
draw(self,-10,10,h-10,h+10)
end
dlg:show()
if (iup.MainLoopLevel()==0) then
iup.MainLoop()
iup.Close()
end
|
return {
{
name = 'ARM',
startunit = 'armcom',
},
{
name = 'CORE',
startunit = 'corcom',
},
{
name = 'TLL',
startunit = 'tllcom',
},
{
name = 'TALON',
startunit = 'talon_com',
},
{
name = 'GOK',
startunit = 'gok_com',
},
}
|
-- I'm just gonna write my own library for events
-- I'm sick of fixing other people's bugs
local Emitter = {}
local pfx_once = '_once_'
setmetatable(Emitter, {
__call = function (_) return Emitter:new() end
})
function Emitter:new()
local obj = {}
self.__index = self
setmetatable(obj, self)
obj:construct()
return obj
end
function Emitter:construct()
-- first it will have a table of events
self.events = {}
-- each of those events is going to be a string
-- and the value will be the array of listeners
-- anything else?
self.events_to_remove = {}
end
function Emitter:on(event, listener)
if self.events[event] then
table.insert(self.events[event], listener)
else
self.events[event] = { listener }
end
end
function Emitter:emit(event, ...)
self:cleanUp()
if self.events[event] then
for i = 1, #self.events[event] do
self.events[event][i](...)
end
end
local once_event = pfx_once..event
if self.events[once_event] then
for i = 1, #self.events[once_event] do
self.events[once_event][i](...)
end
self.events[once_event] = nil
end
self:cleanUp()
end
function Emitter:cleanUp()
for key, arr in pairs(self.events_to_remove) do
for i = 1, #arr do
for j = 1, #self.events[key] do
if arr[i] == self.events[key][j] then
table.remove(self.events[key], j)
break
end
end
end
end
self.events_to_remove = {}
end
function Emitter:removeListener(event, listener)
if self.events_to_remove[event] then
table.insert(self.events_to_remove[event], listener)
else
self.events_to_remove[event] = { listener }
end
return false
end
function Emitter:once(event, listener)
self:on(pfx_once..event, listener)
end
function Emitter:untilTrue(event, listener, finally)
local function wrapper(...)
local args = listener(...)
if args then
self:removeListener(event, wrapper)
if finally then finally(args, ...) end
end
end
self:on(event, wrapper)
end
function Emitter:removeAllListeners(event)
self.events[event] = nil
self.events[pfx_once..event] = nil
end
return Emitter
|
local _, cfg = ... --export config
local addon, ns = ... --get addon namespace
--not done yet |
local ModExtTable = require("api.ModExtTable")
local IModDataHolder = class.interface("IModDataHolder", { get_mod_data = "function" })
function IModDataHolder:init()
self._mod_data = ModExtTable:new()
end
function IModDataHolder:get_mod_data(mod_id)
return self._mod_data:get_mod_data(mod_id)
end
return IModDataHolder
|
--[[====================================
=
= template list 扩展
=
========================================]]
local CCContainer = tolua_get_class('CCContainer')
local AsyncContainer = tolua_get_class('AsyncContainer')
--模板基类
local SCrollList, SCrollList_Super = tolua_get_class('SCrollList')
-- override
function SCrollList:Create()
return cc.ScrollView:create():CastTo(self):_init(CCContainer)
end
-- override
function SCrollList:_init(ContainerType)
SCrollList_Super._init(self)
self:AddChild('_container', ContainerType:Create())
self._startVisiIndex = nil
self._endVisiIndex = nil
self._lastScrollOffset = nil
self._nNotAutoHideLen = 0
self._container:setAnchorPoint(ccp(0, 1))
self:HandleScrollEvent()
return self
end
-- override
function SCrollList:_registerInnerEvent()
SCrollList_Super._registerInnerEvent(self)
self.newHandler.OnScroll = function()
if self._bScheduleUpVisiRangeNextFrame == nil and self:_canTestVisibility() then
self:UpdateVisibleRangeNextFrame()
end
end
end
-- override
function SCrollList:_canTestVisibility()
if self:GetItemCount() == 0 then
return false
end
if self._lastScrollOffset == nil then
return true
else
local offset = self:getContentOffset()
if self:IsHorzDirection() then
if offset.x > 0 or offset.x < self:minContainerOffset().x then
if self._bScrollToBoundary then
return
else
self._bScrollToBoundary = true
end
else
self._bScrollToBoundary = nil
end
local diff = offset.x - self._lastScrollOffset.x
-- print('x diff', diff)
if diff > 0 then
-- container -> 右
if self:IsLeft2RightOrder() then
return diff > self._checkVisibilityUpperScroll
else
return diff > self._checkVisibilitylowerScroll
end
else
-- container -> 左
if self:IsLeft2RightOrder() then
return -diff > self._checkVisibilitylowerScroll
else
return -diff > self._checkVisibilityUpperScroll
end
end
else
if offset.y > 0 or offset.y < self:minContainerOffset().y then
if self._bScrollToBoundary then
return
else
self._bScrollToBoundary = true
end
else
self._bScrollToBoundary = nil
end
local diff = offset.y - self._lastScrollOffset.y
-- print('y diff', diff)
if diff > 0 then
-- container -> 上
return diff >= self._checkVisibilitylowerScroll
else
-- container -> 下
return -diff >= self._checkVisibilityUpperScroll
end
end
end
end
-- override
function SCrollList:_updateSingleListVisibleRange()
local varLength = self._container:GetVarLength()
if varLength == nil then
return
end
local offset = self:getContentOffset()
local csize = self:getContentSize()
local w, h = self:GetContentSize()
local startLen
local endLen
local curLen = 0
local indent
if self:IsHorzDirection() then
if self:IsLeft2RightOrder() then
startLen = -offset.x - self._container:GetHorzBorder()
else
startLen = csize.width + offset.x - w - self._container:GetHorzBorder()
end
endLen = startLen + w
indent = self._container:GetHorzIndent()
else
startLen = csize.height + offset.y - h - self._container:GetVertBorder()
endLen = startLen + h
indent = self._container:GetVertIndent()
end
startLen = startLen - self._nNotAutoHideLen
endLen = endLen + self._nNotAutoHideLen
local startVisiIndex
local endVisiIndex
local upperScroll
local lowerScroll
for i, v in ipairs(varLength) do
curLen = curLen + v + indent
if startVisiIndex == nil and curLen > startLen then
startVisiIndex = i
upperScroll = v - (curLen - startLen)
end
if endVisiIndex == nil and curLen >= endLen then
endVisiIndex = i
lowerScroll = curLen - endLen
break
end
end
self._startVisiIndex = startVisiIndex or 1
self._endVisiIndex = endVisiIndex or self:GetItemCount()
self._lastScrollOffset = offset
self._checkVisibilityUpperScroll = (upperScroll or 0) + self._nNotAutoHideLen / 4
self._checkVisibilitylowerScroll = (lowerScroll or 0) + self._nNotAutoHideLen / 4
-- print('_updateSingleListVisibleRange', self._startVisiIndex, self._endVisiIndex, self._checkVisibilityUpperScroll, self._checkVisibilitylowerScroll)
return true
end
-- override
function SCrollList:_updateMultiListVisibleRange()
local sz = self._container:GetCtrlSize()
local ctrlW, ctrlH = sz.width, sz.height
local offset = self:getContentOffset()
local csize = self:getContentSize()
local w, h = self:GetContentSize()
local startLen
local endLen
local unitLen
local upperScroll
local lowerScroll
local startVisiIndex
local endVisiIndex
if self:IsHorzDirection() then
unitLen = ctrlW + self._container:GetHorzIndent()
if self:IsLeft2RightOrder() then
startLen = -offset.x - self._container:GetHorzBorder()
else
startLen = csize.width + offset.x - w - self._container:GetHorzBorder()
end
endLen = startLen + w
else
unitLen = ctrlH + self._container:GetVertIndent()
startLen = csize.height + offset.y - h - self._container:GetVertBorder()
endLen = startLen + h
end
startLen = startLen - self._nNotAutoHideLen
endLen = endLen + self._nNotAutoHideLen
upperScroll = startLen % unitLen
startVisiIndex = math.ceil(startLen / unitLen)
lowerScroll = unitLen - endLen % unitLen
endVisiIndex = math.ceil(endLen / unitLen)
local numPerunit = self._container:GetNumPerUnit()
if numPerunit > 1 then
startVisiIndex = numPerunit * (startVisiIndex - 1) + 1
endVisiIndex = numPerunit * endVisiIndex
end
local nMax = self:GetItemCount()
self._startVisiIndex = math.min(math.max(startVisiIndex, 1), nMax)
self._endVisiIndex = math.min(math.max(endVisiIndex, 1), nMax)
self._lastScrollOffset = offset
self._checkVisibilityUpperScroll = upperScroll + self._nNotAutoHideLen / 4
self._checkVisibilitylowerScroll = lowerScroll + self._nNotAutoHideLen / 4
-- print('_updateMultiListVisibleRange', self._startVisiIndex, self._endVisiIndex, self._checkVisibilityUpperScroll, self._checkVisibilitylowerScroll)
end
-- override
function SCrollList:_updateVisibleRange()
if self:GetItemCount() > 0 then
return self:_updateSingleListVisibleRange() or self:_updateMultiListVisibleRange()
end
end
function SCrollList:UpdateVisibleRangeNextFrame()
if self._bScheduleUpVisiRangeNextFrame then
return
end
self._bScheduleUpVisiRangeNextFrame = true
self:DelayCall(0, function()
self._bScheduleUpVisiRangeNextFrame = nil
self:_updateVisibleRange()
end)
end
-- override
function SCrollList:SetContentSize(sw, sh)
local sz = self:CalcSize(sw, sh)
local W, H = self._container:GetContentSize()
if self._container:IsHorzDirection() then
sz.height = H
else
sz.width = W
end
self:setViewSize(sz)
return self:_refreshItemPos()
end
function SCrollList:_refreshItemPos()
local W, H = self:GetContentSize()
local CW, CH = self._container:GetContentSize()
if self._container:IsHorzDirection() then
if H ~= CH then
H = CH
end
else
if W ~= CW then
W = CW
end
end
local ret = CCSize(W, H)
self:setViewSize(ret)
self:setContentSize(CCSize(math.max(CW, W), math.max(CH, H)))
self._container:SetPosition(0, 'i0')
self:UpdateVisibleRangeNextFrame()
return ret
end
function SCrollList:_refreshContainer()
self._container:_refreshItemPos()
self:_refreshItemPos()
end
function SCrollList:SetHorzDirection(bHorz)
if bHorz then
self:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL)
else
self:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
end
self._container:SetHorzDirection(bHorz)
self:_refreshItemPos()
self:EnableMouseWheelAndScroll(bHorz)
end
function SCrollList:IsHorzDirection()
return self._container:IsHorzDirection()
end
function SCrollList:SetNumPerUnit(nNum)
self._container:SetNumPerUnit(nNum)
self:_refreshItemPos()
end
function SCrollList:GetUnitNum()
return self._container:GetUnitNum()
end
function SCrollList:SetHorzBorder(nBorder)
self._container:SetHorzBorder(nBorder)
self:_refreshItemPos()
end
function SCrollList:SetVertBorder(nBorder)
self._container:SetVertBorder(nBorder)
self:_refreshItemPos()
end
function SCrollList:SetHorzIndent(nIndent)
self._container:SetHorzIndent(nIndent)
self:_refreshItemPos()
end
function SCrollList:SetVertIndent(nIndent)
self._container:SetVertIndent(nIndent)
self:_refreshItemPos()
end
function SCrollList:SetLeft2RightOrder(bLeft2RightOrder)
self._container:SetLeft2RightOrder(bLeft2RightOrder)
end
function SCrollList:GetItem(index)
return self._container:GetItem(index)
end
function SCrollList:GetItemCount()
return self._container:GetItemCount()
end
function SCrollList:GetAllItem()
return self._container:GetAllItem()
end
function SCrollList:SetTemplate(templateName, templateInfo, customizeConf)
self._container:SetTemplate(templateName, templateInfo, customizeConf)
end
function SCrollList:SetInitCount(nCurCount, bNotRefresh)
local add = self._container:SetInitCount(nCurCount, bNotRefresh)
if add then
for i, ctrl in ipairs(add) do
self:_set_up_ctrl(ctrl)
end
end
if not bNotRefresh then
self:_refreshItemPos()
end
end
function SCrollList:AddItem(conf, index, bNotRefresh)
local ret = self._container:AddItem(conf, index, bNotRefresh)
self:_set_up_ctrl(ret)
if not bNotRefresh then
self:_refreshItemPos()
end
return ret
end
function SCrollList:AddControl(ctrl, index, bNotRefresh)
local ret = self._container:AddControl(ctrl, index, bNotRefresh)
self:_set_up_ctrl(ret)
if not bNotRefresh then
self:_refreshItemPos()
end
return ret
end
function SCrollList:AddTemplateItem(index, bNotRefresh)
local ret = self._container:AddTemplateItem(index, bNotRefresh)
self:_set_up_ctrl(ret)
if not bNotRefresh then
self:_refreshItemPos()
end
return ret
end
function SCrollList:DeleteAllSubItem()
self._container:DeleteAllSubItem()
self:_refreshItemPos()
end
function SCrollList:DeleteItemIndex(index, bNotRefresh)
self._container:DeleteItemIndex(index, bNotRefresh)
if not bNotRefresh then
self:_refreshItemPos()
end
end
function SCrollList:DeleteItem(item, bNotRefresh)
self._container:DeleteItem(item, bNotRefresh)
if not bNotRefresh then
self:_refreshItemPos()
end
end
function SCrollList:LocatePosByItem(index, duration)
local item = self:GetItem(index)
if not item then
return
end
self:CenterWithNode(item, duration)
end
function SCrollList:GetHorzBorder()
return self._container:GetHorzBorder()
end
function SCrollList:GetVertBorder()
return self._container:GetHorzBorder()
end
function SCrollList:GetHorzIndent()
return self._container:GetHorzIndent()
end
function SCrollList:GetVertIndent()
return self._container:GetVertIndent()
end
function SCrollList:GetCtrlSize()
return self._container:GetCtrlSize()
end
function SCrollList:GetNumPerUnit()
return self._container:GetNumPerUnit()
end
function SCrollList:IsLeft2RightOrder()
return self._container:IsLeft2RightOrder()
end
function SCrollList:SetNotAutoHideLen(len)
self._nNotAutoHideLen = len
end
local AsyncList, AsyncList_Super = tolua_get_class('AsyncList')
-- override
function AsyncList:_init()
AsyncList_Super._init(self, AsyncContainer)
self._bReverseLoadOrder = false
return self
end
-- override
function AsyncList:_registerInnerEvent()
AsyncList_Super._registerInnerEvent(self)
self:_regInnerEvent('OnCreateItem')
end
-- override
function AsyncList:SetInitCount(nCurCount, bNotRefresh)
self._container:SetInitCount(nCurCount, bNotRefresh)
if not bNotRefresh then
self:_refreshItemPos()
end
end
-- override
function AsyncList:AddItem(conf, index, bNotRefresh, callback)
local ret = self._container:AddItem(conf, index, bNotRefresh, callback)
if not bNotRefresh then
self:_refreshItemPos()
end
return ret
end
function AsyncList:SetReverseLoadOrder(bReverse)
self._bReverseLoadOrder = bReverse
end
function AsyncList:IsSingleItemReverseLoadOrder()
return self._bReverseLoadOrder
end
-- override
function AsyncList:_updateVisibleRange()
if self:GetItemCount() == 0 then
return
end
if self._startVisiIndex and self._endVisiIndex then
for i = self._startVisiIndex, self._endVisiIndex do
local ctrl = self._container:GetItem(i)
if tolua_is_obj(ctrl) then
ctrl:setVisible(false)
end
end
end
if not self:_updateSingleListVisibleRange() then
self:_updateMultiListVisibleRange()
end
if self._startVisiIndex and self._endVisiIndex then
for i = self._startVisiIndex, self._endVisiIndex do
local ctrl = self._container:GetItem(i)
if tolua_is_obj(ctrl) then
ctrl:setVisible(true)
end
end
end
self:_doAsyncLoad()
end
function AsyncList:_doAsyncLoad()
local itemCount = self:GetItemCount()
if itemCount == 0 then
return
end
if self._bScheduleLoading == true then
return
end
-- 在 schedule 过程中如果出现减少元素的情况可能会出现以下情况
if self._endVisiIndex > itemCount then
self._endVisiIndex = itemCount
end
local istart, iend, istep
if self._bReverseLoadOrder then
istart = self._endVisiIndex
iend = self._startVisiIndex
istep = -1
else
istart = self._startVisiIndex
iend = self._endVisiIndex
istep = 1
end
local loadedList = {}
local bSingleList = self:GetNumPerUnit() == 1
for i = istart, iend, istep do
if not self._container:IsItemLoaded(i) then
local ok = g_async_task_mgr.do_execute(function()
local item = self._container:DoLoadItem(i)
self:_set_up_ctrl(item)
self.eventHandler:Trigger('OnCreateItem', i, item)
if bSingleList then
if self._bReverseLoadOrder then
table.insert(loadedList, 1, {i, item})
else
table.insert(loadedList, {i, item})
end
end
end)
if not ok then
self._bScheduleLoading = true
self:DelayCall(0.01, function()
self._bScheduleLoading = nil
self:_doAsyncLoad()
end)
break
end
end
end
local diffLen = self._container:OnItemProcessed(loadedList)
if diffLen and diffLen > 0 then
self:_refreshItemPos()
local offset = self:getContentOffset()
if self:IsHorzDirection() then
if not self._bReverseLoadOrder then
offset.x = offset.x - diffLen
end
else
if not self._bReverseLoadOrder then
offset.y = offset.y - diffLen
end
end
self:setContentOffset(offset)
end
end
-- backwards
AsyncList.TestAsyncLoad = AsyncList.UpdateVisibleRangeNextFrame
|
----------------------- istable --------------------------
local function istable(obj)
return obj and (type(obj) == "table")
end
----------------------- isfunction --------------------------
local function isfunction(obj)
return obj and (type(obj) == "function")
end
----------------------- isstring --------------------------
local function isstring(obj)
return obj and (type(obj) == "string")
end
----------------------- extends --------------------------
local function extends(parent)
local child = {}
setmetatable(child, parent)
child.__index = child
child.__super = parent
return child
end
----------------------- embed --------------------------
local function embed(obj, data)
if (istable(obj) and istable(data)) then
for k,v in pairs(data) do
obj[k] = v
end
end
end
----------------------- checkcall --------------------------
local function checkcall(obj, fname, ...)
--print(string.format("checkcall: %s", tostring(obj)))
if (istable(obj) and isstring(fname)) then
local func = obj[fname]
--print(string.format(" func: %s", tostring(func)))
if (isfunction(func)) then
return func(obj, ...)
end
end
end
----------------------- broadcast --------------------------
local broadcast = {}
function broadcast:skill(skill)
if (WeakAuras and WeakAuras.ScanEvents) then
WeakAuras.ScanEvents("SKILLBAR_SKILL_CHANGED", skill)
end
end
function broadcast:clocktick(now)
if (WeakAuras and WeakAuras.ScanEvents) then
WeakAuras.ScanEvents("SKILLBAR_CLOCK_TICK", now)
end
end
----------------------- iterate --------------------------
local function iterate(list, fname, ...)
if (istable(list)) then
--print(string.format("iterate: %s", list.name or tostring(list)))
for _,obj in pairs(list) do
--print(string.format(" obj: %s", tostring(obj)))
checkcall(obj, fname, ...)
end
end
end
----------------------- Skill Bar --------------------------
SkillBar =
{
extends = extends,
embed = embed,
checkcall = checkcall,
iterate = iterate,
broadcast = broadcast,
}
|
-- updated to pass compress mode, mvh 20140126
-- updated to suppress characters like umlaut Jorg 20160609
print('Content-Type: application/xml\n')
local patid = string.gsub(series2, ':.*$', '')
local seriesuid = string.gsub(series2, '^.*:', '')
local q = DicomObject:new()
q.QueryRetrieveLevel = 'IMAGE'
q.PatientID = patid
q.SeriesInstanceUID = seriesuid
q.SOPInstanceUID = ''
q.PatientBirthDate = ''
q.PatientName = ''
q.StudyInstanceUID = ''
q.StudyDescription = ''
q.StudyDate = ''
q.StudyTime = ''
q.SeriesDescription = ''
q.SeriesNumber = ''
q.Modality = ''
q.ImageNumber = ''
r = dicomquery(servercommand('get_param:MyACRNema'), 'IMAGE', q)
-- ascii compliance insert: remove non alphanumeric characters 06/2016
r[0].PatientName =r[0].PatientName:gsub('%W','_')
r[0].StudyDescription =r[0].StudyDescription:gsub('%W','_')
r[0].SeriesDescription = r[0].SeriesDescription:gsub('%W','_')
-- end ascii compliance insert
wt = ""
if compress=='J3' or compress=='j3' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.50"' end
if compress=='J4' or compress=='j4' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.51"' end
if compress=='J5' or compress=='j5' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.53"' end
if compress=='J1' or compress=='j1' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.55"' end
if compress=='J2' or compress=='j2' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.57"' end
if compress=='J1' or compress=='j1' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.70"' end
if compress=='JK' or compress=='jk' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.90"' end
if compress=='JL' or compress=='jl' then wt = ' WadoTransferSyntaxUID="1.2.840.10008.1.2.4.91"' end
local s = DicomObject:new()
print([[
<?xml version="1.0" encoding="utf-8" ?>
<wado_query xmlns= "http://www.weasis.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" wadoURL="]]..webscriptadress..[[" requireOnlySOPInstanceUID="false" overrideDicomTagsList="0x00000000" >
<Patient PatientID="]]..patid..[[" PatientName="]]..r[0].PatientName..[[" PatientBirthDate="]]..r[0].PatientBirthDate..[[" >
<Study StudyInstanceUID="]]..r[0].StudyInstanceUID..[[" StudyDescription="]]..r[0].StudyDescription..[[" StudyDate="]]..r[0].StudyDate..[[" StudyTime="]]..r[0].StudyTime..[[" >
<Series SeriesInstanceUID="]]..r[0].SeriesInstanceUID..[[" SeriesDescription="]]..r[0].SeriesDescription..[[" SeriesNumber="]]..r[0].SeriesNumber..[[" Modality="]]..r[0].Modality..[["]]..wt..[[ >
]])
for i=0, #r-1 do
print([[<Instance SOPInstanceUID="]]..r[i].SOPInstanceUID..[[" InstanceNumber="]]..i..[[" />]])
end
print([[
</Series>
</Study>
</Patient>
</wado_query>
]])
|
-- LICENSE
-- MIT License
-- Copyright (c) 2021 thibaultDup
-- 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.
-- END LICENSE
ESX = nil
localVehicles = {}
localGarages = {}
isInDelivery = false --{5}
playerId = nil
--TEST - gameEvents --------------------------------
-- RegisterNetEvent('onResourceStart')
-- AddEventHandler('onResourceStart', function(resource)
-- print("RESOURCE STARTED !!!!!")
-- end)
--Fin TEST
--Events -------------------------------------------------------------------------------------------------
--Event to get the return of the Event server [ esx_bringIt:GetPersonalCar ]
RegisterNetEvent("esx_bringIt:GetPersonalCar:return")
AddEventHandler("esx_bringIt:GetPersonalCar:return", function(vehicles)
localVehicles = vehicles
end)
--Event to get the return of the Event server [ esx_bringIt:GetPersonalCarInGarage ]
RegisterNetEvent("esx_bringIt:GetPersonalCarInGarage:return")
AddEventHandler("esx_bringIt:GetPersonalCarInGarage:return", function(vehicles)
localVehicles = vehicles
end)
--Event to get the return of the Event server [ esx_bringIt:GetPersonalGarage ]
RegisterNetEvent("esx_bringIt:GetPersonalGarage:return")
AddEventHandler("esx_bringIt:GetPersonalGarage:return", function(garages)
localGarages = garages
end)
--Event called by our server script when a player emmits a call (via gcphone) to 505505 or 505-505 numbers wich will start the script core by calling our [ main() ] function {7}
RegisterNetEvent("esx_bringIt:MechanoCalled")
AddEventHandler("esx_bringIt:MechanoCalled", function()
-- --Sends an NUIMessage to our [ closephone.js ] wich in turn will trigger an NUIcallback from gcphone to close the phone
-- SendNUIMessage({action = 'close'})
--Set the focus to the NUI menu of our script, focus wich is normaly on the gcphone NUI script. To allow player to interact with our mechano menu while the phone is still out.
--SetNuiFocus(true, true)
playerId = PlayerPedId()
Citizen.Wait(2000)
main()
Citizen.Wait(1000)
-- Trigger the Event we add to the [ gcphone/client/client.lua ] wich close the phone after our Menu is displayed
TriggerEvent("gcPhone:closeThePhone")
end)
--Fin Events -------------------------------------------------------------------------------------------------
--Thread[0] Wait to GET the ESX Object -------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(100)
end
end)
--Fin Thread[0] -------------------------------------------------------------------------------------------------
--Thread[1] Main Thread -------------------------------------------------------------------------------------------------
-- Citizen.CreateThread(function()
-- Citizen.Wait(100)
-- displayMenu()
-- --TEST
-- --playerCoordsTest = GetEntityCoords(PlayerPedId())
-- --print(LookForCoordsNearPlayer(playerCoordsTest))
-- --Fin TEST
-- end)
--Fin Thread[1] -------------------------------------------------------------------------------------------------
--Functions -------------------------------------------------------------------------------------------------
--Our main function wich is called by our event [ MechanoCalled ]. This function will launch the script by displaying the menu {7}
function main()
Citizen.Wait(100)
displayMenu()
end
--Function that will display a menu wich includes all the player's car
function displayMenu()
Citizen.Wait(100)
-- --Trigger the server Event that fetch all the parked car of the player in is garages
-- TriggerServerEvent("esx_bringIt:GetPersonalCar")
--TABLE that will contain our menu items
local menuItems = {}
--Temp var to add garages to the list
local garage = ""
--For all the garages in [ esx_garage/config.lua ]
for k,v in pairs(Config.Garages) do
--IsClosed mean Open weirdly
if (v.IsClosed) then
table.insert(menuItems, { ["label"] = k, ["value"] = k })
end
end
--[TO MOVE] Get the coords of the player to later spawn the car beside him
--playerCoords = GetEntityCoords(PlayerPedId())
playerCoords = GetEntityCoords(playerId)
print(playerCoords)
--Call the function that search for a road behind the player to spawn the vehicle and return the coords of the spwan point
spawnVehicleCoords = LookForCoordsNearPlayer(playerCoords)
--TEST
--print(spawnVehicleCoords)
--If the [ LookForCoordsNearPlayer() ] doesn't found any coords on road near the player
if( spawnVehicleCoords == nil ) then
ESX.ShowAdvancedNotification("Mechano", "~b~BringIt" ,"~r~I can't get to you know, try a little later !", "CHAR_MECHANIC")
return
end
-- If variable [ isInDelivery ] is true, that means that the mechano is already in delivery so he isn't reachable {5}
if( isInDelivery == true ) then
ESX.ShowAdvancedNotification("Mechano", "~b~BringIt" ,"~r~I'm already driving a car to you, I cannot duplicate myself !!!", "CHAR_MECHANIC")
return
end
--Close all eventual menu
ESX.UI.Menu.CloseAll()
--Open the Menu [ bringItGarages ]
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItGarages',
{
title = "Your garages",
align = 'top-left',
elements = menuItems
},
function(data, menu)
local action = data.current.value
if (action == "MiltonDrive") then
print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("MiltonDrive")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--TEST -----------
--return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in MiltonDrive",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
Citizen.Wait(500)
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
end, function(data, menu)
menu.close()
end)
elseif (action == "IntegrityWay") then
print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("IntegrityWay")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in IntegrityWay",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
Citizen.Wait(500)
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
end, function(data, menu)
menu.close()
end)
elseif (action == "DidionWay") then
print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("DidionWay")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in DidionWay",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
Citizen.Wait(500)
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
end, function(data, menu)
menu.close()
end)
elseif (action == "VinewoodEstate2650") then
--print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("VinewoodEstate2650")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in VinewoodEstate2650",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
Citizen.Wait(500)
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
end, function(data, menu)
menu.close()
end)
elseif (action == "ImaginationCt265") then
print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("ImaginationCt265")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in ImaginationCt265",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
Citizen.Wait(500)
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
end, function(data, menu)
menu.close()
end)
elseif (action == "SteeleWay1150") then
print("PRESSED")
subMenuItems = {}
--Used to load the global variable [ localVehicle ] with the cars that are in the garage passed in arg1
getCarInGarage("SteeleWay1150")
--TEST
--If the garage is empty no need to add ITEMS and Open the [ bringItCars ] so we close the parent menu and return
if( localVehicles[1] == nil ) then
--print("EMPTY !!")
--ShowNotification : No cars parked in this garage
ESX.ShowNotification("~r~No cars in this garage", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
return
else
--Add entries to the UI Sub Menu [ bringItCars ]
--For each vehicle in the player's garage
for i, field in ipairs(localVehicles) do
for k, vehicleData in pairs(field.vehicle) do
if (k == "model") then
--Add the car to the subMenuCar for this Garage
table.insert(subMenuItems, { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData)), ["value"] = i })
--elements[i] = { ["label"] = string.lower(GetDisplayNameFromVehicleModel(vehicleData.model)), ["value"] = field.id }
end
end
end
end
--Fin TEST
--Close the parent Menu if open
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItGarages')
--Open the sub menu
print("OPEN SUBMENU HERE")
ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'bringItCars',
{
title = "Your cars in SteeleWay1150",
align = 'top-left',
elements = subMenuItems
},
function(data, menu)
vehicleIndex = data.current.value
--Call the function to spawn the vehicle et delete him from the garage
spawnVehicle(vehicleIndex)
--Close the child menu
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
end, function(data, menu)
menu.close()
end)
end
end, function(data, menu)
menu.close()
end)
end
--Function that get all the cars in the garage in arg1
function getCarInGarage(garage)
TriggerServerEvent("esx_bringIt:GetPersonalCarInGarage", garage)
Citizen.Wait(2000)
vehicleProps = {}
--Go through each field stored in the [ localVehicles ] wich are the same as the fields in table [ user_parkings ] but only the one we fetch in the server script {1}
for i, field in ipairs(localVehicles) do
--field.id = the unique id of the DB table entry
--field.garage = garage name
--field.vehicle = table containing all the caracteristics of the vehicle and their value (model,turbo,engine ...)
--The idea here is to parse the [ vehicle ] index of localVehicules into a lua TABLE
for k, vehicleData in pairs(field.vehicle) do
--print(k)
--print(vehicleData)
--table.insert(vehicleProps, {k = vehicleData})
vehicleProps[k] = vehicleData
end
--replace the [ localVehicles.vehicle ] of the local TABLE [ localVehicles ] with a TABLE more suited for LUA
field.vehicle = vehicleProps
vehicleProps = {}
end
end
--Function that spawn the desired vehicle and remove it from the garage he is in
function spawnVehicle(vehicleIndex)
local driverNpc = nil
local _vehicle = nil
local loopSwitch = true
--Spawn a vehicule model of the user and set all its caracteristics as the player's car
ESX.Game.SpawnVehicle(localVehicles[vehicleIndex].vehicle.model, spawnVehicleCoords, 100.0,function(vehicle)
--Add the same modifications as the original player car
ESX.Game.SetVehicleProperties(vehicle, localVehicles[vehicleIndex].vehicle)
_vehicle = vehicle
end)
--Wait for the [ SpawnVehicle ] function to finish (cause Async)
while _vehicle == nil do
Citizen.Wait(5000)
end
--print(_vehicle)
--Allow us to know that the mechano is alreay in delivery
isInDelivery = true
--Create a NPC inside the vehicle, to drive it
RequestModel(-907676309) --Request NPC model
Citizen.Wait(1000) --Wait for the model to load
driverNpc = CreatePedInsideVehicle(_vehicle, 4, -907676309, -1, true, false)
print("DriverNpc :")
print(driverNpc)
Citizen.Wait(2500)
--Add Blip to the NPC so the player can see is position on the map
npcBlip = AddBlipForEntity(driverNpc)
SetBlipSprite(npcBlip, 225)
SetBlipColour(npcBlip, 17)
SetBlipAlpha(npcBlip, 200)
SetBlipFlashes(npcBlip, true)
--Make the NPC drive the car to the player location
--TaskVehicleDriveToCoord(driverNpc, _vehicle, playerCoords.x, playerCoords.y, playerCoords.z, 30.0, 1, _vehicle, 1074528293, 1.0, true) --786603
TaskVehicleDriveToCoordLongrange(driverNpc, _vehicle, playerCoords.x, playerCoords.y, playerCoords.z, 18.0, 1074528293, 5.0)
--ShowNotification saying that vehicle is on is way
ESX.ShowNotification("~b~Your Vehicle is on is way ! (check your map)", true, false, 140)
ESX.UI.Menu.Close('default', GetCurrentResourceName(), 'bringItCars')
--Citizen.Wait(100000)
--Check if the NPC is arrived to the player coords
driverCoords = GetEntityCoords(_vehicle)
while( loopSwitch ) do
--check every 1 sec
Citizen.Wait(1000)
--checking the new driver coords
driverCoords = GetEntityCoords(_vehicle)
--TEST
--print(playerCoords)
--print(driverCoords)
--TEST
--If the vehicle is at 6 units of the player coords on the X or Y unit then quit the loop
if( (playerCoords.x - driverCoords.x >= -20 and playerCoords.x - driverCoords.x <= 20) and (playerCoords.y - driverCoords.y >= -20 and playerCoords.y - driverCoords.y <= 20 ) ) then
loopSwitch = false
--Make the NPC stop progressively when he reaches the player position, so he doesn't drift like crazy
TaskVehicleTempAction(driverNpc, _vehicle, 1, 1000)
--Make the NPC exit the vehicle and flag him as not needed anymore
TaskLeaveAnyVehicle(driverNpc, 0, 256)
--TEST -----------------------
--NPC honk at the player
for i = 1, 60000 do
SoundVehicleHornThisFrame(_vehicle)
end
end
print("On is way")
print(loopSwitch)
end
ESX.ShowAdvancedNotification("Mechano", "~r~BringIt" ,"~b~Your car as arrived, check aroud you", "CHAR_MECHANIC")
--Mechano is not in delivery anymore
isInDelivery = false
Citizen.Wait(2000)
--Make the NPC walk so he doesn't enter back in the car when we let him go with [ RemovePedElegantly() ]
TaskWanderStandard(driverNpc, 10, 10)
Citizen.Wait(2000)
--Flag the NPC as NoLongerNeeded so the game will delete it when he will see fit
--SetPedAsNoLongerNeeded(driverNpc)
RemovePedElegantly(driverNpc)
RemoveBlip(npcBlip)
--Delete the vehicle from the parking table (because the player is summoning it so it is no longer in is garage)
--TriggerServerEvent("esx_bringIt:RemoveCarFromGarage", localVehicles[vehicleIndex].garage, localVehicles[vehicleIndex].id)
print("should be arrived")
end
--Function that search a road near the player actual location
function LookForCoordsNearPlayer(playerCoords)
local noRoadsCounter = 0
local headingBackOfPlayer = 0
--The value of [ spawnpoint ] starts at player coords then will change until we find a point on the road behind the player
local spawnpoint = playerCoords
local headingPlayer = GetEntityHeading(PlayerPedId())
if( headingPlayer < 180) then
headingBackOfPlayer = headingPlayer + 180
else
headingBackOfPlayer = headingPlayer - 180
end
--TEST --------------------------------
--Move the spawnpoint further from the player, so the car will spawn in another street or around another building block
if( headingBackOfPlayer > 0 and headingBackOfPlayer < 90 ) then
spawnpoint = vector3(playerCoords.x - 100, playerCoords.y + 100, playerCoords.z)
elseif( headingBackOfPlayer >= 90 and headingBackOfPlayer < 180 ) then
spawnpoint = vector3(playerCoords.x - 100, playerCoords.y - 100, playerCoords.z)
elseif( headingBackOfPlayer >= 180 and headingBackOfPlayer < 270 ) then
spawnpoint = vector3(playerCoords.x + 100, playerCoords.y + 100, playerCoords.z)
elseif( headingBackOfPlayer >= 270 and headingBackOfPlayer <= 360 ) then
spawnpoint = vector3(playerCoords.x + 100, playerCoords.y + 100, playerCoords.z)
else
--NOTHING
end
--Fin TEST -------------------------------
--pointOnRoad = 1 if player on road else pointOnRoad = false
local pointOnRoad = false
--Changed to true if no point on road are found at 600 units of the player {4}
local notFound = false
--TEST
--print(spawnpoint)
checkCoords = spawnpoint
--Checking different coodrs behind the player to find a road where to spawn the vehicle
while pointOnRoad == false do
--checkCoords = spawnpoint
if( headingBackOfPlayer > 0 and headingBackOfPlayer < 90 ) then
checkCoords = vector3(checkCoords.x - 30,checkCoords.y + 30,checkCoords.z)
elseif( headingBackOfPlayer >= 90 and headingBackOfPlayer < 180 ) then
checkCoords = vector3(checkCoords.x - 30,checkCoords.y - 30,checkCoords.z)
elseif( headingBackOfPlayer >= 180 and headingBackOfPlayer < 270 ) then
checkCoords = vector3(checkCoords.x + 30,checkCoords.y - 30,checkCoords.z)
elseif( headingBackOfPlayer >= 270 and headingBackOfPlayer <= 360 ) then
checkCoords = vector3(checkCoords.x + 30,checkCoords.y + 30,checkCoords.z)
else
--NOTHING
end
--Check to see if our actual [ checkCoords ] is on a road
pointOnRoad = IsPointOnRoad(checkCoords.x,checkCoords.y,checkCoords.z)
--TEST
--print(checkCoords)
--If their is no points on road at 600 units of the player, drop the search {4}
noRoadsCounter = noRoadsCounter + 1
if( noRoadsCounter == 300 ) then
--pointOnRoad = "NOT FOUND !"
notFound = true
pointOnRoad = true
end
end
spawnpoint = checkCoords
--If no point on road are found at 600 units of the player {4}
if( notFound ) then
spawnpoint = nil
end
return spawnpoint
end
--Fin Functions -------------------------------------------------------------------------------------------------
-- [ TODO ] -------------------------------------------------------------------------------------------------
--[GOOD]Implement the SubMenu for the "VinewoodEstate2650" garage and test it (ESX.UI.Menu.Open())
--[GOOD]Make the NPC drive the car to the player location with the function [ TaskVehicleDriveToCoordLongrange ]
--[GOOD] + then make the NPC exit the car, walk away and then deleteHim
--[GOOD]Add the "Vehicle incoming" Notification
--[GOOD]Add the if statement to change the condition of the loop
--[+/- GOOD] Make the NPC horn at the player at arrival
--[GOOD]Send a notif to the player when the [ LookForCoordsNearPlayer() ] function isn't able to find a spwanPoint aroundHim
--[GOOD]Regler le problème du multi spawn de voiture lors du spam ENTER (move the ExitMenu the higher up)
--Faire un system qui annule la livraison si la voiture met trop de temps à arriver
--[GOOD]Delete the car from DB only at the end (move the TriggerEvent to the end of spawn car)
--[GOOD]Implement a system to check if the mechano is already in delivery for this player, if so disable his services (so the player cannot recall for the same car){5}
--[GOOD] Fix the problem of the NPC not spawning inside the vehicule at random times (maybe increase timer)
--[GOOD]Stop the task of the NPC when he arrives to destination before making him exit vehicle, so he doesn't drift and make a mess
--Deal with the fact that the vehicle isn't in the database anymore
--Faire un retour arrière du sub menu au menu si la garage est vide, au cas ou le joueur se trompe ou autre
-- Table[ user_parkings ] champ [ vehicle ] content :
-- test = {"modEngine"=-1,
-- "modTurbo"=false,
-- "modSeats"=-1,
-- "neonColor"=[255,0,255],
-- "modTrimA"=-1,
-- "modSuspension"=-1,
-- "model"=-1216765807,
-- "pearlescentColor"=7,
-- "modDoorSpeaker"=-1,
-- "modBackWheels"=-1,
-- "bodyHealth"=1000.0,
-- "engineHealth"=1000.0,
-- "modRoof"=-1,
-- "modRearBumper"=-1,
-- "modOrnaments"=-1,
-- "xenonColor"=255,
-- "modLivery"=-1,
-- "modAirFilter"=-1,
-- "modDashboard"=-1,
-- "modDial"=-1,
-- "color1"=1,
-- "modFrame"=-1,
-- "modShifterLeavers"=-1,
-- "modAerials"=-1,
-- "color2"=0,
-- "tyreSmokeColor"=[255,255,255],
-- "modVanityPlate"=-1,
-- "fuelLevel"=65.0,
-- "tankHealth"=1000.0,
-- "wheelColor"=156,
-- "modSideSkirt"=-1,
-- "modXenon"=false,
-- "modRightFender"=-1,
-- "modWindows"=-1,
-- "modGrille"=-1,
-- "modArchCover"=-1,
-- "modSteeringWheel"=-1,
-- "windowTint"=-1,
-- "modTransmission"=-1,
-- "modFender"=-1,
-- "extras"={"1"=true,"12"=true,"10"=false},
-- "modExhaust"=-1,
-- "modSmokeEnabled"=false,
-- "plate"="06KMN732",
-- "neonEnabled"=[false,false,false,false],
-- "modHorns"=-1,
-- "modBrakes"=-1,
-- "dirtLevel"=1.2,
-- "modFrontWheels"=-1,
-- "modTrimB"=-1,
-- "modSpeakers"=-1,
-- "modArmor"=-1,
-- "modFrontBumper"=-1,
-- "modAPlate"=-1,
-- "modTank"=-1,
-- "modStruts"=-1,
-- "modEngineBlock"=-1,
-- "modTrunk"=-1,
-- "modPlateHolder"=-1,
-- "modHydrolic"=-1,
-- "plateIndex"=0,
-- "wheels"=7,
-- "modHood"=-1,
-- "modSpoilers"=-1
-- } |
local InCombat = {
}
local OutCombat = {
}
XB.CR:Add(256, '[XB] Priest - Discipline', inCombat, outCombat) |
local Concord = require "libs.concord"
local Input = Concord.component()
return Input
|
class("GetDormThemeListCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot3 = 0
slot4 = nil
if slot1:getBody() and type(slot2) == "table" then
slot4 = slot2.callback
else
pg.ConnectionMgr.GetInstance():Send(19018, {
id = slot2 or 0
}, 19019, function (slot0)
slot1 = getProxy(DormProxy)
if slot0 == 0 then
slot1:initThemes(slot0.theme_list or {})
else
for slot5, slot6 in ipairs(slot0.theme_list) do
slot1:updateTheme(slot6)
end
end
slot1:sendNotification(GAME.GET_DORMTHEME_DONE)
if slot1.sendNotification then
slot2()
end
end)
return
end
end
return class("GetDormThemeListCommand", pm.SimpleCommand)
|
-- * _JOKER_VERSION: 0.0.1 ** Please do not modify this line.
--[[----------------------------------------------------------
Joker - Jokes, Riddles, Fun Facts, & Other Tomfoolery
----------------------------------------------------------
*
* COMPILATION: Your Custom Jokes!
*
* SOURCES:
* It's common practice & kindess to cite any non-original jokes:
* e.g. https://icanhazdadjoke.com,
* Reddit Search,
* Reader's Digest,
* My Friend Bob,
* etc
*
]]--
JokerData = JokerData or {}
JokerData.Config = JokerData.Config or {}
JokerData.Config.CustomJokes = {
label = "My Custom Jokes",
command = "custom",
nsfw = false,
joke = true,
disabled = true
}
JokerData.CustomJokes = {
"Seven days without a pun makes one weak.",
"When does a joke become a dad joke? When it becomes apparent."
}
|
require "vmath"
module(..., package.seeall);
local function AddMembers(classInst, members)
for funcName, func in pairs(members) do
classInst[funcName] = func;
end
end
--2D Viewport.
local View = {}
function View:Size()
return self.pixelSize;
end
--Takes points in viewport space, returns points in pixel space.
--Applies the current transform
function View:Transform(points)
if(vmath.vtype(points) == "table") then
local ret = {};
for i, realPoint in ipairs(points) do
ret[i] = self:Transform(realPoint);
end
return ret;
end
local point = points;
if(self.transform) then
point = self.transform:Matrix():Transform(point)
end;
point = self.matrix:Transform(point);
point = point + self.pixelOffset;
return point;
end
--Takes points in viewport space, returns points in pixel space.
--Does not apply the current transform
function View:ViewportTransform(...)
local transform = self.transform;
self.transform = nil;
local ret = self:Transform(...);
self.transform = transform;
return ret;
end
function View:SetTransform(transform)
self.transform = transform;
end
--Returns the top-right and bottom-left corners of the viewport in viewport space.
function View:Extents()
local halfSize = self.vpSize / 2;
local upperBound = self.vpOrigin + halfSize;
local lowerBound = self.vpOrigin - halfSize;
return upperBound, lowerBound;
end
--Computes what the given viewport length will be in pixel coordinates.
function View:Length(testVal)
local originVec = vmath.vec2(0, 0);
local testVec = vmath.vec2(testVal, 0);
local test1 = self:Transform(originVec);
local test2 = self:Transform(testVec);
return vmath.length(test2 - test1);
end
function Viewport(pixelSize, vpOrigin, vpSize, vpPixelOffset)
local viewport = {};
viewport.pixelSize = vmath.vec2(pixelSize);
viewport.vpOrigin = vmath.vec2(vpOrigin);
viewport.pxCenter = viewport.pixelSize / 2;
if(type(vpSize) == "number") then
vpSize = vmath.vec2(vpSize, vpSize * (pixelSize[2] / pixelSize[1]))
end;
viewport.vpSize = vmath.vec2(vpSize);
if(vpPixelOffset) then
viewport.pixelOffset = vmath.vec2(vpPixelOffset);
else
viewport.pixelOffset = vmath.vec2(0.0, 0.0);
end
local trans = Transform2D();
trans:Translate(viewport.pxCenter);
trans:Scale(viewport.pixelSize);
trans:Scale(vmath.vec2(1, -1));
trans:Scale(1.0 / viewport.vpSize);
trans:Translate(-viewport.vpOrigin);
viewport.matrix = trans;
AddMembers(viewport, View);
return viewport;
end
-- Transform 2D.
local function Identity3()
return vmath.mat3(vmath.vec3{1, 0, 0}, vmath.vec3{0, 1, 0}, vmath.vec3{0, 0, 1});
end
local Trans2D = {}
function Trans2D:Translate(offset)
local trans = Identity3();
trans:SetCol(3, vmath.vec3(offset, 1));
self.currMatrix = self.currMatrix * trans;
end
function Trans2D:Scale(scale)
local scaleMat = Identity3();
scaleMat[1][1] = scale[1];
scaleMat[2][2] = scale[2];
self.currMatrix = self.currMatrix * scaleMat;
end
function Trans2D:Rotate(angleDeg)
local rotation = Identity3();
angleDeg = math.rad(angleDeg);
local sinAng, cosAng = math.sin(angleDeg), math.cos(angleDeg);
rotation[1][1] = cosAng; rotation[2][1] = -sinAng;
rotation[1][2] = sinAng; rotation[2][2] = cosAng;
self.currMatrix = self.currMatrix * rotation;
end
function Trans2D:MultMatrix(matrix)
self.currMatrix = self.currMatrix * matrix;
end
function Trans2D:Push()
if(not self.stack) then
self.stack = {};
self.stack.top = 0;
end
self.stack[self.stack.top + 1] = self.currMatrix;
self.stack.top = self.stack.top + 1;
end
function Trans2D:Pop()
assert(self.stack, "No Push has been called yet.");
assert(self.stack.top > 0, "Matrix stack underflow.");
self.currMatrix = self.stack[self.stack.top];
self.stack.top = self.stack.top - 1;
end
function Trans2D:Identity()
self.currMatrix = Identity3();
end
function Trans2D:Matrix()
return self.currMatrix;
end
function Trans2D:Vector(point)
return vmath.vec2(point);
end
function Trans2D:Transform(points)
if(vmath.vtype(points) == "table") then
local ret = {};
for i, realPoint in ipairs(points) do
ret[i] = self:Transform(realPoint);
end
return ret;
end
return self.currMatrix:Transform(points);
end
function Transform2D()
local transform = {};
transform.currMatrix = Identity3();
AddMembers(transform, Trans2D);
return transform;
end
-- Transform 3D.
local function Identity4()
return vmath.mat4(
vmath.vec4{1, 0, 0, 0},
vmath.vec4{0, 1, 0, 0},
vmath.vec3{0, 0, 1, 0},
vmath.vec3{0, 0, 0, 1});
end
local Trans3D = {}
Trans3D.Push = Trans2D.Push;
Trans3D.Pop = Trans2D.Pop;
function Trans3D:Translate(offset)
local trans = Identity4();
trans:SetCol(4, vmath.vec4(offset, 1));
self.currMatrix = self.currMatrix * trans;
end
function Trans3D:Scale(scale)
local scaleMat = Identity4();
scaleMat[1][1] = scale[1];
scaleMat[2][2] = scale[2];
scaleMat[3][3] = scale[3];
self.currMatrix = self.currMatrix * scaleMat;
end
function Trans3D:RotateX(angleDeg)
local rotation = Identity4();
angleDeg = math.rad(angleDeg);
local sinAng, cosAng = math.sin(angleDeg), math.cos(angleDeg);
rotation[2][2] = cosAng; rotation[3][2] = -sinAng;
rotation[2][3] = sinAng; rotation[3][3] = cosAng;
self.currMatrix = self.currMatrix * rotation;
end
function Trans3D:RotateY(angleDeg)
local rotation = Identity4();
angleDeg = math.rad(angleDeg);
local sinAng, cosAng = math.sin(angleDeg), math.cos(angleDeg);
rotation[1][1] = cosAng; rotation[3][1] = sinAng;
rotation[1][3] = -sinAng; rotation[3][3] = cosAng;
self.currMatrix = self.currMatrix * rotation;
end
function Trans3D:RotateZ(angleDeg)
local rotation = Identity4();
angleDeg = math.rad(angleDeg);
local sinAng, cosAng = math.sin(angleDeg), math.cos(angleDeg);
rotation[1][1] = cosAng; rotation[2][1] = -sinAng;
rotation[1][2] = sinAng; rotation[2][2] = cosAng;
self.currMatrix = self.currMatrix * rotation;
end
Trans3D.MultMatrix = Trans2D.MultMatrix;
Trans3D.Transform = Trans2D.Transform
function Trans3D:Identity()
self.currMatrix = Identity4();
end
function Trans3D:Matrix()
return self.currMatrix;
end
function Trans3D:Vector(point)
return vmath.vec3(point);
end
function Transform3D()
local transform = {};
transform.currMatrix = Identity4();
AddMembers(transform, Trans3D);
return transform;
end
|
ring_onehand = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Onehands Swiftness",
directObjectTemplate = "object/tangible/wearables/ring/aakuan_ring.iff",
craftingValues = {
},
customizationStringNames = {},
customizationValues = {},
skillMods = {
{"onehandmelee_accuracy", 25},
{"onehandmelee_damage", 25},
{"onehandmelee_speed", 25},
{"dodge", 15},
{"counterattack", 15},
}
}
addLootItemTemplate("ring_onehand", ring_onehand)
|
-- Default values
local DEFAULT_FRAME_COUNT = 10
local DEFAULT_BACKGROUND = { r = 255, g = 255, b = 128 }
local DEFAULT_FOREGROUND = { r = 0, g = 0, b = 0 }
local DEFAULT_BORDER = { r = 0, g = 0, b = 0 }
local FONT_SCALE = 1
local FONT_NAME = "arial"
-- Internal vars
local isEventHandled = false
local processTooltips
--
-- Utility functions
--
local function isValidTooltip(tooltip)
if tooltip and isElement(tooltip) and getElementType(tooltip) == "__tooltip" then
return true
else
return false
end
end
local function colorToTable(color)
color = math.floor(color)
local result = {}
result.a = math.floor(color / 16777216)
color = color - (result.a * 16777216)
result.r = math.floor(color / 65536)
color = color - (result.r * 65536)
result.g = math.floor(color / 256)
color = color - (result.g * 256)
result.b = color
return result
end
local function linesIterator(str)
local i,j = 0,0
local _
local finished = false
return function()
if finished then return nil end
i = j + 1
_,j = string.find(str, "\n", i)
if not j then
finished = true
return i, #str
else
return i,j-1
end
end
end
local function getTooltipBestSizeForText(text)
local width
local height
local numlines = 0
for i,j in linesIterator(text) do
local substr = string.sub(text, i, j)
local tempwidth = dxGetTextWidth(substr, FONT_SCALE, FONT_NAME)
if not width or tempwidth > width then
width = tempwidth
end
numlines = numlines + 1
end
height = dxGetFontHeight(FONT_SCALE, FONT_NAME) * numlines
return (width or 0), height
end
--
-- Interface functions
--
function Create(x, y, text, _foreground, _background, _border)
if not x or not y or not text
or type(x) ~= "number" or type(y) ~= "number" or type(text) ~= "string"
then
return false
end
local w, h = guiGetScreenSize()
if x < 0 then x = 0 end
if x > w then x = w end
if y < 0 then y = 0 end
if y > h then y = h end
x = math.floor(tonumber(x))
y = math.floor(tonumber(y))
text = tostring(text)
local foreground
local background
local border
if _foreground and type(_foreground) == "number" then
foreground = colorToTable(_foreground)
else
foreground = DEFAULT_FOREGROUND
end
if _background and type(_background) == "number" then
background = colorToTable(_background)
else
background = DEFAULT_BACKGROUND
end
if _border and type(_border) == "number" then
border = colorToTable(_border)
else
border = DEFAULT_BORDER
end
local newTooltip = createElement("__tooltip")
setElementData(newTooltip, "x", x)
setElementData(newTooltip, "y", y)
setElementData(newTooltip, "text", text)
setElementData(newTooltip, "state", "hidden")
setElementData(newTooltip, "framesToFade", 0)
setElementData(newTooltip, "framesFaded", 0)
setElementData(newTooltip, "background", background)
setElementData(newTooltip, "foreground", foreground)
setElementData(newTooltip, "border", border)
local width, height = getTooltipBestSizeForText(text)
setElementData(newTooltip, "width", width)
setElementData(newTooltip, "height", height)
return newTooltip
end
function FadeIn(tooltip, frames)
if not frames then frames = DEFAULT_FRAME_COUNT end
if type(frames) ~= "number" then
return false
end
if frames < 1 then frames = 1 end
if isValidTooltip(tooltip) then
setElementData(tooltip, "state", "faddingin")
setElementData(tooltip, "framesToFade", math.floor(tonumber(frames)))
setElementData(tooltip, "framesFaded", 0)
if not isEventHandled then
addEventHandler("onClientRender", root, processTooltips)
isEventHandled = true
end
return true
else
return false
end
end
function FadeOut(tooltip, frames)
if not frames then frames = DEFAULT_FRAME_COUNT end
if type(frames) ~= "number" then
return false
end
if frames < 1 then frames = 1 end
if isValidTooltip(tooltip) then
setElementData(tooltip, "state", "faddingout")
setElementData(tooltip, "framesToFade", math.floor(tonumber(frames)))
setElementData(tooltip, "framesFaded", 0)
if not isEventHandled then
addEventHandler("onClientRender", root, processTooltips)
isEventHandled = true
end
return true
else
return false
end
end
function GetState(tooltip)
if isValidTooltip(tooltip) then
return getElementData(tooltip, "state")
else
return false
end
end
function SetPosition(tooltip, x, y)
if isValidTooltip(tooltip)
and x and y
and type(x) == "number" and type(y) == "number"
then
local w, h = guiGetScreenSize()
if x < 0 then x = 0 end
if x > w then x = w end
if y < 0 then y = 0 end
if y > h then y = h end
setElementData(tooltip, "x", math.floor(tonumber(x)))
setElementData(tooltip, "y", math.floor(tonumber(y)))
return true
else
return false
end
end
function GetPosition(tooltip)
if isValidTooltip(tooltip) then
local x = getElementData(tooltip, "x")
local y = getElementData(tooltip, "y")
return x, y
else
return false
end
end
function SetText(tooltip, text)
if isValidTooltip(tooltip) and text and type(text) == "string" then
setElementData(tooltip, "text", tostring(text))
local width, height = getTooltipBestSizeForText(text)
setElementData(tooltip, "width", width)
setElementData(tooltip, "height", height)
return true
else
return false
end
end
function GetText(tooltip)
if isValidTooltip(tooltip) then
return getElementData(tooltip, "text")
else
return false
end
end
--
-- Color setting/getting interface functions
--
local function setTooltipColor(tooltip, colorname, color)
if isValidTooltip(tooltip) and color and type(color) == "number" then
setElementData(tooltip, colorname, colorToTable(color))
return true
else
return false
end
end
local function getTooltipColor(tooltip, colorname)
if isValidTooltip(tooltip) then
local color = getElementData(tooltip, colorname)
return color.r, color.g, color.b
else
return false
end
end
function SetForegroundColor(tooltip, color)
return setTooltipColor(tooltip, "foreground", color)
end
function GetForegroundColor(tooltip)
return getTooltipColor(tooltip, "foreground")
end
function SetBackgroundColor(tooltip, color)
return setTooltipColor(tooltip, "background", color)
end
function GetBackgroundColor(tooltip)
return getTooltipColor(tooltip, "background")
end
function SetBorderColor(tooltip, color)
return setTooltipColor(tooltip, "border", color)
end
function GetBorderColor(tooltip)
return getTooltipColor(tooltip, "border")
end
--
-- processTooltips
-- Event called for every frame to draw with directx the tooltips
-- that should be drawn.
--
processTooltips = function()
local tooltips = getElementsByType("__tooltip")
if #tooltips == 0 then
removeEventHandler("onClientRender", root, processTooltips)
isEventHandled = false
return
end
local existVisibleTooltips = false
for k,tooltip in ipairs(tooltips) do
local state = getElementData(tooltip, "state")
local alpha = false
if state == "visible" then
-- If the state is visible we don't need to calculate any alpha value
alpha = 255
elseif state == "faddingin" then
-- If it's still fadding in we must calculate the tooltip transparency
local framesToFade = getElementData(tooltip, "framesToFade")
local framesFaded = getElementData(tooltip, "framesFaded")
framesFaded = framesFaded + 1
if framesFaded >= framesToFade then
-- When it has finished fadding in, set it as visible so we don't have to
-- calculate the intermediate alpha values
setElementData(tooltip, "state", "visible")
alpha = 255
else
setElementData(tooltip, "framesFaded", framesFaded)
alpha = math.floor(framesFaded * 255 / framesToFade)
end
elseif state == "faddingout" then
-- If it's fadding out we must calculate the tooltip transparency
local framesToFade = getElementData(tooltip, "framesToFade")
local framesFaded = getElementData(tooltip, "framesFaded")
framesFaded = framesFaded + 1
if framesFaded >= framesToFade then
-- When it has finished fadding out, set it as hidden so it won't be checked again
setElementData(tooltip, "state", "hidden")
alpha = false
else
setElementData(tooltip, "framesFaded", framesFaded)
alpha = math.floor(255 - (framesFaded * 255 / framesToFade))
end
end
-- Alpha can be false if the tooltip state is unknown or hidden
if alpha then
local x = getElementData(tooltip, "x")
local y = getElementData(tooltip, "y")
local text = getElementData(tooltip, "text")
local background = getElementData(tooltip, "background")
local foreground = getElementData(tooltip, "foreground")
local border = getElementData(tooltip, "border")
local width = getElementData(tooltip, "width")
local height = getElementData(tooltip, "height")
local borderColor = tocolor(border.r, border.g, border.b, alpha)
local backColor = tocolor(background.r, background.g, background.b, alpha)
local foreColor = tocolor(foreground.r, foreground.g, foreground.b, alpha)
existVisibleTooltips = true
-- Draw the tooltip borders
dxDrawLine(x, y, x + width + 6, y, borderColor, 1, true)
dxDrawLine(x, y + height + 4, x + width + 6, y + height + 4, borderColor, 1, true)
dxDrawLine(x, y, x, y + height + 4, borderColor, 1, true)
dxDrawLine(x + width + 6, y, x + width + 6, y + height + 4, borderColor, 1, true)
-- Draw the tooltip background
dxDrawRectangle(x + 1, y + 1, width + 4, height + 2, backColor, true)
-- Draw the tooltip text
dxDrawText(text, x + 3, y + 2, x + 3 + width, y + 2 + height, foreColor,
FONT_SCALE, FONT_NAME, "left", "top", false, false, true)
end
end
if not existVisibleTooltips then
removeEventHandler("onClientRender", root, processTooltips)
isEventHandled = false
end
end
|
local core = require("apisix.core")
local m_redis = require("apisix.plugins.auth-bios.redis")
local m_init = require("apisix.plugins.auth-bios.init")
local m_ident = require("apisix.plugins.auth-bios.ident")
local m_auth = require("apisix.plugins.auth-bios.auth")
local json = require("cjson")
local ngx_encode_base64 = ngx.encode_base64
local plugin_name = "auth-bios"
local schema = {
type = "object",
properties = {
redis_host = { type = "string" },
redis_port = { type = "integer", default = 6379 },
redis_password = { type = "string" },
redis_timeout = { type = "integer", default = 1000 },
redis_database = { type = "integer", default = 0 },
token_flag = { type = "string", default = "BIOS-Token" },
auth_flag = { type = "string", default = "Authorization" },
date_flag = { type = "string", default = "BIOS-Date" },
host_flag = { type = "string", default = "BIOS-Host" },
protocol_flag = { type = "string", default = "https" },
request_date_offset_ms = { type = "integer", default = 5000 },
context_flag = { type = "string", default = "BIOS-Context" },
cache_resources = { type = "string", default = "bios:iam:resources" },
cache_change_resources = { type = "string", default = "bios:iam:change_resources:" },
cache_change_resources_timer_sec = { type = "integer", default = 30 },
cache_token = { type = "string", default = "bios:iam:token:info:" },
cache_token_exp_sec = { type = "integer", default = 60 },
cache_aksk = { type = "string", default = "bios:iam:app:aksk:" },
cache_aksk_exp_sec = { type = "integer", default = 60 },
},
required = { "redis_host" }
}
local _M = {
version = 0.1,
priority = 5001,
type = 'auth',
name = plugin_name,
schema = schema,
}
function _M.check_schema(conf)
local check_ok, check_err = core.schema.check(schema, conf)
if not check_ok then
core.log.error("Configuration parameter error")
return false, check_err
end
local _, redis_err = m_redis.init(conf.redis_host, conf.redis_port, conf.redis_database, conf.redis_timeout, conf.redis_password, nil, nil)
if redis_err then
core.log.error("Connect redis error", redis_err)
return false, redis_err
end
m_init.init(conf.cache_resources, conf.cache_change_resources, conf.cache_change_resources_timer_sec)
return true
end
function _M.rewrite(conf, ctx)
local ident_code, ident_message = m_ident.ident(conf, ctx)
if ident_code ~= 200 then
return ident_code, ident_message
end
local auth_code, auth_message = m_auth.auth(ctx.ident_info)
if auth_code ~= 200 then
return auth_code, auth_message
end
core.request.set_header(ctx, conf.context_flag, ngx_encode_base64(json.decode({
trace = {
id=ngx.now() .. math.random(10000,99999),
},
ident = {
res_action = ctx.ident_info.resource_action,
res_uri = ctx.ident_info.resource_uri,
app_id = ctx.ident_info.app_id,
tenant_id = ctx.ident_info.tenant_id,
account_id = ctx.ident_info.account_id,
token = ctx.ident_info.token,
token_kind = ctx.ident_info.token_kind,
ak = ctx.ident_info.ak,
roles = ctx.ident_info.roles,
groups = ctx.ident_info.groups,
}
})))
end
return _M |
local thread = require 'bee.thread'
---@class pub_brave
local m = {}
m.type = 'brave'
m.ability = {}
--- 注册成为勇者
function m.register(id)
m.taskpad = thread.channel('taskpad' .. id)
m.waiter = thread.channel('waiter' .. id)
m.id = id
m.start()
end
--- 注册能力
function m.on(name, callback)
m.ability[name] = callback
end
--- 报告
function m.push(name, params)
m.waiter:push(name, params)
end
--- 开始找工作
function m.start()
while true do
local suc, name, id, params = m.taskpad:pop()
if not suc then
-- 找不到工作的勇者,只好睡觉
thread.sleep(0.001)
goto CONTINUE
end
local ability = m.ability[name]
-- TODO
if not ability then
m.waiter:push(id)
log.error('Brave can not handle this work: ' .. name)
goto CONTINUE
end
local suc, res = xpcall(ability, log.error, params)
if not suc then
m.waiter:push(id)
goto CONTINUE
end
m.waiter:push(id, res)
::CONTINUE::
end
end
return m
|
object_tangible_tcg_series7_armor_kit_composite_battleworn = object_tangible_tcg_series7_shared_armor_kit_composite_battleworn:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series7_armor_kit_composite_battleworn, "object/tangible/tcg/series7/armor_kit_composite_battleworn.iff") |
-- ██████╗░██████╗░░█████╗░██████╗░██╗░░░░░███████╗████████╗
-- ██╔══██╗██╔══██╗██╔══██╗██╔══██╗██║░░░░░██╔════╝╚══██╔══╝
-- ██║░░██║██████╔╝██║░░██║██████╔╝██║░░░░░█████╗░░░░░██║░░░
-- ██║░░██║██╔══██╗██║░░██║██╔═══╝░██║░░░░░██╔══╝░░░░░██║░░░
-- ██████╔╝██║░░██║╚█████╔╝██║░░░░░███████╗███████╗░░░██║░░░
-- ╚═════╝░╚═╝░░╚═╝░╚════╝░╚═╝░░░░░╚══════╝╚══════╝░░░╚═╝░░░
-- Refer to our documentation to set up our product properly: https://nicklaus.gitbook.com/droplet/
return {
Stocking = {
Enabled = true,
Group = 14196949,
Whitelisted = {200, 250, 254, 255},
RestrictAmount = false,
MaxDistance = 15
},
Types = {
ClickDetector = true,
ProximityPrompt = false
}
} |
--[[
Copyright 2019 Manticore Games, Inc.
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.
--]]
-- Internal custom properties
local AS = require(script:GetCustomProperty("API"))
local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject()
local TEXT_BOX = script:GetCustomProperty("TextBox"):WaitForObject()
local PROGRESS_BAR = script:GetCustomProperty("ProgressBar"):WaitForObject()
local AMMO_PANEL = script:GetCustomProperty("AmmoPanel"):WaitForObject()
local AMMO_TEXT = script:GetCustomProperty("AmmoText"):WaitForObject()
local MAX_AMMO_TEXT = script:GetCustomProperty("MaxAmmo"):WaitForObject()
local WEAPON_NAME = script:GetCustomProperty("WeaponName"):WaitForObject()
-- User exposed properties
local SHOW_NUMBER = COMPONENT_ROOT:GetCustomProperty("ShowNumber")
local SHOW_MAXIMUM = COMPONENT_ROOT:GetCustomProperty("ShowMaximum")
local SHOW_AMMO = COMPONENT_ROOT:GetCustomProperty("ShowAmmo")
local LOCAL_PLAYER = Game.GetLocalPlayer()
local CURRENT_WEAPON
local AmmoSize = AMMO_TEXT.fontSize
-- Player GetViewedPlayer()
-- Returns which player the local player is spectating (or themselves if not spectating)
function GetViewedPlayer()
local specatatorTarget = AS.GetSpectatorTarget()
if AS.IsSpectating() and specatatorTarget then
return specatatorTarget
end
return LOCAL_PLAYER
end
-- Equipment GetWeapon()
-- Returns weapon that player is using
function GetWeapon(player)
for i,v in ipairs(player:GetEquipment()) do
if v.name ~= "Equipment" then
return v
end
end
end
function Tick(deltaTime)
local player = GetViewedPlayer()
if player then
if (GetWeapon(player) ~= CURRENT_WEAPON) then
CURRENT_WEAPON = GetWeapon(player)
if CURRENT_WEAPON then
WEAPON_NAME.text = CURRENT_WEAPON.name or ""
end
end
if SHOW_AMMO then
local weapon = GetWeapon(player)
if weapon ~= nil then
--while not weapon.clientUserData.MaxAmmo and not weapon.clientUserData.Ammo do Task.Wait() end
if weapon.clientUserData.Ammo then
AMMO_PANEL.visibility = Visibility.FORCE_ON
AMMO_TEXT.fontSize = AmmoSize
AMMO_TEXT.text = tostring(weapon.clientUserData.Ammo)
else
AMMO_TEXT.text = ""
AMMO_PANEL.visibility = Visibility.FORCE_OFF
end
if weapon.clientUserData.MaxAmmo then
AMMO_PANEL.visibility = Visibility.FORCE_ON
MAX_AMMO_TEXT.text = tostring(weapon.clientUserData.MaxAmmo) or weapon.maxAmmo
else
MAX_AMMO_TEXT.text = ""
AMMO_PANEL.visibility = Visibility.FORCE_OFF
end
else
AMMO_TEXT.text = tostring("∞")
MAX_AMMO_TEXT.text = tostring("")
end
else
AMMO_PANEL.visibility = Visibility.FORCE_OFF
end
end
end
-- Initialize
if not SHOW_NUMBER then
TEXT_BOX.visibility = Visibility.FORCE_OFF
end
PROGRESS_BAR.progress = 1
|
-- Because there does not seem to be any way to have a dir automatically added
-- to the Lua packages cpath, and there also does not seem to be a way to get
-- the current project directory, it must be specified here manually.
-- Otherwise, doing "require 'layout'" will fail, because the .dll will not be
-- in search path.
--
-- Edit the projectdir string to be the absolute path of this Stingray project
-- on disk.
local projectdir = 'C:\\Users\\myname\\Documents\\Stingray\\layoutexample\\'
Project = Project or {}
require 'script/lua/flow_callbacks'
local modulespath = projectdir .. 'layoutexample\\modules\\?.dll'
package.cpath = package.cpath .. ';' .. modulespath
Project.level_names = {
empty = "content/levels/empty"
}
-- Can provide a config for the basic project, or it will use a default if not.
local SimpleProject = require 'core/appkit/lua/simple_project'
SimpleProject.config = {
standalone_init_level_name = Project.level_names.empty,
camera_unit = "core/appkit/units/camera/camera",
camera_index = 1,
shading_environment = nil, -- Will override levels that have env set in editor.
create_free_cam_player = false, -- Project will provide its own player.
exit_standalone_with_esc_key = true
}
-- Optional function by SimpleProject after level, world and player is loaded
-- but before lua trigger level loaded node is activated.
function Project.on_level_load_pre_flow()
if not Project.ui_started then
if scaleform then
scaleform.Stingray.load_project_and_scene("ui/layout_test.s2d/layout_test")
end
if GlobalUI then
GlobalUI.start()
end
Project.ui_started = true
end
end
-- Optional function by SimpleProject after loading of level, world and player and
-- triggering of the level loaded flow node.
function Project.on_level_shutdown_post_flow()
end
-- Optional function called by SimpleProject after world update (we will probably want to split to pre/post appkit calls)
function Project.update(dt)
-- I don't want to do this in update() every frame, but not sure where to
-- put it to make it work correctly.
if stingray.Window then
stingray.Window.set_clip_cursor(false)
stingray.Window.set_show_cursor(true)
end
if GlobalUI then
GlobalUI.update(dt)
end
end
-- Optional function called by SimpleProject *before* appkit/world render
function Project.render()
end
-- Optional function called by SimpleProject *before* appkit/level/player/world shutdown
function Project.shutdown()
if Project.ui_started then
if GlobalUI then
GlobalUI.shutdown()
end
Project.ui_started = nil
end
end
return Project
|
local m = require 'pegparser.parser'
local coder = require 'pegparser.coder'
local util = require'pegparser.util'
local parser = [[
-- EXTERNAL DEFINITIONS
translationUnit <- Spacing externalDeclaration+ EOT^ErrEOT
externalDeclaration <- functionDefinition / declaration
functionDefinition <- declarationSpecifiers declarator declarationList? compoundStatemet
declarationList <- declaration+
statement <- labeledStatement / compoundStatemet / expressionStatement / selectionStatement /
iterationStatement / jumpStatement
labeledStatement <- Identifier COLON statement^ErrLabeledStatement /
CASE constantExpression^ErrCaseExpression COLON^ErrCaseColon statement^ErrCaseStatement /
DEFAULT COLON^ErrDefaultColon statement^ErrDefaultStatement
compoundStatemet <- LWING ( declaration / statement )* RWING^ErrCompoundRWing
expressionStatement <- expression? SEMI
selectionStatement <- IF LPAR^ErrIfLPar expression^ErrIfExpression RPAR^ErrIfRPar statement^ErrIfStatement ( ELSE statement^ErrElseStatement)? /
SWITCH LPAR^ErrSwitchLPar expression^ErrSwitchExpression RPAR^ErrSwitchRPar statement^ErrSwitchStatement
iterationStatement <- WHILE LPAR^ErrWhileLPar expression^ErrWhileExpression RPAR^ErrWhileRPar statement^ErrWhileStatement /
DO statement^ErrDoWhileStatement WHILE^ErrDoWhile LPAR^ErrDoWhileLPar expression^ErrDoWhileExpression RPAR^ErrDoWhileRPar SEMI^ErrDoWhileSemi /
FOR LPAR^ErrForLPar expression? SEMI expression? SEMI^ErrForSemi expression? RPAR^ErrForRPar statement^ErrForStatement /
FOR LPAR^ErrForLPar declaration^ErrForDeclaration expression? SEMI^ErrForSemi expression? RPAR^ErrForRPar statement^ErrForStatement
jumpStatement <- GOTO Identifier^ErrGotoId SEMI^ErrGotoSemi /
CONTINUE SEMI^ErrContinueSemi /
BREAK SEMI^ErrBreakSemi /
RETURN expression? SEMI^ErrReturnSemi
declaration <- declarationSpecifiers initDeclaratorList? SEMI
initDeclaratorList <- initDeclarator ( COMMA initDeclarator^ErrInitDeclarator )*
initDeclarator <- declarator ( EQU initializer^ErrInitDeclaratorInitializer )?
constantExpression <- conditionalExpression
conditionalExpression <- logicalORExpression (QUERY expression^ErrConditionalExpression COLON^ErrConditionalExpressionColon logicalORExpression^ErrConditionalExpressionLogicalOR)*
logicalORExpression <- logicalANDExpression (OROR logicalANDExpression^ErrLogicalORExpression)*
logicalANDExpression <- inclusiveORExpression (ANDAND inclusiveORExpression^ErrLogicalANDExpression)*
inclusiveORExpression <- exclusiveORExpression (OR exclusiveORExpression^ErrInclusiveORExpression)*
exclusiveORExpression <- andExpression (HAT andExpression^ErrExclusiveORExpression)*
andExpression <- equalityExpression (AND equalityExpression^ErrAndExpression)*
equalityExpression <- relationalExpression ((EQUEQU / BANGEQU) relationalExpression^ErrEqualityExpression)*
relationalExpression <- shiftExpression ((LE / GE / LT / GT) shiftExpression^ErrRelationalExpression)*
shiftExpression <- additiveExpression ((LEFT / RIGHT) additiveExpression^ErrShiftExpression)*
additiveExpression <- multiplicativeExpression ((PLUS / MINUS) multiplicativeExpression^ErrAdditiveExpression)*
multiplicativeExpression <- castExpression ((STAR / DIV / MOD) castExpression^ErrMultiplicativeExpression)*
castExpression <- (LPAR typeName RPAR)* unaryExpression
unaryExpression <- postfixExpression /
INC unaryExpression /
DEC unaryExpression /
unaryOperator castExpression /
SIZEOF (unaryExpression / LPAR^ErrSizeofLPar typeName^ErrSizeofTypeName RPAR^ErrSizeofRPar )
unaryOperator <- AND / STAR / PLUS / MINUS / TILDA / BANG
postfixExpression <- ( primaryExpression /
LPAR typeName RPAR LWING initializerList^ErrPostFixExpressionInitialiazer COMMA? RWING^ErrPostFixExpressionRWing )
( LBRK expression^ErrPostFixExpression RBRK^ErrPostFixExpressionRBrk /
LPAR argumentExpressionList? RPAR^ErrPostFixExpressionRPar /
DOT Identifier^ErrPostFixExpressionDotIdentifier /
PTR Identifier^ErrPostFixExpressionPtrIdentifier /
INC /
DEC )*
typeName <- specifierQualifierList abstractDeclarator?
initializerList <- designation? initializer (COMMA designation? initializer)*
designation <- designator+ EQU
designator <- LBRK constantExpression RBRK / DOT Identifier
initializer <- assignmentExpression / LWING initializerList^ErrInitializerInitializerList COMMA? RWING^ErrInitializerRWing
argumentExpressionList <- assignmentExpression (COMMA assignmentExpression^ErrArgumentExpressionListAssignmentExpression)*
specifierQualifierList <- ( typeQualifier* typedefName typeQualifier* ) /
( typeSpecifier / typeQualifier )+
typeQualifier <- CONST / RESTRICT / VOLATILE / DECLSPEC LPAR^ErrDeclspecLPar Identifier^ErrDeclspecIdentifier RPAR^ErrDeclspecRPar
typedefName <- Identifier
typeSpecifier <- VOID / CHAR / SHORT / INT / LONG / FLOAT / DOUBLE / SIGNED / UNSIGNED /
BOOL / COMPLEX / structOrUnionSpecifier / enumSpecifier
structOrUnionSpecifier <- structOrUnion ( Identifier? LWING structDeclaration+^ErrStructOrUnionSpecifierStructDeclaration RWING^ErrStructOrUnionSpecifierRWing / Identifier^ErrStructOrUnionSpecifierIdentifier )
enumSpecifier <- ENUM ( Identifier? LWING enumeratorList^ErrEnumSpecifierEnumeratorList COMMA? RWING^ErrEnumSpecifierRWing / Identifier^ErrEnumSpecifierIdentifier )
enumeratorList <- enumerator (COMMA enumerator)*
enumerator <- EnumerationConstant (EQU constantExpression^ErrEnumeratorConstantExpression)?
structOrUnion <- STRUCT / UNION
structDeclaration <- specifierQualifierList structDeclaratorList^ErrStructDeclarationStructDeclaratorList SEMI^ErrStructDeclarationSemi
structDeclaratorList <- structDeclarator (COMMA structDeclarator^ErrStructDeclarationListAfterComma)*
structDeclarator <- declarator? COLON constantExpression / declarator
declarator <- pointer? directDeclarator
pointer <- ( STAR typeQualifier* )+
directDeclarator <- ( Identifier / LPAR declarator RPAR)
( LBRK typeQualifier* assignmentExpression? RBRK
/ LBRK STATIC typeQualifier* assignmentExpression^ErrDirectDeclaratorAssignmentExpression RBRK^ErrDirectDeclaratorRBrk
/ LBRK typeQualifier+ STATIC assignmentExpression^ErrDirectDeclaratorAssignmentExpression RBRK^ErrDirectDeclaratorRBrk
/ LBRK typeQualifier* STAR RBRK^ErrDirectDeclaratorRBrk
/ LPAR parameterTypeList RPAR
/ LPAR identifierList? RPAR^ErrDirectDeclaratorRPar )*
parameterTypeList <- parameterList (COMMA ELLIPSIS)?
identifierList <- Identifier (COMMA Identifier^ErrIdentifierListIdentifier)*
parameterList <- parameterDeclaration (COMMA parameterDeclaration)*
parameterDeclaration <- declarationSpecifiers ( declarator / abstractDeclarator )?
declarationSpecifiers <- (( storageClassSpecifier / typeQualifier / functionSpecifier )* typedefName ( storageClassSpecifier / typeQualifier / functionSpecifier )*) /
( storageClassSpecifier / typeSpecifier / typeQualifier / functionSpecifier )+
abstractDeclarator <- pointer? directAbstractDeclarator / pointer
directAbstractDeclarator <- ( LPAR abstractDeclarator RPAR^ErrDirectAbstractDeclarationRPar /
LBRK (assignmentExpression / STAR)? RBRK^ErrDirectAbstractDeclarationRBrk /
LPAR parameterTypeList? RPAR^ErrDirectAbstractDeclarationRPar )
( LBRK (assignmentExpression / STAR)? RBRK^ErrDirectAbstractDeclarationRBrk
/ LPAR parameterTypeList? RPAR^ErrDirectAbstractDeclarationRPar )*
storageClassSpecifier <- TYPEDEF / EXTERN / STATIC / AUTO / REGISTER /
ATTRIBUTE LPAR^ErrAttributeLPar LPAR^ErrAttributeLPar (!RPAR .)* RPAR^ErrAttributeRPar RPAR^ErrAttributeRPar
functionSpecifier <- INLINE / STDCALL
primaryExpression <- Identifier / Constant / StringLiteral / LPAR expression RPAR^ErrPrimatyExpressionRPar
expression <- assignmentExpression (COMMA assignmentExpression)*
assignmentExpression <- unaryExpression assignmentOperator assignmentExpression^ErrAssignmentExpression / conditionalExpression
assignmentOperator <- EQU / STAREQU / DIVEQU / MODEQU / PLUSEQU / MINUSEQU / LEFTEQU /
RIGHTEQU / ANDEQU / HATEQU / OREQU
-- Lexical Elements
StringLiteral <- '"' (!'"' .)* '"'^ErrStringLiteral Spacing
Spacing <- ( LongComment / LineComment / Pragma / %nl)*
COMMENT <- LongComment / LineComment
LongComment <- "/*" (!"*/" .)* "*/"
LineComment <- "//" (!%nl .)*
Pragma <- "#" (!%nl .)*
-- Identifiers
Identifier <- !Keyword IdNondigit IdChar* Spacing
IdChar <- [a-z] / [A-Z] / [0-9]
IdNondigit <- [a-z] / [A-Z]
-- Constants
Constant <- FloatConstant / IntegerConstant / EnumerationConstant / CharacterConstant
FloatConstant <- DecimalFloatConstant Spacing
DecimalFloatConstant <- Fraction / [0-9]+
Fraction <- [0-9]* "." [0-9]+ / [0-9]+ "."
IntegerConstant <- DecimalConstant Spacing
DecimalConstant <- [1-9][0-9]*
EnumerationConstant <- Identifier
CharacterConstant <- "L"? "'" Char* "'"^ErrChar Spacing
Char <- [a-z] / [A-Z] / !"'" .
--Keywords
Keyword <- ( "auto" / "break" / "case" / "char" / "const" / "continue" / "default" / "double" /
"do" / "else" / "enum" / "extern" / "float" / "for" / "goto" / "if" / "int" /
"inline" / "long" / "register" / "restrict" / "return" / "short" / "signed" /
"sizeof" / "static" / "struct" / "switch" / "typedef" / "union" / "unsigned" /
"void" / "volatile" / "while" / "_Bool" / "_Complex" / "_Imaginary" / "_stdcall" /
"__declspec" / "__attribute__" ) !IdChar
AUTO <- "auto" !IdChar Spacing
BREAK <- "break" !IdChar Spacing
CASE <- "case" !IdChar Spacing
CHAR <- "char" !IdChar Spacing
CONST <- "const" !IdChar Spacing
CONTINUE <- "continue" !IdChar Spacing
DEFAULT <- "default" !IdChar Spacing
DOUBLE <- "double" !IdChar Spacing
DO <- "do" !IdChar Spacing
ELSE <- "else" !IdChar Spacing
ENUM <- "enum" !IdChar Spacing
EXTERN <- "extern" !IdChar Spacing
FLOAT <- "float" !IdChar Spacing
FOR <- "for" !IdChar Spacing
GOTO <- "goto" !IdChar Spacing
IF <- "if" !IdChar Spacing
INT <- "int" !IdChar Spacing
INLINE <- "inline" !IdChar Spacing
LONG <- "long" !IdChar Spacing
REGISTER <- "register" !IdChar Spacing
RESTRICT <- "restrict" !IdChar Spacing
RETURN <- "return" !IdChar Spacing
SHORT <- "short" !IdChar Spacing
SIGNED <- "signed" !IdChar Spacing
SIZEOF <- "sizeof" !IdChar Spacing
STATIC <- "static" !IdChar Spacing
STRUCT <- "struct" !IdChar Spacing
SWITCH <- "switch" !IdChar Spacing
TYPEDEF <- "typedef" !IdChar Spacing
UNION <- "union" !IdChar Spacing
UNSIGNED <- "unsigned" !IdChar Spacing
VOID <- "void" !IdChar Spacing
VOLATILE <- "volatile" !IdChar Spacing
WHILE <- "while" !IdChar Spacing
BOOL <- "_Bool" !IdChar Spacing
COMPLEX <- "_Complex" !IdChar Spacing
STDCALL <- "_stdcall" !IdChar Spacing
DECLSPEC <- "__declspec" !IdChar Spacing
ATTRIBUTE <- "__attribute__" !IdChar Spacing
-- Punctuators
LBRK <- "[" Spacing
RBRK <- "]" Spacing
LPAR <- "(" Spacing
RPAR <- ")" Spacing
LWING <- "{" Spacing
RWING <- "}" Spacing
DOT <- "." Spacing
PTR <- "->" Spacing
INC <- "++" Spacing
DEC <- "--" Spacing
AND <- "&" !"&" Spacing
STAR <- "*" !"=" Spacing
PLUS <- "+" !"+=" Spacing
MINUS <- "-" !"\-=>" Spacing
TILDA <- "~" Spacing
BANG <- "!" !"=" Spacing
DIV <- "/" !"=" Spacing
MOD <- "%" !"=>" Spacing
LEFT <- "<<" !"=" Spacing
RIGHT <- ">>" !"=" Spacing
LT <- "<" !"=" Spacing
GT <- ">" !"=" Spacing
LE <- "<=" Spacing
GE <- ">=" Spacing
EQUEQU <- "==" Spacing
BANGEQU <- "!=" Spacing
HAT <- "^" !"=" Spacing
OR <- "|" ![=|] Spacing
ANDAND <- "&&" Spacing
OROR <- "||" Spacing
QUERY <- "?" Spacing
COLON <- ":" !">" Spacing
SEMI <- ";" Spacing
ELLIPSIS <- "..." Spacing
EQU <- "=" !"=" Spacing
STAREQU <- "*=" Spacing
DIVEQU <- "/=" Spacing
MODEQU <- "%=" Spacing
PLUSEQU <- "+=" Spacing
MINUSEQU <- "-=" Spacing
LEFTEQU <- "<<=" Spacing
RIGHTEQU <- ">>=" Spacing
ANDEQU <- "&=" Spacing
HATEQU <- "^=" Spacing
OREQU <- "|=" Spacing
COMMA <- "," Spacing
EOT <- !.
]]
g, lab, pos = m.match(parser)
print(g, lab, pos)
--gerar o parser
local p = coder.makeg(g)
local dir = lfs.currentdir() .. '/yes/'
util.testYes(dir, 'c', p)
dir = lfs.currentdir() .. '/yes2/'
util.testYes(dir, 'c', p)
dir = lfs.currentdir() .. '/no/'
util.testNo(dir, 'c', p)
print("\nStrict")
dir = lfs.currentdir() .. '/no-strict/'
util.testNo(dir, 'c', p, 'strict')
|
object_tangible_event_perk_halloween_skull_candle_02 = object_tangible_event_perk_shared_halloween_skull_candle_02:new {
}
ObjectTemplates:addTemplate(object_tangible_event_perk_halloween_skull_candle_02, "object/tangible/event_perk/halloween_skull_candle_02.iff")
|
pointcloud.Projection = pointcloud.Projection or {}
pointcloud.Projection.Key = CreateClientConVar("pointcloud_projection_key", KEY_J, true, true)
pointcloud.Projection.Scale = CreateClientConVar("pointcloud_projection_scale", "0.01", true, false)
pointcloud.Projection.Mode = CreateClientConVar("pointcloud_projection_mode", POINTCLOUD_MODE_CUBE, true, false)
pointcloud.Projection.ColorRed = CreateClientConVar("pointcloud_projection_color_r", "0", true, false)
pointcloud.Projection.ColorGreen = CreateClientConVar("pointcloud_projection_color_g", "161", true, false)
pointcloud.Projection.ColorBlue = CreateClientConVar("pointcloud_projection_color_b", "255", true, false)
pointcloud.Projection.DrawIndex = pointcloud.Projection.DrawIndex or 0
pointcloud.Projection.RenderTarget = GetRenderTarget("pointcloud_projection", 1920, 1080, true)
local sprite = Material("sprites/gmdm_pickups/light")
pointcloud.Input:AddHandler("projection_toggle", pointcloud.Projection.Key, function()
pointcloud.Projection:Toggle()
end)
function pointcloud.Projection:Clear()
self.DrawIndex = 0
self.Position = nil
end
local function shuffle(tab)
for i = #tab, 2, -1 do
local j = math.random(i)
tab[i], tab[j] = tab[j], tab[i]
end
end
function pointcloud.Projection:Toggle()
if self.Position then
self.Position = nil
else
local vec = LocalPlayer():GetEyeTrace().HitPos
self.Position = vec
self.IndexList = {}
for i = 1, #pointcloud.Data.PointList do
self.IndexList[i] = i
end
shuffle(self.IndexList)
end
self.Stored = nil
end
function pointcloud.Projection:AddPoint(index)
if not self.Position then
return
end
self.IndexList[#self.IndexList + 1] = index
end
function pointcloud.Projection:Draw()
local start = SysTime()
local pData = pointcloud.Data
local resolution = pointcloud:GetResolution()
local scale = self.Scale:GetFloat()
local lp = LocalPlayer()
local lpos = lp:EyePos()
local lang = lp:EyeAngles()
local lfov = lp:GetFOV()
local clear = not self.Stored or (self.Stored.Pos != lpos) or (self.Stored.Ang != lang) or (self.Stored.FOV != lfov)
if not self.Stored then
self.Stored = {
Pos = lpos,
Ang = lang,
FOV = lfov
}
end
if clear then
render.PushRenderTarget(self.RenderTarget)
render.Clear(0, 0, 0, 0, true, true)
render.PopRenderTarget()
self.DrawIndex = 0
end
local mode = self.Mode:GetInt()
local bounds = game.GetWorld():GetModelBounds()
pointcloud.Performance:UpdateBudget("Projection")
cam.Start3D()
local size = resolution * scale * 0.5
local mins = Vector(-size, -size, -size)
local maxs = -mins
if mode == POINTCLOUD_MODE_CUBE then
render.SetColorMaterial()
render.OverrideDepthEnable(true, true)
render.OverrideAlphaWriteEnable(true, true)
else
render.SetMaterial(sprite)
end
render.PushRenderTarget(self.RenderTarget)
while pointcloud.Performance:HasBudget("Projection") do
local time = SysTime()
if self.DrawIndex >= #self.IndexList then
break
end
self.DrawIndex = self.DrawIndex + 1
local index = self.IndexList[self.DrawIndex]
local vec = pData:FromData(pData.PointList[index][1])
vec.z = vec.z - bounds.z
local col = pData.PointList[index][2]:ToColor()
if mode == POINTCLOUD_MODE_CUBE then
render.DrawBox(self.Position + (vec * scale), angle_zero, mins, maxs, col)
else
if mode == POINTCLOUD_MODE_HOLOGRAM then
col = Color(self.ColorRed:GetInt(), self.ColorGreen:GetInt(), self.ColorBlue:GetInt())
else
local hue, sat = ColorToHSV(col)
col = HSVToColor(hue, sat, 1)
end
render.DrawSprite(self.Position + (vec * scale), size * 4, size * 4, col)
end
pointcloud.Performance:AddSample("Projection", SysTime() - time)
end
render.PopRenderTarget()
if mode == POINTCLOUD_MODE_CUBE then
render.OverrideDepthEnable(false)
render.OverrideAlphaWriteEnable(false)
end
cam.End3D()
pointcloud.Material:SetTexture("$basetexture", self.RenderTarget)
cam.Start2D()
if mode != POINTCLOUD_MODE_CUBE then
render.OverrideBlend(true, BLEND_SRC_COLOR, BLEND_ONE, BLENDFUNC_ADD, BLEND_SRC_ALPHA, BLEND_DST_ALPHA, BLENDFUNC_SUBTRACT)
end
surface.SetDrawColor(255, 255, 255)
surface.SetMaterial(pointcloud.Material)
surface.DrawTexturedRect(0, 0, ScrW(), ScrH())
if mode != POINTCLOUD_MODE_CUBE then
render.OverrideBlend(false)
end
cam.End2D()
self.Stored = {
Pos = lpos,
Ang = lang,
FOV = lfov
}
pointcloud.Debug.ProjectionTime = SysTime() - start
end
|
--More Shiny bob!
data:extend({
{
type = "item-subgroup",
name = "msb-lighted-poles-list-first",
group = "logistics",
order = "d[poles]-a[poles]-b",
},
{
type = "item-subgroup",
name = "msb-lighted-poles-list-second",
group = "logistics",
order = "d[poles]-b[poles]-b",
},
{
type = "item-subgroup",
name = "msb-lighted-poles-list-third",
group = "logistics",
order = "d[poles]-c[poles]-b",
},
})
if data.raw["item"]["lighted-small-electric-pole"] then
data.raw["item"]["lighted-small-electric-pole"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-small-electric-pole"].order = "a[poles]-01[lighted-small-electric-pole]"
end
if data.raw["item"]["lighted-small-iron-electric-pole"] then
data.raw["item"]["lighted-small-iron-electric-pole"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-small-iron-electric-pole"].order = "a[poles]-02[lighted-small-electric-pole]"
end
if data.raw["item"]["lighted-medium-electric-pole"] then
data.raw["item"]["lighted-medium-electric-pole"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-medium-electric-pole"].order = "a[poles]-03[lighted-medium-electric-pole]"
end
if data.raw["item"]["lighted-medium-electric-pole-2"] then
data.raw["item"]["lighted-medium-electric-pole-2"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-medium-electric-pole-2"].order = "a[poles]-04[lighted-medium-electric-pole]"
end
if data.raw["item"]["lighted-medium-electric-pole-3"] then
data.raw["item"]["lighted-medium-electric-pole-3"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-medium-electric-pole-3"].order = "a[poles]-05[lighted-medium-electric-pole]"
end
if data.raw["item"]["lighted-medium-electric-pole-4"] then
data.raw["item"]["lighted-medium-electric-pole-4"].subgroup = "msb-lighted-poles-list-first"
data.raw["item"]["lighted-medium-electric-pole-4"].order = "a[poles]-06[lighted-medium-electric-pole]"
end
if data.raw["item"]["lighted-bi-big-wooden-pole"] then
data.raw["item"]["lighted-bi-big-wooden-pole"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-bi-big-wooden-pole"].order = "a[poles]-01[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-bi-huge-wooden-pole"] then
data.raw["item"]["lighted-bi-huge-wooden-pole"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-bi-huge-wooden-pole"].order = "a[poles]-02[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-big-electric-pole"] then
data.raw["item"]["lighted-big-electric-pole"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-big-electric-pole"].order = "a[poles]-03[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-big-electric-pole-2"] then
data.raw["item"]["lighted-big-electric-pole-2"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-big-electric-pole-2"].order = "a[poles]-04[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-big-electric-pole-3"] then
data.raw["item"]["lighted-big-electric-pole-3"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-big-electric-pole-3"].order = "a[poles]-05[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-big-electric-pole-4"] then
data.raw["item"]["lighted-big-electric-pole-4"].subgroup = "msb-lighted-poles-list-second"
data.raw["item"]["lighted-big-electric-pole-4"].order = "a[poles]-06[lighted-big-electric-pole]"
end
if data.raw["item"]["lighted-floating-electric-pole"] then
data.raw["item"]["lighted-floating-electric-pole"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-floating-electric-pole"].order = "a[poles]-01[lighted-substation]"
end
if data.raw["item"]["lighted-bi-large-substation"] then
data.raw["item"]["lighted-bi-large-substation"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-bi-large-substation"].order = "a[poles]-06[lighted-substation]"
data.raw["recipe"]["lighted-bi-large-substation"].subgroup = "msb-lighted-poles-list-third"
data.raw["recipe"]["lighted-bi-large-substation"].order = "a[poles]-02[lighted-substation]"
end
if data.raw["item"]["lighted-substation"] then
data.raw["item"]["lighted-substation"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-substation"].order = "a[poles]-03[lighted-substation]"
end
if data.raw["item"]["lighted-substation-2"] then
data.raw["item"]["lighted-substation-2"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-substation-2"].order = "a[poles]-04[lighted-substation]"
end
if data.raw["item"]["lighted-substation-3"] then
data.raw["item"]["lighted-substation-3"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-substation-3"].order = "a[poles]-05[lighted-substation]"
end
if data.raw["item"]["lighted-substation-4"] then
data.raw["item"]["lighted-substation-4"].subgroup = "msb-lighted-poles-list-third"
data.raw["item"]["lighted-substation-4"].order = "a[poles]-06[lighted-substation]"
end |
fx_version 'cerulean'
game 'gta5'
name 'rr_notify'
description 'Simple notification script'
version '1.0'
url 'https://github.com/RoleplayRevisited/rr_notify'
author 'RoleplayRevisted - Kevintjuhz'
client_scripts {
'client.lua'
}
ui_page 'html/index.html'
files {
'html/index.html',
'html/tata.js',
'html/index.js'
}
|
array_cifre = {};
array_temp = {};
array_value = {};
array_out = {};
order = {};
value = {}
stampa = 10;
array_cifre[1] = math.random(5) + 4;
array_cifre[2] = math.random(4);
array_cifre[3] = 0;
index = 0;
for i = 1,3 do
if(array_cifre[i] ~= 0) then
sub1 = array_cifre[i];
for j = 1,3 do
sub2 = sub1 * 10 + array_cifre[j];
for k = 1,3 do
index = index + 1;
array_temp[index] = sub2 * 10 + array_cifre[k];
end
end
end
end
order = lib.math.argsort(array_temp);
int = 1;
array_out[1] = array_temp[order[1]];
for i = 2,index do
if (int < stampa) then
if (array_temp[order[i]] ~= array_out[int] ) then
int = int + 1;
array_out[int] = array_temp[order[i]];
end
end
end
array_value = lib.math.random_shuffle(array_out);
for i = 1, int do
array_out[i] = array_out[i] / 100
array_value[i] = array_value[i] / 100
end
for i = 1, int do
value[i] = lib.dec_to_str(array_value[i])
end
|
return function()
return Board and Board:GetSize() == Point(6, 6)
end |
cfg.table("Person", function(tb)
tb.sqls.Add = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
-- cfg.params函数用于遍历获取SqlParameters的key或者value,函数中的参数说明:
-- (Func<string, string, string, string, string, ICollection<string>, object>)
-- (type, sqlkey, prefix, suffix, ignores, separate)
-- type: 操作类型,目前有
-- pair.join / pair.join.notnull (遍历SqlParameters中的key-value.notnull为获取value不为null的SqlParameter(包括string不为empty的))
-- keys.join / keys.join.notnull (遍历SqlParameters中的key, .notnull为获取value不为null的SqlParameter(包括string不为empty的))
-- vals.join / vals.join.notnull (遍历SqlParameters中的value, .notnull为获取value不为null的SqlParameter(包括string不为empty的))
-- pair / pair.notnull(获取所有SqlParameters中的key-value)
-- keys / keys.notnull(获取所有SqlParameters中的key)
-- vals / vals.notnull(获取所有SqlParameters中的val)
-- count / count.notnull(获取所有SqlParameters的个数)
-- clear / clear.null(用于清除所有的SqlParameters, .null为清除value为null的SqlParameter(包括string为empty的))
-- sqlkey: 传递lua sql函数的第一个参数(sk),用于获取SqlParameters
-- ignores: 需要忽略的key
-- prefix: 每个key的前缀(pair / join的时候使用)
-- suffix: 每个key的后缀(pair / join的时候使用)
-- separate: pair-pair / key-key / val-val之间的分隔符,默认为","(join的时候使用)
return "insert into Person(" .. cfg.params("keys.join", sk) .. ") values(" .. cfg.params("keys.join", sk, "@") .. ")"
--最后生成:return "insert into Person(name, birthday, addrid) values(@name, @birthday, @addrid)"
end
tb.sqls.Add1 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person("
.. cfg.params("keys.join", sk, " ", " ", ",", {"birthday", "addrid"})
.. ") values("
.. cfg.params("vals.join", sk, "'", "'", ",", {"birthday", "addrid"})
.. ")"
cfg.param("del", sk, "addrid"); --移除SqlParameter
return sql;
end
tb.sqls.Add11 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person("
.. cfg.params("keys.join.notnull", sk, " ", " ")
.. ") values("
.. cfg.params("keys.join.notnull", sk, "@", nil, ",")
.. ")"
cfg.params("clear.null", sk); --清除值为null的SqlParameter
return sql;
end
tb.sqls.Add12 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person("
.. cfg.params("keys.join.notnull", sk, " ", " ", nil, {"birthday"})
.. ",addrid) values("
.. cfg.params("vals.join.notnull", sk, "'", "'", ",", {"birthday"})
.. "," .. cfg.params("count", sk) --这里为了测试count而已
.. ")"
cfg.params("clear", sk, nil, nil, nil, {"birthday"}); --清除所有SqlParameter
return sql;
end
tb.sqls.Add13 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person("
.. cfg.params("keys.join.notnull", sk, " ", " ")
.. ",addrid) values("
.. cfg.params("vals.join.notnull", sk, "'", "'", ",")
.. "," .. cfg.params("count.notnull", sk) --这里为了测试count而已
.. ")"
cfg.params("clear", sk); --清除所有SqlParameter
return sql;
end
tb.sqls.Add2 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person(";
--使用lua遍历keys
local keys = cfg.params("keys", sk, nil, nil, nil, {"birthday"}); --忽略birthday的
local bsplit = false;
for k,v in pairs(keys) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. v;
end
sql = sql .. ") values(";
--使用lua遍历vals(注意,lua中并不支持DateTime / Guid等C#类型,可能会抛异常,因此应该使用cfg.params("vals.join", sk),这里只是演示而已)
local vals = cfg.params("vals", sk, nil, nil, nil, {"birthday"});
bsplit = false;
for k,v in pairs(vals) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. "'" .. v .. "'";
end
sql = sql .. ")";
cfg.params("clear", sk); --清理所有的SqlParameter
return sql;
end
tb.sqls.Add21 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person(";
--使用lua遍历keys
local keys = cfg.params("keys.notnull", sk, nil, nil, nil, {"birthday"}); --忽略birthday的
local bsplit = false;
for k,v in pairs(keys) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. v;
end
sql = sql .. ") values(";
--使用lua遍历vals(注意,lua中并不支持DateTime / Guid等C#类型,可能会抛异常,因此应该使用cfg.params("vals.join", sk),这里只是演示而已)
local vals = cfg.params("vals.notnull", sk, nil, nil, nil, {"birthday"});
bsplit = false;
for k,v in pairs(vals) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. "'" .. v .. "'";
end
sql = sql .. ")";
cfg.params("clear", sk); --清理所有的SqlParameter
return sql;
end
tb.sqls.Add3 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "insert into Person(";
--使用lua遍历keys
local keys = cfg.params("keys", sk);
local bsplit = false;
for k,v in pairs(keys) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. v;
end
sql = sql .. ") values(";
--使用lua遍历vals(注意,lua中并不支持DateTime / Guid等C#类型,可能会抛异常,因此应该使用cfg.params("vals.join", sk),这里只是演示而已)
local vals = cfg.params("vals", sk);
bsplit = false;
for k,v in pairs(vals) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. "'" .. v .. "'";
end
sql = sql .. ")";
cfg.params("clear", sk); --清理所有的SqlParameter
return sql;
end
----------------------------------------update start
tb.sqls.Update = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "update Person set "
--.. cfg.params("pair.join", sk, " ", " ", ' , ', { "name" })
.. cfg.params("pair.join", sk)
.. " where name=@name";
return sql;
end
tb.sqls.Update1 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "update Person set "
--.. cfg.params("pair.join.notnull", sk, " ", " ", ' , ', { "name" })
.. cfg.params("pair.join.notnull", sk)
.. " where name=@name";
cfg.params("clear.null", sk); --清除值为null的SqlParameter
return sql;
end
tb.sqls.Update2 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "update Person set ";
--使用lua遍历keys
local ps = cfg.params("pair", sk, nil, nil, nil, {"birthday"}); --忽略birthday的
local bsplit = false;
for k,v in pairs(ps) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. k .. '=' .. "'" .. v .. "'";
end
sql = sql .. " where name=@name";
cfg.param("del", sk, "birthday");
return sql;
end
tb.sqls.Update21 = function (sk) --sk是一个key(guid),用于获取SqlParameters时用的
local sql = "update Person set ";
--使用lua遍历keys
local ps = cfg.params("pair.notnull", sk); --忽略birthday的
local bsplit = false;
for k,v in pairs(ps) do
if bsplit then
sql = sql .. ',';
else
bsplit = true;
end
sql = sql .. k .. '=' .. "'" .. v .. "'";
end
sql = sql .. " where name=@name";
cfg.param("del", sk, "birthday");
return sql;
end
----------------------------------------update end
tb.sqls.Delete = function ()
return "delete from Person where name=@name"
end
end);
|
--[[
Programmable robot ('hoverbot') mod for Minetest
Copyright (C) 2018 Pilcrow182
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]--
local LOG,VERBOSE = false, false
local debug_log = function(output)
if not LOG then return end
print("HOVERBOT:: DEBUG: "..output)
if not VERBOSE then return end
minetest.chat_send_all("HOVERBOT:: DEBUG: "..output)
end
hoverbot.item_pickup = function(pos, inv)
for _,object in ipairs(minetest.get_objects_inside_radius(pos, 1)) do
if not object:is_player() and object:get_luaentity() and object:get_luaentity().name == "__builtin:item" then
if inv:room_for_item("main", ItemStack(object:get_luaentity().itemstring)) then
inv:add_item("main", ItemStack(object:get_luaentity().itemstring))
object:get_luaentity().itemstring = ""
object:remove()
end
end
end
end
hoverbot.save_return = function(pos, exec_page, exec)
debug_log("saving return data before setting new exec_page")
local meta = minetest.get_meta(pos)
local return_table = minetest.deserialize(meta:get_string("return_table"))
local new_return = {{exec_page,exec},return_table[1],return_table[2],return_table[3]}
meta:set_string("return_table", minetest.serialize(new_return))
debug_log("return table (serialized) is now "..minetest.serialize(new_return))
end
hoverbot.load_return = function(pos)
debug_log("codepage completed. loading return data")
local meta = minetest.get_meta(pos)
local return_table = minetest.deserialize(meta:get_string("return_table"))
local return_page = return_table[1]
if return_page[1] == "end" then
debug_log("no return data found. shutting down")
hoverbot.deactivate(pos,hoverbot.page0,0)
else
local new_return = {return_table[2],return_table[3],return_table[4],{"end",0}}
meta:set_string("return_table", minetest.serialize(new_return))
meta:set_string("exec_page", return_page[1])
meta:set_string("exec", return_page[2])
debug_log("return table (serialized) is now "..minetest.serialize(new_return))
end
end
hoverbot.rotate_self = function(botpos, facepos)
local old_p2 = minetest.get_node(botpos).param2
if minetest.get_node(botpos).name ~= "hoverbot:hoverbot_active" then return false end
local b,f = botpos,facepos
local p2 = 0
local dir = minetest.dir_to_facedir({x = f.x - b.x, y = f.y - b.y, z = f.z - b.z})
debug_log("attempting to rotate "..minetest.get_node(botpos).name.." from param2 = "..old_p2.." to param2 = "..dir)
if dir == old_p2 or (dir == 0 and f.z-b.z ~= 1) then
debug_log("did not rotate "..minetest.get_node(botpos).name.."; old_p2 ("..old_p2..") matches dir ("..dir..")")
return true
end
minetest.swap_node(botpos, {name="hoverbot:hoverbot_active", param2=dir})
end
hoverbot.move_player = function(startpos, endpos, afterpos)
local push_player = function(botpos, radpos, footpos, headpos)
for _,object in ipairs(minetest.get_objects_inside_radius(radpos, 0.5)) do
if object:is_player() then
local footnode = minetest.get_node(footpos)
local headnode = minetest.get_node(headpos)
debug_log("attempting to move player into '"..footnode.name..minetest.pos_to_string(footpos).."' and '"..headnode.name..minetest.pos_to_string(headpos).."'")
if ( minetest.pos_to_string(footpos) == minetest.pos_to_string(botpos) or minetest.registered_nodes[footnode.name].walkable == false )
and ( minetest.pos_to_string(headpos) == minetest.pos_to_string(botpos) or minetest.registered_nodes[headnode.name].walkable == false ) then
object:moveto({x=footpos.x,y=footpos.y-0.5,z=footpos.z})
return true
else
debug_log("move failed; either '"..footnode.name.."' or '"..headnode.name.."' is a solid node")
return false
end
end
end
return true
end
--move player on top
debug_log("processing move function for player on top of hoverbot")
if not push_player(startpos, {x=startpos.x,y=startpos.y+0.5,z=startpos.z}, {x=endpos.x,y=endpos.y+1,z=endpos.z}, {x=endpos.x,y=endpos.y+2,z=endpos.z}) then
debug_log("ignoring move failure for top-mounted player")
end
--move player in front, pushing feet
debug_log("processing move function for player in front of hoverbot (pushing feet)")
if not push_player(startpos, {x=endpos.x,y=endpos.y-0.5,z=endpos.z}, afterpos, {x=afterpos.x,y=afterpos.y+1,z=afterpos.z}) then
debug_log("move failure acknowledged. looping until failure no longer occurs")
return false
end
--move player in front, pushing head
debug_log("processing move function for player in front of hoverbot (pushing head)")
if not push_player(startpos, {x=endpos.x,y=endpos.y-1.5,z=endpos.z}, {x=afterpos.x,y=afterpos.y-1,z=afterpos.z}, afterpos) then
debug_log("move failure acknowledged. looping until failure no longer occurs")
return false
end
return true
end
hoverbot.move = function(startpos, endpos, acted_upon)
if acted_upon then debug_log("move failed. attempting to push interfering node and try move again") end
debug_log("hoverbot.move function called with startnode "..minetest.get_node(startpos).name.." "..minetest.pos_to_string(startpos).."and endnode "..minetest.get_node(endpos).name.." "..minetest.pos_to_string(endpos))
local dir = {x = endpos.x - startpos.x, y = endpos.y - startpos.y, z = endpos.z - startpos.z}
local afterpos = {x = endpos.x + dir.x, y = endpos.y + dir.y, z = endpos.z + dir.z}
local startnode = minetest.get_node(startpos)
local endnode = minetest.get_node(endpos)
if minetest.registered_nodes[endnode.name].buildable_to and minetest.registered_nodes[endnode.name].liquidtype == "none" then
local player_moved = hoverbot.move_player(startpos, endpos, afterpos)
if not acted_upon then
hoverbot.rotate_self(startpos, endpos)
if startnode.name == "hoverbot:hoverbot_active" and player_moved == false then
hoverbot.exec_loop(startpos)
return false
end
end
local meta = minetest.get_meta(startpos)
local meta0 = meta:to_table()
local p2 = minetest.get_node(startpos).param2
debug_log("moving "..startnode.name.." from "..minetest.pos_to_string(startpos).." to "..minetest.pos_to_string(endpos))
minetest.set_node(endpos, {name=startnode.name, param2=p2})
meta = minetest.get_meta(endpos)
meta:from_table(meta0)
minetest.set_node(startpos, {name="air"})
nodeupdate(startpos)
elseif ( not acted_upon ) and minetest.registered_nodes[startnode.name].liquidtype == "none" and hoverbot.move(endpos,afterpos, true) then
hoverbot.move(startpos,endpos)
else
if startnode.name == "hoverbot:hoverbot_active" then
hoverbot.exec_loop(startpos)
end
end
end
hoverbot.dig = function(botpos, digpos)
debug_log("digging node "..minetest.get_node(digpos).name.." at pos "..minetest.pos_to_string(digpos))
local botmeta = minetest.get_meta(botpos)
local botinv = botmeta:get_inventory()
local exec = tonumber(botmeta:get_string("exec"))
local dignode = minetest.get_node(digpos)
if dignode.name == "air" or dignode.name == "ignore" then
return nil
elseif minetest.registered_nodes[dignode.name] and minetest.registered_nodes[dignode.name].liquidtype ~= "none" then
hoverbot.exec_loop(botpos)
return false
end
local digger = hoverbot.mimic_player(botpos)
--check node to make sure it is diggable
local def = ItemStack({name=dignode.name}):get_definition()
if #def ~= 0 and not def.diggable or (def.can_dig and not def.can_dig(digpos, digger)) then --node is not diggable
return
end
--save old meta to table
local meta = minetest.get_meta(digpos)
local oldmetadata = meta:to_table()
--handle node drops
local drops = minetest.get_node_drops(dignode.name, "default:pick_mese")
for _, dropped_item in ipairs(drops) do
--add item to hoverbot's inventory
if botinv:room_for_item("main", dropped_item) then
botinv:add_item("main", dropped_item)
else
minetest.add_item(botpos, dropped_item)
end
end
minetest.remove_node(digpos)
nodeupdate(digpos)
--handle post-digging callback
if def.after_dig_node then
-- Copy pos and node because callback can modify them
local pos_copy = {x=digpos.x, y=digpos.y, z=digpos.z}
local node_copy = {name=node.name, param1=node.param1, param2=node.param2}
def.after_dig_node(pos_copy, node_copy, oldmetadata, digger)
end
--run digging event callbacks
for _, callback in ipairs(minetest.registered_on_dignodes) do
-- Copy pos and node because callback can modify them
local digpos_copy = {x=digpos.x, y=digpos.y, z=digpos.z}
local dignode_copy = {name=dignode.name, param1=dignode.param1, param2=dignode.param2}
callback(digpos_copy, dignode_copy, digger)
end
end
hoverbot.leftclick = function(botpos, clickedpos)
hoverbot.rotate_self(botpos, clickedpos)
debug_log("attempting to leftclick node at pos "..minetest.pos_to_string(clickedpos))
local meta = minetest.get_meta(botpos)
local clicker = hoverbot.mimic_player(botpos)
local clickednode = minetest.get_node(clickedpos)
if not minetest.registered_nodes[clickednode.name] then
hoverbot.exec_loop(botpos)
return false
end
local pointed_thing = {type = "node", under = clickedpos, above = botpos}
local wielded = clicker:get_wielded_item()
local wieldname = wielded:get_name()
local wieldcount = wielded:get_count()
local new_itemstack = nil
hoverbot.compat["before_leftclick"](clickedpos, clickednode, clicker, pointed_thing)
if minetest.registered_items[wieldname].on_use then
new_itemstack = minetest.registered_items[wieldname].on_use(wielded, clicker, pointed_thing)
else
new_itemstack = minetest.registered_nodes[clickednode.name].on_punch(clickedpos, clickednode, clicker, pointed_thing)
hoverbot.dig(botpos, clickedpos)
end
hoverbot.compat["after_leftclick"](clickedpos, clickednode, clicker, pointed_thing)
if new_itemstack then
local newname, newcount = wieldname, wieldcount
if new_itemstack.name then
newname, newcount = new_itemstack.name, new_itemstack.count or 1
else
newname, newcount = new_itemstack:get_name(), new_itemstack:get_count()
end
if newname == wieldname and newcount == wieldcount then return end
local inv = meta:get_inventory()
local inv_slot = tonumber(meta:get_string("inv_slot"))
inv:set_stack("main", inv_slot, new_itemstack)
end
end
hoverbot.place = function(botpos, placepos, afterpos)
local meta = minetest.get_meta(botpos)
local inv = meta:get_inventory()
local inv_slot = tonumber(meta:get_string("inv_slot"))
local inv_stack = inv:get_stack("main", inv_slot)
debug_log("attempting to place '"..inv_stack:get_name().."' from inventory slot "..inv_slot.." to pos "..minetest.pos_to_string(placepos))
if minetest.registered_nodes[minetest.get_node(placepos).name].buildable_to == false then
return false
elseif inv_stack:to_string() == "" then
hoverbot.exec_loop(botpos)
return false
end
if minetest.registered_nodes[minetest.get_node(afterpos).name].pointable then
pointed_under = afterpos
else
pointed_under = botpos
end
local placer = hoverbot.mimic_player(botpos)
local inv_stack2 = minetest.item_place(inv_stack, placer, {type="node", under=pointed_under, above=placepos})
if minetest.setting_getbool("creative_mode") and not minetest.get_modpath("unified_inventory") then --infinite stacks ahoy!
inv_stack2:take_item()
end
inv:set_stack("main", inv_slot, inv_stack2)
return
end
hoverbot.rightclick = function(botpos, clickedpos, afterpos)
hoverbot.rotate_self(botpos, clickedpos)
debug_log("attempting to rightclick node at pos "..minetest.pos_to_string(clickedpos))
local meta = minetest.get_meta(botpos)
local clicker = hoverbot.mimic_player(botpos)
local clickednode = minetest.get_node(clickedpos)
if not minetest.registered_nodes[clickednode.name] then
hoverbot.exec_loop(botpos)
return false
end
local pointed_thing = {type = "node", under = clickedpos, above = botpos}
local wielded = clicker:get_wielded_item()
local wieldname = wielded:get_name()
local wieldcount = wielded:get_count()
local new_itemstack = false
hoverbot.compat["before_rightclick"](clickedpos, clickednode, clicker, wielded, pointed_thing)
if minetest.registered_nodes[clickednode.name].on_rightclick then
new_itemstack = minetest.registered_nodes[clickednode.name].on_rightclick(clickedpos, clickednode, clicker, wielded, pointed_thing)
else
new_itemstack = minetest.registered_items[wieldname].on_place(wielded, clicker, pointed_thing)
hoverbot.place(botpos, clickedpos, afterpos)
end
hoverbot.compat["after_rightclick"](clickedpos, clickednode, clicker, wielded, pointed_thing)
if new_itemstack then
local newname, newcount = wieldname, wieldcount
if new_itemstack.name then
newname, newcount = new_itemstack.name, new_itemstack.count or 1
else
newname, newcount = new_itemstack:get_name(), new_itemstack:get_count()
end
if newname == wieldname and newcount == wieldcount then return end
local inv = meta:get_inventory()
local inv_slot = tonumber(meta:get_string("inv_slot"))
inv:set_stack("main", inv_slot, new_itemstack)
end
end
hoverbot.pushpull = function(srcpos, dstpos, withdraw)
local trylabels = function(labels,inv)
for i=1,#labels do
invlist = inv:get_list(labels[i])
if invlist then return labels[i],invlist end
end
end
local srcmeta = minetest.get_meta(srcpos)
local srcinv = srcmeta:get_inventory()
local dstinv = minetest.get_meta(dstpos):get_inventory()
local srclabel, srclist = trylabels({"main", "dst"}, srcinv)
local dstlabel, dstlist = trylabels({"main", "src"}, dstinv)
if (not srclist) or (not dstlist) then return false end
local srcsize = srcinv:get_size(srclabel)
local startslot, endslot = 1, srcsize
if withdraw then
hoverbot.rotate_self(dstpos, srcpos)
else
hoverbot.rotate_self(srcpos, dstpos)
local srcslot = tonumber(srcmeta:get_string("inv_slot"))
startslot, endslot = srcslot, srcslot
end
for i=startslot,endslot do
local j = 1 + endslot - i -- obtain the LAST non-empty item
if not withdraw then j = i end -- obtain the FIRST non-empty item
local name, count, wear = srclist[j]:get_name(), srclist[j]:get_count(), srclist[j]:get_wear()
if name ~= nil and name ~= "" then
local c = count + 1
repeat c = c - 1 until dstinv:room_for_item(dstlabel, {name=name, count=c, wear=wear})
dstinv:add_item(dstlabel, {name=name, count=c, wear=wear})
srcinv:set_stack(srclabel, j, {name=name, count=count-c, wear=wear})
break
end
end
end
hoverbot.set_exec_page = function(pos, page)
local meta = minetest.get_meta(pos)
local exec_page = meta:get_string("exec_page")
local exec = tonumber(meta:get_string("exec")) or 0
hoverbot.save_return(pos, exec_page, exec)
meta:set_string("exec_page", page)
meta:set_string("exec", 0)
hoverbot.exec_next(pos, 0)
end
hoverbot.set_inv_slot = function(pos, slot)
debug_log("setting current inventory slot to "..slot)
local meta = minetest.get_meta(pos)
meta:set_string("inv_slot", slot)
hoverbot.exec_next(pos, 0)
end
hoverbot.drop = function(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local inv_slot = tonumber(meta:get_string("inv_slot"))
local inv_stack = inv:get_stack("main", inv_slot)
debug_log("attempting to drop '"..inv_stack:get_name().."' from inventory slot "..inv_slot.." at pos "..minetest.pos_to_string(pos))
minetest.add_item({x = pos.x, y = pos.y - 0.3, z = pos.z}, inv_stack)
inv:set_stack("main", inv_slot, nil)
end
hoverbot.delete = function(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local inv_slot = tonumber(meta:get_string("inv_slot"))
debug_log("attempting to delete '"..inv:get_stack("main", inv_slot):get_name().."' from inventory slot "..inv_slot)
inv:set_stack("main", inv_slot, nil)
end
hoverbot.sleep = function()
debug_log("hoverbot is sleeping")
return true
end
hoverbot.upload = function(pos)
debug_log("NOTE -- the 'hoverbot.upload' command is only a placeholder until DigiBank Wireless Storage System is programmed")
return false
end
hoverbot.download = function(pos)
debug_log("NOTE -- the 'hoverbot.upload' command is only a placeholder until DigiBank Wireless Storage System is programmed")
return false
end
hoverbot.exec_functions = {
-- move
["hoverbot:cmd_move_n"] = function(pos) hoverbot.move(pos,{x=pos.x,y=pos.y,z=pos.z+1}) end,
["hoverbot:cmd_move_s"] = function(pos) hoverbot.move(pos,{x=pos.x,y=pos.y,z=pos.z-1}) end,
["hoverbot:cmd_move_e"] = function(pos) hoverbot.move(pos,{x=pos.x+1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_move_w"] = function(pos) hoverbot.move(pos,{x=pos.x-1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_move_u"] = function(pos) hoverbot.move(pos,{x=pos.x,y=pos.y+1,z=pos.z}) end,
["hoverbot:cmd_move_d"] = function(pos) hoverbot.move(pos,{x=pos.x,y=pos.y-1,z=pos.z}) end,
-- leftclick
["hoverbot:cmd_leftclick_n"] = function(pos) hoverbot.leftclick(pos,{x=pos.x,y=pos.y,z=pos.z+1}) end,
["hoverbot:cmd_leftclick_s"] = function(pos) hoverbot.leftclick(pos,{x=pos.x,y=pos.y,z=pos.z-1}) end,
["hoverbot:cmd_leftclick_e"] = function(pos) hoverbot.leftclick(pos,{x=pos.x+1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_leftclick_w"] = function(pos) hoverbot.leftclick(pos,{x=pos.x-1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_leftclick_u"] = function(pos) hoverbot.leftclick(pos,{x=pos.x,y=pos.y+1,z=pos.z}) end,
["hoverbot:cmd_leftclick_d"] = function(pos) hoverbot.leftclick(pos,{x=pos.x,y=pos.y-1,z=pos.z}) end,
-- rightclick
["hoverbot:cmd_rightclick_n"] = function(pos) hoverbot.rightclick(pos,{x=pos.x,y=pos.y,z=pos.z+1},{x=pos.x,y=pos.y,z=pos.z+2}) end,
["hoverbot:cmd_rightclick_s"] = function(pos) hoverbot.rightclick(pos,{x=pos.x,y=pos.y,z=pos.z-1},{x=pos.x,y=pos.y,z=pos.z-2}) end,
["hoverbot:cmd_rightclick_e"] = function(pos) hoverbot.rightclick(pos,{x=pos.x+1,y=pos.y,z=pos.z},{x=pos.x+2,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_rightclick_w"] = function(pos) hoverbot.rightclick(pos,{x=pos.x-1,y=pos.y,z=pos.z},{x=pos.x-2,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_rightclick_u"] = function(pos) hoverbot.rightclick(pos,{x=pos.x,y=pos.y+1,z=pos.z},{x=pos.x,y=pos.y+2,z=pos.z}) end,
["hoverbot:cmd_rightclick_d"] = function(pos) hoverbot.rightclick(pos,{x=pos.x,y=pos.y-1,z=pos.z},{x=pos.x,y=pos.y-2,z=pos.z}) end,
-- deposit
["hoverbot:cmd_deposit_n"] = function(pos) hoverbot.pushpull(pos,{x=pos.x,y=pos.y,z=pos.z+1}) end,
["hoverbot:cmd_deposit_s"] = function(pos) hoverbot.pushpull(pos,{x=pos.x,y=pos.y,z=pos.z-1}) end,
["hoverbot:cmd_deposit_e"] = function(pos) hoverbot.pushpull(pos,{x=pos.x+1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_deposit_w"] = function(pos) hoverbot.pushpull(pos,{x=pos.x-1,y=pos.y,z=pos.z}) end,
["hoverbot:cmd_deposit_u"] = function(pos) hoverbot.pushpull(pos,{x=pos.x,y=pos.y+1,z=pos.z}) end,
["hoverbot:cmd_deposit_d"] = function(pos) hoverbot.pushpull(pos,{x=pos.x,y=pos.y-1,z=pos.z}) end,
-- withdraw
["hoverbot:cmd_withdraw_n"] = function(pos) hoverbot.pushpull({x=pos.x,y=pos.y,z=pos.z+1}, pos, true) end,
["hoverbot:cmd_withdraw_s"] = function(pos) hoverbot.pushpull({x=pos.x,y=pos.y,z=pos.z-1}, pos, true) end,
["hoverbot:cmd_withdraw_e"] = function(pos) hoverbot.pushpull({x=pos.x+1,y=pos.y,z=pos.z}, pos, true) end,
["hoverbot:cmd_withdraw_w"] = function(pos) hoverbot.pushpull({x=pos.x-1,y=pos.y,z=pos.z}, pos, true) end,
["hoverbot:cmd_withdraw_u"] = function(pos) hoverbot.pushpull({x=pos.x,y=pos.y+1,z=pos.z}, pos, true) end,
["hoverbot:cmd_withdraw_d"] = function(pos) hoverbot.pushpull({x=pos.x,y=pos.y-1,z=pos.z}, pos, true) end,
-- page
["hoverbot:cmd_page_1"] = function(pos) hoverbot.set_exec_page(pos, "codebox1") end,
["hoverbot:cmd_page_2"] = function(pos) hoverbot.set_exec_page(pos, "codebox2") end,
["hoverbot:cmd_page_3"] = function(pos) hoverbot.set_exec_page(pos, "codebox3") end,
["hoverbot:cmd_page_4"] = function(pos) hoverbot.set_exec_page(pos, "codebox4") end,
["hoverbot:cmd_page_5"] = function(pos) hoverbot.set_exec_page(pos, "codebox5") end,
-- inv
["hoverbot:cmd_inv_1"] = function(pos) hoverbot.set_inv_slot(pos, "1") end,
["hoverbot:cmd_inv_2"] = function(pos) hoverbot.set_inv_slot(pos, "2") end,
["hoverbot:cmd_inv_3"] = function(pos) hoverbot.set_inv_slot(pos, "3") end,
["hoverbot:cmd_inv_4"] = function(pos) hoverbot.set_inv_slot(pos, "4") end,
["hoverbot:cmd_inv_5"] = function(pos) hoverbot.set_inv_slot(pos, "5") end,
["hoverbot:cmd_inv_6"] = function(pos) hoverbot.set_inv_slot(pos, "6") end,
["hoverbot:cmd_inv_7"] = function(pos) hoverbot.set_inv_slot(pos, "7") end,
["hoverbot:cmd_inv_8"] = function(pos) hoverbot.set_inv_slot(pos, "8") end,
-- misc
["hoverbot:cmd_drop"] = function(pos) hoverbot.drop(pos) end,
["hoverbot:cmd_delete"] = function(pos) hoverbot.delete(pos) end,
["hoverbot:cmd_sleep"] = function(pos) hoverbot.sleep() end,
["hoverbot:cmd_upload"] = function(pos) hoverbot.upload(pos) end,
["hoverbot:cmd_download"] = function(pos) hoverbot.download(pos) end,
}
hoverbot.exec_loop = function(pos)
local meta = minetest.get_meta(pos)
local exec = tonumber(meta:get_string("exec"))
meta:set_string("exec", exec-1)
end
hoverbot.exec_next = function(pos, consumes)
local running = true
if consumes ~= 0 then running = hoverbot.consume_fuel(pos, 1) end
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local exec_page = meta:get_string("exec_page")
local exec = tonumber(meta:get_string("exec")) or 0
local codesize = inv:get_size(exec_page)
hoverbot.item_pickup(pos, inv)
hoverbot.add_fuel(pos)
if running then
minetest.after(0, function()
if minetest.get_node(pos).name ~= "hoverbot:hoverbot_active" then return false end
local command = ""
while true do
exec = exec + 1
if exec > codesize then
hoverbot.load_return(pos)
break
end
meta:set_string("exec", exec)
command = inv:get_stack(exec_page, exec):get_name()
debug_log("attempting to execute page "..exec_page..", command slot "..exec.." of "..codesize.."; command item '"..command.."'")
if command ~= "" then break end
end
if command ~= "" then
debug_log("attempting to execute command '"..command.."' from table 'hoverbot.exec_functions'")
hoverbot.exec_functions[command](pos)
end
end)
end
end
minetest.register_abm({
nodenames = {"hoverbot:hoverbot_active"},
interval = 1,
chance = 1,
action = function(pos)
minetest.after(0, function() hoverbot.exec_next(pos, 1) end)
hoverbot.set_infotext(pos)
end
})
minetest.register_abm({
nodenames = {"hoverbot:hoverbot"},
interval = 1,
chance = 1,
action = function(pos)
minetest.after(0, function()
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
hoverbot.item_pickup(pos, inv)
hoverbot.add_fuel(pos)
hoverbot.set_infotext(pos)
end)
end
})
|
-- You will only get nice output from this script (like other unicode examples)
-- if executed in a properly multilingual environment like SciTE.
-- To get UTF-8 support in SciTE, edit your global properties like so:
-- # Internationalisation
-- # Japanese input code page 932 and ShiftJIS character set 128
-- #code.page=932
-- #character.set=128
-- # Unicode
-- code.page=65001 # uncomment out this line
-- #code.page=0 # and comment out this line
--
-- And restart SciTE.
require 'winapi'
winapi.setenv('greek','ελληνική')
print(os.getenv 'greek') -- this will still be nil
-- but child processes can see this variable ...
os.execute [[lua -e "print(os.getenv('greek'))"]]
|
local Player = "LocalPlayer" -- Don't change if you want it to be you
local StatName = "StatName" -- Change it to the name of the stat
local Value = "69" -- Change it to the value you want the stat to change to
-- Do not touch below --
local Plr = game:GetService("Players"):FindFirstChild(Player)
if Plr and Plr.Character then
Plr.leaderstats[StatName].Value = Value
end
-- joseph2235 -- |
local is_windows = vim.loop.os_uname().sysname == "Windows"
local path_sep = is_windows and '\\' or '/'
-- check index in table
local function has_key (tab,idx)
for index,_ in pairs(tab) do
if index == idx then
return true
end
end
return false
end
return {
is_windows = is_windows,
path_sep = path_sep,
has_key = has_key
}
|
--
player = {}
function player:new(tipo, x, y, raio, velocidade)
local instancia = {
x = x or 20,
y = y or 30,
raio = raio or 20,
velocidade = velocidade or 10,
_tipo = tipo
}
function instancia:draw()
love.graphics.circle(tipo, x, y, raio, 12)
end
function instancia:move(x, y)
x = x or 0
y = y or 0
instancia.x = instancia.x + x
instancia.y = instancia.y + y
end
function instancia:debug()
love.graphics.print(
'x: '..instancia.x,
instancia.x,
instancia.y - 30
)
end
return instancia
end
return player |
local ose = require('os_ext')
local dir = {}
function dir.create(dir_path)
local result, output, err_code, err_msg = ose.run_command(string.format('mkdir %q', dir_path))
return result, err_msg
end
function dir.copy(source_dir, dest_dir)
local result = false
local output = nil
local err_code = 0
local err_msg = nil
if ose.is_windows then
result, output, err_code, err_msg = ose.run_command(string.format('xcopy /E /Q /C /Y /R /I %q %q', source_dir, dest_dir))
else
result, output, err_code, err_msg = ose.run_command(string.format('cp -r %q %q', source_dir, dest_dir))
end
return result, err_msg
end
function dir.delete(dir_path)
local result = false
local output = nil
local err_code = 0
local err_msg = nil
if ose.is_windows then
result, output, err_code, err_msg = ose.run_command(string.format('rmdir /S /Q %q', dir_path))
else
result, output, err_code, err_msg = ose.run_command(string.format('rm -rfd %q', dir_path))
end
return result, err_msg
end
return dir
|
#!/usr/bin/env tarantool
-- Copyright 2021 Kafka-Tarantool-Loader
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
require("strict").on()
if package.setsearchroot ~= nil then
package.setsearchroot()
else
-- Workaround for rocks loading in tarantool 1.10
-- It can be removed in tarantool > 2.2
-- By default, when you do require('mymodule'), tarantool looks into
-- the current working directory and whatever is specified in
-- package.path and package.cpath. If you run your app while in the
-- root directory of that app, everything goes fine, but if you try to
-- start your app with "tarantool myapp/init.lua", it will fail to load
-- its modules, and modules from myapp/.rocks.
local fio = require("fio")
local app_dir = fio.abspath(fio.dirname(arg[0]))
print("App dir set to " .. app_dir)
package.path = package.path .. ";" .. app_dir .. "/?.lua"
package.path = package.path .. ";" .. app_dir .. "/?/init.lua"
package.path = package.path .. ";" .. app_dir .. "/.rocks/share/tarantool/?.lua"
package.path = package.path .. ";" .. app_dir .. "/.rocks/share/tarantool/?/init.lua"
package.cpath = package.cpath .. ";" .. app_dir .. "/?.so"
package.cpath = package.cpath .. ";" .. app_dir .. "/?.dylib"
package.cpath = package.cpath .. ";" .. app_dir .. "/.rocks/lib/tarantool/?.so"
package.cpath = package.cpath .. ";" .. app_dir .. "/.rocks/lib/tarantool/?.dylib"
end
local cartridge = require("cartridge")
local ok, err = cartridge.cfg({
workdir = "tmp/db",
roles = {
"cartridge.roles.vshard-storage",
"cartridge.roles.vshard-router",
"app.roles.adg_api",
"app.roles.adg_storage",
"app.roles.adg_kafka_connector",
"app.roles.adg_scheduler",
"app.roles.adg_input_processor",
"app.roles.adg_output_processor",
"app.roles.adg_state",
},
cluster_cookie = "memstorage-cluster-cookie",
})
assert(ok, tostring(err))
|
------------------------------------------
-- acme_file_reader.lua
-- Author: Hadriel Kaplan (hadrielk at yahoo dot com)
-- version = 1.0
-- date = 3/3/2014
------------------------------------------
--[[
This is a Wireshark Lua-based capture file reader.
This "capture file" reader reads message logs from Acme Packet (now Oracle) Session Border Controllers,
such as sipmsg.log files. There are several variants of the log file format, as well as some changes that
can happen based on how the log file is generated and retrieved; for example if it's generated through a
'tail' command, or FTP'ed by a FTP client which adds carriage-returns. This Lua file reader tries to handle
such conditions.
Note: this script wasn't written to be super-efficient, nor clever. When you've been writing Lua for a while
you get used to writing in a different, more elegant fashion than this script is; but other people find it
hard to read such Lua code, so I've tried to keep this simpler.
Features:
-handles sipmsg type logs, sipdns type logs, algd type logs
-handles both IPv4 and IPv6, for both UDP and TCP
-reads sipmsg logs from 3800, 4250, 4500, 9200, 6300 SBCs
-handles logs with extra carriage-returns and linefeeds, such as from certain FTP'ed cases
-handles logs generated/copied from a 'tail' command on the SBC ACLI
-handles MBCD messages in logs, and puts their decoded ascii description in comments in Wireshark
Issues:
-for very large logs (many megabytes), it takes a long time (many minutes)
-creates fake IP and UDP/TCP headers, which might be misleading
-has to guess sometimes, though it hasn't guessed wrong yet as far as I know
To-do:
- make it use Struct.tohex/fromhex now that we have the Struct library in Wireshark
- make it use a linux cooked-mode pseudo-header (see https://wiki.wireshark.org/SLL)
- make it use preferences, once I write C-code for Wireshark to do that :)
- rewrite some of the pattern searches to use real regex/PCRE instead? It's not in Wireshark yet,
but it's coming (see https://code.wireshark.org/review/#/c/332/)
Example SIP over UDP message:
Aug 26 19:25:10.685 On [5:0]2.1.1.1:5060 received from 2.1.2.115:5060
REGISTER sip:2.1.1.1:5060 SIP/2.0
Via: SIP/2.0/UDP 2.1.2.115:5060;branch=z9hG4bK6501441021660x81000412
From: <sip:[email protected]:5060>;tag=520052-7015560x81000412
To: <sip:[email protected]:5060>
Call-ID: [email protected]
CSeq: 247 REGISTER
Contact: <sip:[email protected]:5060;transport=udp>
Expires: 300
Max-Forwards: 70
Authorization: Digest username="public_115",realm="empirix.com",uri="sip:2.1.1.1",response="5d61837cc54dc27018a40f2532e622de",nonce="430f6ff09ecd8c3fdfc5430b6e7e437a4cf77057",algorithm=md5
Content-Length: 0
----------------------------------------
Another one:
2007-03-06 13:38:48.037 OPENED
2007-03-06 13:38:48.037 OPENED
2007-03-06 13:38:48.037 OPENED
Mar 6 13:38:54.959 On [1:0]135.25.29.135:5060 received from 192.168.109.138:65471
OPTIONS sip:135.25.29.135 SIP/2.0
Accept: application/sdp
User-Agent: ABS GW v5.1.0
To: sip:135.25.29.135
From: sip:192.168.109.138;tag=a2a090ade36bb108da70b0c8f7ba02e9
Contact: sip:192.168.109.138
Call-ID: [email protected]
CSeq: 347517161 OPTIONS
Via: SIP/2.0/UDP 192.168.109.138;branch=z9hG4bK21feac80fe9a63c1cf2988baa2af0849
Max-Forwards: 70
Content-Length: 0
----------------------------------------
Another SIP over UDP (from 9200):
File opened.
Jun 8 14:34:22.599 UDP[3:0]10.102.131.194:5060 OPENED
Jun 8 14:34:22.616 UDP[6:0]10.102.130.185:5060 OPENED
Jun 8 14:34:49.416 On [6:0]10.102.130.185:5060 received from 10.102.130.150:5060
REGISTER sip:csp.noklab.net SIP/2.0
Via: SIP/2.0/UDP 192.168.1.100:5060;branch=z9hG4bK26b7a48d
From: sip:[email protected]
To: sip:[email protected]
Call-ID: [email protected]
CSeq: 144 REGISTER
User-Agent: CSCO/7
Contact: <sip:[email protected]:5060>
Content-Length: 0
Expires: 3600
----------------------------------------
Example SIP over TCP message (note it ends in the middle of a header name):
Jan 12 00:03:54.700 On 172.25.96.200:8194 received from 172.25.32.28:5060
SIP/2.0 200 OK
From: Unavailable <sip:[email protected]:5060;user=phone>;tag=1200822480
To: 24001900011 <sip:[email protected]:5060;user=phone>;tag=03c86c0b27df1b1254aeccbc000
Call-ID: [email protected]
CSe
----------------------------------------
Example SIP Pre and Post-NAT messages:
Post-NAT from private<realm=e911core> encoded:
SIP/2.0 302 Moved Temporarily
Call-ID: SD27o9f04-fcc63aa885c83e22a1be64cfc210b55e-vjvtv00
CSeq: 2 INVITE
From: <sip:[email protected]:5060;user=phone;e911core=TSD5051AEPCORE-dnamt76v6nm04;CKE=BSLD-5cuduig6t52l2;e911vpn=TSD5051AEPVPN-7gdq13vt8fi59>;tag=SD27o9f04-10000000-0-1424021314
To: <sip:[email protected];user=phone;CKE=BSLD-8blt7m3dhnj17>;tag=10280004-0-1239441202
Via: SIP/2.0/UDP 127.254.254.1:5060;branch=z9hG4bK5i4ue300dgrdras7q281.1
Server: DC-SIP/1.2
Content-Length: 0
Contact: <sip:[email protected]:5060;e911core=TSD5051AEPCORE-5n86t36uuma01>
----------------------------------------
Pre-NAT to private<realm=e911core> decode:
ACK sip:[email protected];user=phone;CKE=BSLD-8blt7m3dhnj17 SIP/2.0
Via: SIP/2.0/UDP 127.254.254.1:5060;branch=z9hG4bK5i4ue300dgrdras7q281.1
Call-ID: SD27o9f04-fcc63aa885c83e22a1be64cfc210b55e-vjvtv00
CSeq: 2 ACK
From: <sip:[email protected]:5060;user=phone;e911core=TSD5051AEPCORE-dnamt76v6nm04;CKE=BSLD-5cuduig6t52l2;e911vpn=TSD5051AEPVPN-7gdq13vt8fi59>;tag=SD27o9f04-10000000-0-1424021314
To: <sip:[email protected];user=phone;CKE=BSLD-8blt7m3dhnj17>;tag=10280004-0-1239441202
Max-Forwards: 70
----------------------------------------
Example DNS message:
Nov 1 23:03:12.811 On 10.21.232.194:1122 received from 10.21.199.204:53
DNS Response 3916 flags=8503 q=1 ans=0 auth=1 add=0 net-ttl=0
Q:NAPTR 7.6.5.4.3.2.1.0.1.2.e164
NS:SOA e164 ttl=0 netnumber01
rname=user.netnumber01
ser=223 ref=0 retry=0 exp=0 minttl=0
0000: 0f 4c 85 03 00 01 00 00 00 01 00 00 01 37 01 36 .L...........7.6
0010: 01 35 01 34 01 33 01 32 01 31 01 30 01 31 01 32 .5.4.3.2.1.0.1.2
0020: 04 65 31 36 34 00 00 23 00 01 04 65 31 36 34 00 .e164..#...e164.
0030: 00 06 00 01 00 00 00 00 00 33 0b 6e 65 74 6e 75 .........3.netnu
0040: 6d 62 65 72 30 31 00 04 75 73 65 72 0b 6e 65 74 mber01..user.net
0050: 6e 75 6d 62 65 72 30 31 00 00 00 00 df 00 00 00 number01........
0060: 00 00 00 00 00 00 00 00 00 00 00 00 00 .............
----------------------------------------
Example MGCP message (note the IP/UDP headers are in the hex):
Mar 1 14:37:26.683 On [0:803]172.16.84.141:2427 sent to 172.16.74.100:2427
Packet:
0000: 00 04 00 00 00 01 00 02 00 00 03 23 0a ad 00 c9 ...........#....
0010: 45 00 00 a8 23 36 00 00 3c 11 63 fd ac 10 54 8d E...#6..<.c...T.
0020: ac 10 4a 64 09 7b 09 7b 00 94 16 c2 32 35 30 20 ..Jd.{.{....250
250 55363 Connection Deleted
P: PS=6551, OS=1048160, PR=6517, OR=1042720, PL=0, JI=1, LA=5, PC/RPS=6466, PC/ROS=1034560, PC/RPL=0, PC/RJI=0
----------------------------------------
Example MBCD message:
Mar 1 14:37:26.672 On 127.0.0.1:2946 sent to 127.0.0.1:2944
0000: ac 3e fd a8 01 01 77 36 9e 00 37 10 0c 34 4c bc .>....w6..7..4L.
0010: 00 30 23 0c 34 4c bc 00 11 33 00 0e 35 00 04 00 .0#.4L...3..5...
0020: 00 00 00 30 00 04 00 00 00 00 23 0c 34 4c bd 00 ...0......#.4L..
0030: 11 33 00 0e 35 00 04 00 00 00 00 30 00 04 00 00 .3..5......0....
0040: 00 00 ..
Transaction = 24589982 {
Context = 204754108 {
Subtract = 204754108 {
Audit {
Stats,
Flow
}
},
Subtract = 204754109 {
Audit {
Stats,
Flow
}
}
}
}
----------------------------------------
]]----------------------------------------
-- debug printer, set DEBUG to true to enable printing debug info
-- set DEBUG2 to true to enable really verbose printing
local DEBUG, DEBUG2 = true, false
local dprint = function() end
local dprint2 = function() end
if DEBUG or DEBUG2 then
dprint = function(...)
print(table.concat({"Lua:", ...}," "))
end
if DEBUG2 then
dprint2 = dprint
end
end
-- this should be done as a preference setting
local ALWAYS_UDP = true
local fh = FileHandler.new("Oracle Acme Packet logs", "acme",
"A file reader for Oracle Acme Packet message logs such as sipmsg.log","rs")
-- There are certain things we have to create fake state/data for, because they
-- don't exist in the log file for example to create IP headers we have to create
-- fake identification field values, and to create timestamps we have to guess the
-- year (and in some cases month/day as well), and for TCP we have to create fake
-- connection info, such as sequence numbers. We can't simply have a global static
-- variable holding such things, because Wireshark reads the file sequentially at
-- first, but then calls seek_read for random packets again and we don't want to
-- re-create the fake info again because it will be wrong. So we need to create it
-- for each packet and remember what we created for each packet, so that seek_read
-- gets the same values. We could store the variables in a big table, keyed by the
-- specific header info line for each one; but instead we'll key it off of the file
-- position number, since read() sets it for Wireshark and seek_read() gets it from
-- Wireshark. So we'll have a set of global statics used during read(), but the
-- actual per-packet values will be stored in a table indexed/keyed by the file
-- position number. A separate table holds TCP peer connection info as described
-- later.
-- I said above that this state is "global", but really it can't be global to this
-- whole script file, because more than one file can be opened for reading at the
-- same time. For example if the user presses the reload button, the capture file
-- will be opened for reading before the previous (same) one is closed. So we have
-- to store state per-file. The good news is Wireshark gives us a convenient way to
-- do that, using the CaptureInfo.private_table attribute/member. We can save a Lua
-- table with whatever contents we want, to this private_table member, and get it
-- later during the other read/seek_read/cose function calls.
-- So to store this per-file state, we're going to use Lua class objects. They're
-- just Lua tables that have functions and meta-functions and can be treated like
-- objects in terms of syntax/behavior.
local State = {}
local State_mt = { __index = State }
function State.new()
local new_class = { -- the new instance
-- stuff we need to keep track of to cerate fake info
ip_ident = 0,
tyear = 0,
tmonth = 0,
tmin = 0,
tsec = 0,
tmilli = 0,
nstime = NSTime(),
-- the following table holds per-packet info
-- the key index will be a number - the file position - but it won't be an array type table (too sparse).
-- Each packet's entry is a table holding the "static" variables for that packet; this sub-table will be
-- an array style instead of hashmap, to reduce size/performance
-- This table needs to be cleared whenever the file is closed/opened.
packets = {},
-- the following local table holds TCP peer "connection" info, which is basically
-- TCP control block (TCB) type information; this is needed to create and keep track
-- of fake TCP sockets/headers for messages that went over TCP, for example for fake
-- sequence number info.
-- The key index for this is the local+remote ip:port strings concatenated.
-- The value is a sub-table, array style, holding the most recent sequence numbers.
-- This whole table needs to be cleared whenever the file is closed/opened.
tcb = {},
}
setmetatable( new_class, State_mt ) -- all instances share the same metatable
return new_class
end
-- the indices for the State.packets{} variable sub-tables
local IP_IDENT = 1
local TTIME = 2
local LOCAL_SEQ = 3
local REMOTE_SEQ = 4
-- the indices for the State.tcb{} sub-tables
local TLOCAL_SEQ = 1
local TREMOTE_SEQ = 2
-- helper functions
local char = string.char
local floor = math.floor
-- takes a Lua number and converts it into a 2-byte string binary (network order)
local function dec2bin16(num)
return Struct.pack(">I2",num)
end
-- takes a Lua number and converts it into a 4-byte string binary (network order)
local function dec2bin32(num)
return Struct.pack(">I4",num)
end
-- function to skip log info before/between/after messages
local delim = "^%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-%-$"
-- words that must be found to be skipped. "File ..." is found in 9200 logs)
local skiplist = { " OPENED", " CLOSED", " STARTED", " STOPPED", "^File ", delim }
-- pre/post NAT entries
local pre_nat_header_pattern = "^Pre%-NAT to private<realm=([^>]+)> decode:\r?$"
local post_nat_header_pattern = "^Post%-NAT from private<realm=([^>]+)> encoded:\r?$"
local function skip_ahead(file, line, position)
repeat
local found = #line == 0 -- will be false unless the line is empty
for i, word in ipairs(skiplist) do
if line:find(word) then
found = true
break
end
end
if found then
position = file:seek()
line = file:read()
if not line then return nil end
elseif line:find(pre_nat_header_pattern) or line:find(post_nat_header_pattern) then
-- skip the whole message
found = true
repeat
line = file:read()
until line:find(delim)
end
until not found
return line, position
end
-- following pattern grabs month, day, hour, min, sec, millisecs
local header_time_pattern = "^(%u%l%l) ?(%d%d?) (%d%d?):(%d%d):(%d%d)%.(%d%d%d) On "
-- tail'ed file has no month/day
local header_tail_time_pattern = "^(%d%d):(%d%d)%.(%d%d%d) On "
-- grabs local and remote IPv4:ports (not phy/vlan), and words in between (i.e., "sent to" or "received from")
local header_address_pattern = "(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):(%d+) (%l+ %l+) (%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):(%d+) ?\r?$"
-- grabs local and remote IPv6:ports (not phy/vlan), and words in between (i.e., "sent to" or "received from")
local header_v6address_pattern = "%[([:%x]+)%]:(%d+) (%l+ %l+) %[([:%x]+)%]:(%d+) ?\r?$"
-- grabs phy/vlan info
local header_phy_pattern = "%[(%d+):(%d+)%]"
local SENT = 1
local RECV = 2
local function get_direction(phrase)
if #phrase == 7 and phrase:find("sent to") then
return SENT
elseif #phrase == 13 and phrase:find("received from") then
return RECV
end
dprint("direction phrase not found")
return nil
end
-- monthlist table for getting month number value from 3-char name (number is table index)
local monthlist = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
-- Compute the difference in seconds between local time and UTC
-- from http://lua-users.org/wiki/TimeZone
local function get_timezone()
local now = os.time()
return os.difftime(now, os.time(os.date("!*t", now)))
end
local timezone = get_timezone()
function State:get_timestamp(line, file_position, seeking)
local i, line_pos, month, day, hour, min, sec, milli = line:find(header_time_pattern)
if not month then
return
end
if seeking then
-- we've seen this packet before, just go get the saved timestamp
sec = self.packets[file_position][TTIME]
if not sec then
dprint("failed to get saved timestamp for packet at position:", file_position)
return
end
return sec, line_pos
end
-- find the month's number
for index, name in ipairs(monthlist) do
if month == name then
month = index
break
end
end
if type(month) ~= "number" then return end
day = tonumber(day)
hour = tonumber(hour)
min = tonumber(min)
sec = tonumber(sec)
milli = tonumber(milli)
if not day or not hour or not min or not sec or not milli then
dprint("timestamp could not be determined")
return nil
end
-- we don't know what year the log file was created, so we have to guess
-- if we guess the current system year, then a log of December loaded in January will appear wrong,
-- as will a log file which lasts over new year
-- so we're going to check the current system month, and if it's less than the log file's then we'll
-- assume the log file started last year; if the system month is larger or equal, then we'll assume the log
-- file is of this year. We only do this checking once per file.
if self.tyear == 0 then
local curr_year, curr_month = tonumber(os.date("%Y")), tonumber(os.date("%m"))
if curr_month < month then
-- use last year
if curr_year > 0 then
curr_year = curr_year - 1
end
end
self.tyear = curr_year
-- XXX - but for purposes of testing, we just force the year to
-- 2014, so that we can compare the result of this code reading
-- an Acme log with the result of the pcapng reader reading a
-- pcapng file with the same packets - the time stamps in
-- pcapng files are times since the Epoch, so the year is known
self.tyear = 2014
end
-- if this message's month is less than previous message's, then year wrapped
if month < self.tmonth then
self.tyear = self.tyear + 1
end
self.tmonth = month
local timet = os.time({ ["year"] = self.tyear, ["month"] = month, ["day"] = day, ["hour"] = hour, ["min"] = min, ["sec"] = sec })
if not timet then
dprint("timestamp conversion failed")
end
timet = timet + timezone
-- make an NSTime
self.nstime = NSTime(timet, milli * 1000000)
self.packets[file_position][TTIME] = self.nstime
timet = timet + (milli/1000)
dprint2("found time of ", os.date("%c",timet), " with value=",timet)
return self.nstime, line_pos
end
-- get_tail_time() gets a fictitious timestamp starting from 19:00:00 on Dec 31, 1969, and incrementing based
-- on the minutes/secs/millisecs seen (i.e., if the minute wrapped then hour increases by 1, etc.).
-- this is needed for tail'ed log files, since they don't show month/day/hour
function State:get_tail_time(line, file_position, seeking)
local i, line_pos, min, sec, milli = line:find(header_tail_time_pattern)
if not min then return end
if seeking then
-- we've seen this packet before, just go get the saved timestamp
sec = self.packets[file_position][TTIME]
if not sec then
dprint("failed to get saved timestamp for packet at position:", file_position)
return
end
return sec, line_pos
end
min = tonumber(min)
sec = tonumber(sec)
milli = tonumber(milli)
if not min or not sec or not milli then
dprint("timestamp could not be determined")
return nil
end
-- get difference in time
local tmin, tsec, tmilli, nstime = self.tmin, self.tsec, self.tmilli, self.nstime
local ttime = nstime.secs
-- min, sec, milli are what the log says this tail'ed packet is
-- tmin, tsec, tmilli are what we got from last packet
-- nstime is the unix time of that, and ttime is the seconds of that unix time
-- if minutes wrapped, or they're equal but seconds wrapped, then handle it as if in the next hour
if (min < tmin) or (min == tmin and sec < tsec) or (min == tmin and sec == tsec and milli < tmilli) then
-- something wrapped, calculate difference as if in next hour
ttime = ttime + (((min * 60) + sec + 3600) - ((tmin * 60) + tsec))
else
ttime = ttime + (((min * 60) + sec) - ((tmin * 60) + tsec))
end
self.tmin, self.tsec, self.tmilli = min, sec, milli
self.nstime = NSTime(ttime, milli * 1000000)
self.packets[file_position][TTIME] = self.nstime
return self.nstime, line_pos
end
local hexbin = {
["0"]=0, ["1"]=1, ["2"]=2, ["3"]=3, ["4"]=4, ["5"]=5, ["6"]=6, ["7"]=7, ["8"]=8, ["9"]=9, ["a"]=10, ["b"]=11, ["c"]=12, ["d"]=13, ["e"]=14, ["f"]=15,
["00"]=0, ["01"]=1, ["02"]=2, ["03"]=3, ["04"]=4, ["05"]=5, ["06"]=6, ["07"]=7, ["08"]=8, ["09"]=9, ["0a"]=10, ["0b"]=11, ["0c"]=12, ["0d"]=13, ["0e"]=14, ["0f"]=15,
["10"]=16, ["11"]=17, ["12"]=18, ["13"]=19, ["14"]=20, ["15"]=21, ["16"]=22, ["17"]=23, ["18"]=24, ["19"]=25, ["1a"]=26, ["1b"]=27, ["1c"]=28, ["1d"]=29, ["1e"]=30, ["1f"]=31,
["20"]=32, ["21"]=33, ["22"]=34, ["23"]=35, ["24"]=36, ["25"]=37, ["26"]=38, ["27"]=39, ["28"]=40, ["29"]=41, ["2a"]=42, ["2b"]=43, ["2c"]=44, ["2d"]=45, ["2e"]=46, ["2f"]=47,
["30"]=48, ["31"]=49, ["32"]=50, ["33"]=51, ["34"]=52, ["35"]=53, ["36"]=54, ["37"]=55, ["38"]=56, ["39"]=57, ["3a"]=58, ["3b"]=59, ["3c"]=60, ["3d"]=61, ["3e"]=62, ["3f"]=63,
["40"]=64, ["41"]=65, ["42"]=66, ["43"]=67, ["44"]=68, ["45"]=69, ["46"]=70, ["47"]=71, ["48"]=72, ["49"]=73, ["4a"]=74, ["4b"]=75, ["4c"]=76, ["4d"]=77, ["4e"]=78, ["4f"]=79,
["50"]=80, ["51"]=81, ["52"]=82, ["53"]=83, ["54"]=84, ["55"]=85, ["56"]=86, ["57"]=87, ["58"]=88, ["59"]=89, ["5a"]=90, ["5b"]=91, ["5c"]=92, ["5d"]=93, ["5e"]=94, ["5f"]=95,
["60"]=96, ["61"]=97, ["62"]=98, ["63"]=99, ["64"]=100, ["65"]=101, ["66"]=102, ["67"]=103, ["68"]=104, ["69"]=105, ["6a"]=106, ["6b"]=107, ["6c"]=108, ["6d"]=109, ["6e"]=110, ["6f"]=111,
["70"]=112, ["71"]=113, ["72"]=114, ["73"]=115, ["74"]=116, ["75"]=117, ["76"]=118, ["77"]=119, ["78"]=120, ["79"]=121, ["7a"]=122, ["7b"]=123, ["7c"]=124, ["7d"]=125, ["7e"]=126, ["7f"]=127,
["80"]=128, ["81"]=129, ["82"]=130, ["83"]=131, ["84"]=132, ["85"]=133, ["86"]=134, ["87"]=135, ["88"]=136, ["89"]=137, ["8a"]=138, ["8b"]=139, ["8c"]=140, ["8d"]=141, ["8e"]=142, ["8f"]=143,
["90"]=144, ["91"]=145, ["92"]=146, ["93"]=147, ["94"]=148, ["95"]=149, ["96"]=150, ["97"]=151, ["98"]=152, ["99"]=153, ["9a"]=154, ["9b"]=155, ["9c"]=156, ["9d"]=157, ["9e"]=158, ["9f"]=159,
["a0"]=160, ["a1"]=161, ["a2"]=162, ["a3"]=163, ["a4"]=164, ["a5"]=165, ["a6"]=166, ["a7"]=167, ["a8"]=168, ["a9"]=169, ["aa"]=170, ["ab"]=171, ["ac"]=172, ["ad"]=173, ["ae"]=174, ["af"]=175,
["b0"]=176, ["b1"]=177, ["b2"]=178, ["b3"]=179, ["b4"]=180, ["b5"]=181, ["b6"]=182, ["b7"]=183, ["b8"]=184, ["b9"]=185, ["ba"]=186, ["bb"]=187, ["bc"]=188, ["bd"]=189, ["be"]=190, ["bf"]=191,
["c0"]=192, ["c1"]=193, ["c2"]=194, ["c3"]=195, ["c4"]=196, ["c5"]=197, ["c6"]=198, ["c7"]=199, ["c8"]=200, ["c9"]=201, ["ca"]=202, ["cb"]=203, ["cc"]=204, ["cd"]=205, ["ce"]=206, ["cf"]=207,
["d0"]=208, ["d1"]=209, ["d2"]=210, ["d3"]=211, ["d4"]=212, ["d5"]=213, ["d6"]=214, ["d7"]=215, ["d8"]=216, ["d9"]=217, ["da"]=218, ["db"]=219, ["dc"]=220, ["dd"]=221, ["de"]=222, ["df"]=223,
["e0"]=224, ["e1"]=225, ["e2"]=226, ["e3"]=227, ["e4"]=228, ["e5"]=229, ["e6"]=230, ["e7"]=231, ["e8"]=232, ["e9"]=233, ["ea"]=234, ["eb"]=235, ["ec"]=236, ["ed"]=237, ["ee"]=238, ["ef"]=239,
["f0"]=240, ["f1"]=241, ["f2"]=242, ["f3"]=243, ["f4"]=244, ["f5"]=245, ["f6"]=246, ["f7"]=247, ["f8"]=248, ["f9"]=249, ["fa"]=250, ["fb"]=251, ["fc"]=252, ["fd"]=253, ["fe"]=254, ["ff"]=255
}
local function iptobytes(ipaddr)
local bytes = { ipaddr:match("(%d+)%.(%d+)%.(%d+)%.(%d+)") }
if not #bytes == 4 then
dprint("failed to get ip address bytes for '", ipaddr, "'")
return
end
local ip = ""
for i, byte in ipairs(bytes) do
ip = ip .. char(tonumber(byte))
end
return ip
end
local function hexword2bin(word)
if #word == 4 then
return char(hexbin[word:sub(1,2)], hexbin[word:sub(3,4)])
elseif #word == 3 then
return char(hexbin[word:sub(1,1)], hexbin[word:sub(2,3)])
elseif #word < 3 then
return char(0, hexbin[word])
end
return nil -- error
end
-- convert this 2620:0:60:8ac::102 to its 16-byte binary (=8 of 2-byte words)
local NUMWORDS = 8
local function ipv6tobytes(ipaddr)
-- start with all 16 bytes being zeroes
local words = { "\00\00", "\00\00", "\00\00", "\00\00", "\00\00", "\00\00", "\00\00", "\00\00" }
-- now walk from front of ipv6 address string replacing byte numbers above;
-- if we hit a "::", then jump to end and do it in reverse
local colon_s, colon_e = ipaddr:find("::%x")
if colon_s then
-- there's a double-colon, so split the string and do the end first, backwards
-- get each chunk first
local t = {}
local index, wordix = 1, NUMWORDS
for w in string.gmatch(ipaddr:sub(colon_e - 1), ":(%x+)") do
t[index] = hexword2bin(w)
index = index + 1
end
for ix=index-1, 1, -1 do
words[wordix] = t[ix]
wordix = wordix - 1
end
ipaddr = ipaddr:sub(1, colon_s)
end
local i = 1
for w in string.gmatch(ipaddr, "(%x+):?") do
words[i] = hexword2bin(w)
i = i + 1
end
if not #words == NUMWORDS then
dprint("failed to get IPv6 address bytes for '", ipaddr, "'")
return
end
return table.concat(words)
end
-- calculates checksum as done for IP, TCP, UDP
local function checksum(chunk)
local sum = 0
-- take every 2-byte value and add them up
for one, two in chunk:gmatch("(.)(.)") do
sum = sum + (string.byte(one) * 256) + (string.byte(two))
while floor(sum / 65536) > 0 do
-- add carry/overflow value
sum = (sum % 65536) + (floor(sum / 65536))
end
end
-- now get one's complement of that
sum = 65535 - sum
-- and return it as a 2-byte string
return dec2bin16(sum)
end
----------------------------------------
-- protocol type number
local PROTO_UDP = "\17"
local PROTO_TCP = "\06"
-- enum
local IPv4 = 1
local IPv6 = 2
-- both type enums and header lengths
local UDP = 8
local TCP = 20
----------------------------------------
-- Packet creation/serialization occurs using a Lua class object model
-- There's a single base class 'Packet' which has data/methods every packet type has
-- 'RawPacket' and 'DataPacket' both derive from 'Packet'.
-- 'RawPacket' is for packets which the log file has the raw IP/UDP headers for,
-- such as ALG log messages (MGCP/NCS). Since the IP headers are in them, we use those.
-- 'DataPacket' is for packets which the log file only has payload data for, and
-- we need to create fake IP/UDP or IP/TCP headers for.
-- 'BinPacket' and'AsciiPacket' both derive from 'DataPacket'.
-- 'BinPacket' is for binary-style logged packets, such as MBCD or DNS, while
-- 'AsciiPacket' is for ascii-style ones such as SIP.
-- 'DnsPacket' derives from 'BinPacket', for DNS-style logs.
-- Each class has a read_data() method, which reads in the packet data, builds the packet,
-- and sets the Wireshark buffer. Some classes have a get_data() method which read_data()
-- calls, to get the payload data before building a fake packet.
-- The base Packet class has a get_hex_data() and get_ascii_data() methods, to get the payload
-- in either form, and those base methods are called by get_data() or read_data() of derived
-- classes.
-- For performance reasons, packet data is read line-by-line into a table (called bufftbl),
-- which is concatenated at the end. This avoids Lua building interim strings and garbage
-- collecting them. But it makes the code uglier. The get_data()/get_hex_data()/get_ascii_data()
-- methods read into this table they get passed, while the read_data() functions handle managing
-- the table.
----------------------------------------
----------------------------------------
-- The base Packet class, from which others derive
-- all Packets have a ptype, timestamp, source and dest address:port, and data
--
local Packet = {}
local Packet_mt = { __index = Packet }
function Packet.new(state, timestamp, direction, source_ip, source_port, dest_ip, dest_port, ptype, ttype, file_position)
local new_class = { -- the new instance
["state"] = state,
["timestamp"] = timestamp,
["direction"] = direction,
["source_ip"] = source_ip,
["source_port"] = source_port,
["dest_ip"] = dest_ip,
["dest_port"] = dest_port,
["ptype"] = ptype,
["ttype"] = ttype,
["file_position"] = file_position
}
setmetatable( new_class, Packet_mt ) -- all instances share the same metatable
return new_class
end
function Packet:set_comment(comment)
self["comment"] = comment
end
function Packet:set_wslua_fields(frame)
frame.time = self.timestamp
frame.rec_type = wtap_rec_types.PACKET
frame.flags = wtap_presence_flags.TS -- for timestamp
if self.comment then
frame.comment = self.comment
frame.flags = frame.flags + wtap_presence_flags.COMMENTS -- comment flag
end
return true
end
local packet_hexline_pattern = "^ %x%x%x0: %x%x"
function Packet:get_hex_data(file, line, bufftbl, index)
local start = index
dprint2("Packet:get_hex_data() called")
repeat
for word in line:gmatch("(%x%x) ") do
bufftbl[index] = char(hexbin[word])
index = index + 1
if ((index - start) % 16) == 0 then break end
end
line = file:read()
until not line or not line:find(packet_hexline_pattern)
return index - start, line
end
function Packet:get_ascii_data(file, line, bufftbl, index, only_newline)
local bufflen = 0 -- keep tally of total length of payload
local found_delim = true
dprint2("Packet:get_ascii_data() called")
repeat
bufftbl[index] = line
bufflen = bufflen + #line
-- sanity check if line has "\r" at end, and if so only add \n
if line:find("\r",-1,true) then
bufftbl[index+1] = "\n"
bufflen = bufflen + 1
dprint2("Found carriage-return at end of line")
elseif only_newline then
-- only add a newline
bufftbl[index+1] = "\n"
bufflen = bufflen + 1
else
bufftbl[index+1] = "\r\n"
bufflen = bufflen + 2
end
index = index + 2
-- read next line now
line = file:read()
if not line then
-- hit eof?
found_delim = false
break
end
until line:find(delim)
-- get rid of last \r\n, if we found a dashed delimiter, as it's not part of packet
if found_delim then
bufflen = bufflen - bufftbl[index-1]:len()
bufftbl[index-1] = nil
end
dprint2("Packet:get_ascii_data() returning", bufflen)
return bufflen
end
----------------------------------------
-- RawPacket class, for packets that the log file contains the whole IP header for, such as algd logs
--
local RawPacket = {}
local RawPacket_mt = { __index = RawPacket }
setmetatable( RawPacket, Packet_mt ) -- make RawPacket inherit from Packet
function RawPacket.new(...)
local new_class = Packet.new(...) -- the new instance
setmetatable( new_class, RawPacket_mt ) -- all instances share the same metatable
return new_class
end
function RawPacket:read_data(file, frame, line, seeking)
local bufftbl = {} -- table to hold data bytes
local index = 1 -- start at first slot in array
-- need to skip "Packet:" line and first 0000: line, it's internal junk
line = file:read()
line = file:read()
dprint2("RawPacket:read_data() getting hex from line='", line, "'")
local bufflen, line = self:get_hex_data(file, line, bufftbl, index)
if not bufflen or bufflen < 21 then
dprint("error getting binary data")
return false
end
-- add remainder as more packet data, but first delete overlap
-- see if frag bits are set in IP header, to see if UDP/TCP header exists
if self.ptype == IPv4 then
-- grab byte with frag flags and first byte of offset
local flag = string.byte(bufftbl[7]) -- converts binary character to number
local frag_offset = flag % 32 -- masks off upper 3 bits
frag_offset = (frag_offset * 256) + string.byte(bufftbl[8])
flag = floor(flag / 224) -- shift right
flag = flag % 2 -- mask upper bits
if flag == 1 or frag_offset > 0 then
-- we have a fragmented IPv4 packet, so no proto header
-- only save first 20 bytes (the IP header)
for i=bufflen, 21, -1 do
bufftbl[i] = nil
end
bufflen = 20
else
-- only save first 20 + proto size bytes
local save
if bufftbl[10] == PROTO_UDP then
save = 28
elseif bufftbl[10] == PROTO_TCP then
save = 40
else
dprint("failed to fix raw packet overlap")
return
end
for i=bufflen, save+1, -1 do
bufftbl[i] = nil
end
bufflen = save
end
end
-- TODO: IPv6
-- now read in rest of message, if any
-- first skip extra empty newline
if #line == 0 then
line = file:read()
end
bufflen = bufflen + self:get_ascii_data(file, line, bufftbl, bufflen+1, true)
frame.data = table.concat(bufftbl)
return true
end
----------------------------------------
-- DataPacket class, for packets that the log file contains just the payload data for
--
local DataPacket = {}
local DataPacket_mt = { __index = DataPacket }
setmetatable( DataPacket, Packet_mt ) -- make DataPacket inherit from Packet
function DataPacket.new(...)
local new_class = Packet.new(...) -- the new instance
setmetatable( new_class, DataPacket_mt ) -- all instances share the same metatable
return new_class
end
function DataPacket:set_tcbkey(key)
self["tcbkey"] = key
return
end
function DataPacket:build_ipv4_hdr(bufflen, proto, seeking)
local len = bufflen + 20 -- 20 byte IPv4 header size
-- figure out the ip identification value
local ip_ident
if seeking then
ip_ident = self.state.packets[self.file_position][IP_IDENT]
else
-- increment ident value
self.state.ip_ident = self.state.ip_ident + 1
if self.state.ip_ident == 65536 then
self.state.ip_ident = 1
end
ip_ident = self.state.ip_ident
-- save it for future seeking
self.state.packets[self.file_position][IP_IDENT] = ip_ident
end
-- use a table to concatenate as it's slightly faster that way
local hdrtbl = {
"\69\00", -- 1=ipv4 and 20 byte header length
dec2bin16(len), -- 2=packet length bytes
dec2bin16(ip_ident), -- 3=ident field bytes
"\00\00\64", -- 4=flags/fragment offset, ttl
proto, -- 5=proto
"\00\00", -- 6=checksum (using zero for now)
iptobytes(self.source_ip), -- 7=source ip
iptobytes(self.dest_ip) -- 8=dest ip
}
-- calc IPv4 header checksum, and set its value
hdrtbl[6] = checksum(table.concat(hdrtbl))
return table.concat(hdrtbl)
end
function DataPacket:build_ipv6_hdr(bufflen, proto)
-- use a table to concatenate as it's slightly faster that way
local hdrtbl = {
"\96\00\00\00", -- 1=ipv6 version, class, label
dec2bin16(bufflen), -- 2=packet length bytes
proto .. "\64", -- 4=proto, ttl
ipv6tobytes(self.source_ip), -- 5=source ip
ipv6tobytes(self.dest_ip) -- 6=dest ip
}
return table.concat(hdrtbl)
end
-- calculates TCP/UDP header checksums with pseudo-header info
function DataPacket:calc_header_checksum(bufftbl, bufflen, hdrtbl, proto)
-- first create pseudo IP header
if self.ptype == IPv4 then
local iphdrtbl = {
iptobytes(self.source_ip), -- 1=source ip
iptobytes(self.dest_ip), -- 2=dest ip
"\00", -- zeros
proto, -- proto
dec2bin16(bufflen) -- payload length bytes
}
bufftbl[1] = table.concat(iphdrtbl)
elseif self.ptype == IPv6 then
local iphdrtbl = {
ipv6tobytes(self.source_ip), -- 1=source ip
ipv6tobytes(self.dest_ip), -- 2=dest ip
"\00\00", -- zeroes
dec2bin16(bufflen), -- payload length bytes
"\00\00\00", -- zeros
proto -- proto
}
bufftbl[1] = table.concat(iphdrtbl)
end
-- and pseudo TCP or UDP header
bufftbl[2] = table.concat(hdrtbl)
-- see if payload is odd length
local odd = false
if bufflen % 2 == 1 then
-- odd number of payload bytes, add zero byte at end
odd = true -- remember to undo this
bufftbl[#bufftbl+1] = "\00"
end
local result = checksum(table.concat(bufftbl))
-- remove pseudo-headers
bufftbl[1] = nil
bufftbl[2] = nil
if odd then
bufftbl[#bufftbl] = nil
end
return result
end
function DataPacket:build_udp_hdr(bufflen, bufftbl)
local len = bufflen + 8 -- 8 for size of UDP header
local hdrtbl = {
dec2bin16(self.source_port), -- 1=source port bytes
dec2bin16(self.dest_port), -- 2=dest port bytes
dec2bin16(len), -- 3=payload length bytes
"\00\00" -- 4=checksum
}
if bufftbl then
-- calc udp checksum (only done for IPv6)
hdrtbl[4] = self:calc_header_checksum(bufftbl, len, hdrtbl, PROTO_UDP)
end
return table.concat(hdrtbl)
end
function DataPacket:build_tcp_hdr(bufflen, bufftbl, seeking)
local len = bufflen + 20 -- 20 for size of TCP header
local local_seq, remote_seq
if seeking then
local_seq = self.state.packets[self.file_position][LOCAL_SEQ]
remote_seq = self.state.packets[self.file_position][REMOTE_SEQ]
else
-- find socket/tcb info for this "stream", create if not found
if not self.state.tcb[self.tcbkey] then
-- create them
self.state.tcb[self.tcbkey] = {}
local_seq = 1
remote_seq = 1
self.state.packets[self.file_position][LOCAL_SEQ] = 1
self.state.packets[self.file_position][REMOTE_SEQ] = 1
-- set tcb to next sequence numbers, so that the correct "side"
-- acknowledges receiving these bytes
if self.direction == SENT then
-- this packet is being sent, so local sequence increases next time
self.state.tcb[self.tcbkey][TLOCAL_SEQ] = bufflen+1
self.state.tcb[self.tcbkey][TREMOTE_SEQ] = 1
else
-- this packet is being received, so remote sequence increases next time
-- and local side will acknowldge it next time
self.state.tcb[self.tcbkey][TLOCAL_SEQ] = 1
self.state.tcb[self.tcbkey][TREMOTE_SEQ] = bufflen+1
end
else
-- stream already exists, so send the current tcb seqs and update for next time
if self.direction == SENT then
-- this packet is being sent, so local sequence increases next time
local_seq = self.state.tcb[self.tcbkey][TLOCAL_SEQ]
remote_seq = self.state.tcb[self.tcbkey][TREMOTE_SEQ]
self.state.tcb[self.tcbkey][TLOCAL_SEQ] = local_seq + bufflen
else
-- this packet is being received, so the "local" seq number of the packet is the remote's seq really
local_seq = self.state.tcb[self.tcbkey][TREMOTE_SEQ]
remote_seq = self.state.tcb[self.tcbkey][TLOCAL_SEQ]
-- and remote seq needs to increase next time (remember local_seq is TREMOTE_SEQ)
self.state.tcb[self.tcbkey][TREMOTE_SEQ] = local_seq + bufflen
end
self.state.packets[self.file_position][LOCAL_SEQ] = local_seq
self.state.packets[self.file_position][REMOTE_SEQ] = remote_seq
end
end
local hdrtbl = {
dec2bin16(self.source_port), -- 1=source port bytes
dec2bin16(self.dest_port), -- 2=dest port bytes
dec2bin32(local_seq), -- 3=sequence
dec2bin32(remote_seq), -- 4=ack number
"\80\16\255\255", -- 5=offset, flags, window size
"\00\00", -- 6=checksum
"\00\00" -- 7=urgent pointer
}
-- calc tcp checksum
hdrtbl[6] = self:calc_header_checksum(bufftbl, len, hdrtbl, PROTO_TCP)
return table.concat(hdrtbl)
end
function DataPacket:build_packet(bufftbl, bufflen, seeking)
dprint2("DataPacket:build_packet() called with ptype=",self.ptype)
if self.ptype == IPv4 then
if self.ttype == UDP then
bufftbl[2] = self:build_udp_hdr(bufflen)
bufftbl[1] = self:build_ipv4_hdr(bufflen + 8, PROTO_UDP, seeking)
elseif self.ttype == TCP then
bufftbl[2] = self:build_tcp_hdr(bufflen, bufftbl, seeking)
bufftbl[1] = self:build_ipv4_hdr(bufflen + 20, PROTO_TCP, seeking)
end
elseif self.ptype == IPv6 then
-- UDP for IPv6 requires checksum calculation, so we can't avoid more work
if self.ttype == UDP then
bufftbl[2] = self:build_udp_hdr(bufflen, bufftbl)
bufftbl[1] = self:build_ipv6_hdr(bufflen + 8, PROTO_UDP)
elseif self.ttype == TCP then
bufftbl[2] = self:build_tcp_hdr(bufflen, bufftbl, seeking)
bufftbl[1] = self:build_ipv6_hdr(bufflen + 20, PROTO_TCP)
end
else
dprint("DataPacket:build_packet: invalid packet type (neither IPv4 nor IPv6)")
return nil
end
return table.concat(bufftbl)
end
-- for performance, we read each line into a table and concatenate it at end
-- but it makes this code super ugly
function DataPacket:read_data(file, frame, line, seeking)
local bufftbl = { "", "" } -- 2 slots for ip and udp/tcp headers
local index = 3 -- start at third slot in array
local comment -- for any packet comments
dprint2("DataPacket: read_data(): calling get_data")
local bufflen = self:get_data(file, line, bufftbl, index)
if not bufflen then
dprint("DataPacket: error getting ascii or binary data")
return false
end
local buff = self:build_packet(bufftbl, bufflen, seeking)
frame.data = buff
return true
end
----------------------------------------
-- BinPacket class, for packets that the log file contains binary payload data for, such as MBCD
--
local BinPacket = {}
local BinPacket_mt = { __index = BinPacket }
setmetatable( BinPacket, DataPacket_mt ) -- make BinPacket inherit from DataPacket
function BinPacket.new(...)
local new_class = DataPacket.new(...) -- the new instance
setmetatable( new_class, BinPacket_mt ) -- all instances share the same metatable
return new_class
end
function BinPacket:get_comment_data(file, line, stop_pattern)
local comments = {}
while line and not line:find(stop_pattern) do
if #line > 0 then
comments[#comments+1] = line
comments[#comments+1] = "\r\n"
end
line = file:read()
end
if #comments > 0 then
-- get rid of extra "\r\n"
comments[#comments] = nil
self:set_comment(table.concat(comments))
end
return line
end
function BinPacket:get_data(file, line, bufftbl, index)
local is_alg = false
local bufflen, line = self:get_hex_data(file, line, bufftbl, index)
-- now eat rest of message until delimiter or end of file
-- we'll put them in comments
line = self:get_comment_data(file, line, delim)
-- return the bufflen, which is the same as number of table entries we made
return bufflen
end
----------------------------------------
-- DnsPacket class, for DNS packets (which are binary but with comments at top)
--
local DnsPacket = {}
local DnsPacket_mt = { __index = DnsPacket }
setmetatable( DnsPacket, BinPacket_mt ) -- make DnsPacket inherit from BinPacket
function DnsPacket.new(...)
local new_class = BinPacket.new(...) -- the new instance
setmetatable( new_class, DnsPacket_mt ) -- all instances share the same metatable
return new_class
end
local binpacket_start_pattern = "^ 0000: %x%x %x%x %x%x %x%x %x%x %x%x %x%x %x%x "
function DnsPacket:get_data(file, line, bufftbl, index)
-- it's UDP regardless of what parse_header() thinks
self.ttype = UDP
-- comments are at top instead of bottom of message
line = self:get_comment_data(file, line, binpacket_start_pattern)
local bufflen, line = self:get_hex_data(file, line, bufftbl, index)
-- now eat rest of message until delimiter or end of file
while line and not line:find(delim) do
line = file:read()
end
-- return the bufflen, which is the same as number of table entries we made
return bufflen
end
----------------------------------------
-- AsciiPacket class, for packets that the log file contains ascii payload data for
--
local AsciiPacket = {}
local AsciiPacket_mt = { __index = AsciiPacket }
setmetatable( AsciiPacket, DataPacket_mt ) -- make AsciiPacket inherit from DataPacket
function AsciiPacket.new(...)
local new_class = DataPacket.new(...) -- the new instance
setmetatable( new_class, AsciiPacket_mt ) -- all instances share the same metatable
return new_class
end
function AsciiPacket:get_data(file, line, bufftbl, index)
return self:get_ascii_data(file, line, bufftbl, index)
end
----------------------------------------
-- To determine packet type, we peek at the first line of 'data' following the log
-- message header. Its pattern determines the Packet object type.
-- The following are the patterns we look for; if it doesn't match one of these,
-- then it's an AsciiPacket:
local packet_patterns = {
{ "^ 0000: %x%x %x%x %x%x %x%x %x%x %x%x %x%x %x%x ", BinPacket },
{ "^Packet:$", RawPacket },
{ "^DNS Query %d+ flags=%d+ q=%d+ ans=%d+", DnsPacket },
{ "^DNS Response %d+ flags=%d+ q=%d+ ans=%d+", DnsPacket }
}
-- indeces for above
local PP_PATTERN = 1
local PP_CLASS = 2
local function get_packet_class(line)
for i, t in ipairs(packet_patterns) do
if line:find(t[PP_PATTERN]) then
dprint2("got class type=",i)
return t[PP_CLASS]
end
end
dprint2("got class type AsciiPacket")
return AsciiPacket
end
----------------------------------------
-- parses header line
-- returns nil on failure
-- the header lines look like this:
-- Aug 10 14:30:11.134 On [1:544]10.201.145.237:5060 received from 10.210.1.193:5060
-- this one has no phy/vlan info in brackets:
-- Mar 6 13:39:06.122 On 127.0.0.1:2945 sent to 127.0.0.1:2944
-- this one is IPv6:
-- Aug 10 14:30:11.140 On [3:0][2620:0:60:8ac::102]:5060 sent to [2620:0:60:8ab::12]:5060
-- this is from a tail'ed log output:
-- 52:22.434 On [0:0]205.152.56.211:5060 received from 205.152.56.75:5060
local loopback_pattern = "^127%.0%.0%.%d+$"
local function parse_header(state, file, line, file_position, seeking)
if seeking then
-- verify we've seen this packet before
if not state.packets[file_position] then
dprint("parse_header: packet at file position ", file_position, " not saved previously")
return
end
else
-- first time through, create sub-table for the packet
state.packets[file_position] = {}
end
-- get time info, and line match ending position
local timestamp, line_pos = state:get_timestamp(line, file_position, seeking)
if not timestamp then
-- see if it's a tail'ed log instead
timestamp, line_pos = state:get_tail_time(line, file_position, seeking)
end
if not timestamp then
dprint("parse_header: could not parse time portion")
return
end
local ptype, ttype = IPv4, UDP
-- get phy/vlan if present
-- first skip past time portion
local phy, vlan, i, j, k
line_pos = line_pos + 1
i, j, phy, vlan = line:find(header_phy_pattern, line_pos)
if i then
phy = tonumber(phy)
vlan = tonumber(vlan)
line_pos = j -- skip past this portion for next match
else
-- if there's no phy/vlan info, then assume it's TCP (unless it's loopback address we'll check later)
ttype = TCP
end
-- get addresses and direction
local local_ip, local_port, direction, remote_ip, remote_port = line:match(header_address_pattern, line_pos)
if not local_ip then
-- try IPv6
local_ip, local_port, direction, remote_ip, remote_port = line:match(header_v6address_pattern, line_pos)
if not local_ip then
dprint("parse_header: could not parse address portion")
return nil
end
ptype = IPv6
end
if local_ip:find(loopback_pattern) and remote_ip:find(loopback_pattern) then
-- internal loopback packets never have phy/vlan but are always UDP messages (for all intents)
ttype = UDP
end
-- override above decisions based on configuration
if ALWAYS_UDP then
ttype = UDP
end
direction = get_direction(direction)
if direction == nil then
dprint("parse_header: failed to convert direction")
return nil
end
local source_ip, source_port, dest_ip, dest_port = local_ip, local_port, remote_ip, remote_port
if direction == RECV then
-- swap them
source_ip, source_port, dest_ip, dest_port = remote_ip, remote_port, local_ip, local_port
end
-- convert
source_port = tonumber(source_port)
dest_port = tonumber(dest_port)
-- peek at next line to determine packet type
local position = file:seek()
line = file:read()
dprint2("parse_header: peeking at line='", line, "'")
packet_class = get_packet_class(line)
file:seek("set", position) -- go back
dprint2("parse_header calling packet_class.new with:",
tostring(timestamp), direction, source_ip, source_port,
dest_ip, dest_port, ptype, ttype, file_position)
local packet = packet_class.new(state, timestamp, direction, source_ip, source_port, dest_ip, dest_port, ptype, ttype, file_position)
if not packet then
dprint("parse_header: parser failed to create Packet object")
end
if ttype == TCP then
-- if the packet is tcp type, then set the key for TCB table lookup
packet:set_tcbkey(table.concat({ "[", local_ip, "]:", local_port, "->[", remote_ip, "]:", remote_port }))
end
return packet
end
----------------------------------------
-- file handling functions for Wireshark to use
-- The read_open is called by Wireshark once per file, to see if the file is this reader's type.
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- Since there is no exact magic sequence to search for, we have to use heuristics to guess if the file
-- is our type or not, which we do by parsing a message header.
-- Since Wireshark uses the file cursor position for future reading of this file, we also have to seek back to the beginning
-- so that our normal read() function works correctly.
local function read_open(file, capture)
dprint2("read_open called")
-- save current position to return later
local position = file:seek()
local line = file:read()
if not line then return false end
dprint2("read_open: got this line begin:\n'", line, "'")
line, position = skip_ahead(file, line, position)
if not line then return false end
dprint2("read_open: got this line after skip:\n'", line, "', with position=", position)
local state = State.new()
if parse_header(state, file, line, position) then
dprint2("read_open success")
file:seek("set",position)
capture.time_precision = wtap_filetypes.TSPREC_MSEC -- for millisecond precision
capture.encap = wtap.RAW_IP -- whole file is raw IP format
capture.snapshot_length = 0 -- unknown snaplen
capture.comment = "Oracle Acme Packet SBC message log"
capture.os = "VxWorks or Linux"
capture.hardware = "Oracle Acme Packet SBC"
-- reset state variables
capture.private_table = State.new()
dprint2("read_open returning true")
return true
end
dprint2("read_open returning false")
return false
end
----------------------------------------
-- this is used by both read() and seek_read()
local function read_common(funcname, file, capture, frame, position, seeking)
dprint2(funcname, "read_common called")
local state = capture.private_table
if not state then
dprint(funcname, "error getting capture state")
return false
end
local line = file:read()
if not line then
dprint(funcname, "hit end of file")
return false
end
line, position = skip_ahead(file, line, position)
if not line then
if file:read(0) ~= nil then
dprint(funcname, "did not hit end of file after skipping but ending anyway")
else
dprint2(funcname, "hit end of file after skipping")
end
return false
end
dprint2(funcname, ": parsing line='", line, "'")
local phdr = parse_header(state, file, line, position, seeking)
if not phdr then
dprint(funcname, "failed to parse header")
return false
end
line = file:read()
dprint2(funcname,": calling class object's read_data()")
phdr:read_data(file, frame, line, seeking)
if not phdr:set_wslua_fields(frame) then
dprint(funcname, "failed to set Wireshark packet header info")
return
end
dprint2(funcname, "read_common returning position")
return position
end
----------------------------------------
-- Wireshark/tshark calls read() for each frame/record in the file
-- It passes in (1) a File, (2) CaptureInfo, and (3) a FrameInfo object to this function
-- It expects in return the file offset position the record starts at,
-- or nil/false if there's an error or end-of-file is reached.
-- The offset position is used later: wireshark remembers it and gives
-- it to seek_read() at various random times
local function read(file, capture, frame)
dprint2("read called")
local position = file:seek()
position = read_common("read", file, capture, frame, position)
if not position then
if file:read(0) ~= nil then
dprint("read failed to call read_common")
else
dprint2("read: reached end of file")
end
return false
end
return position
end
----------------------------------------
-- Wireshark/tshark calls seek_read() for each frame/record in the file, at random times
-- It passes in (1) File, (2) CaptureInfo, (3) FrameInfo, and (4) the offset position number
-- It expects in return true for successful parsing, or nil/false if there's an error.
local function seek_read(file, capture, frame, offset)
dprint2("seek_read called")
file:seek("set",offset)
if not read_common("seek_read", file, capture, frame, offset, true) then
dprint("seek_read failed to call read_common")
return false
end
return true
end
----------------------------------------
-- Wireshark/tshark calls read_close() when it's closing the file completely
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- this is a good opportunity to clean up any state you may have created during
-- file reading.
-- In our case there *is* state to reset, but we only saved it in
-- the capture.private_table, so Wireshark will clean it up for us.
local function read_close(file, capture)
dprint2("read_close called")
return true
end
----------------------------------------
-- An often unused function, Wireshark calls this when the sequential walk-through is over
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- (i.e., no more calls to read(), only to seek_read()).
-- In our case there *is* some state to reset, but we only saved it in
-- the capture.private_table, so Wireshark will clean it up for us.
local function seq_read_close(file, capture)
dprint2("seq_read_close called")
return true
end
-- set above functions to the FileHandler
fh.read_open = read_open
fh.read = read
fh.seek_read = seek_read
fh.read_close = read_close
fh.seq_read_close = seq_read_close
fh.extensions = "log" -- this is just a hint
-- and finally, register the FileHandler!
register_filehandler(fh)
|
local override = script.Parent:WaitForChild("@override");
local t = require(script.Parent.types);
local basic = ({
access_point = ("@object");
override_point = ("@override");
meta = ({});
});
local get_mapping = ({
["@type"] = (function(self)
local type = (self["@type"]);
if (type) then
if (type == ("property")) then
return (self:get());
elseif (type == ("signal")) then
return (self);
end;
else
return (self);
end;
end);
});
local set_mapping = ({
["@type"] = (function(self, index, ...)
local type = (self["@type"]);
if (type) then
if (type == ("property")) then
return (self:set(...));
elseif (type == ("signal")) then
error(("cannot set <%s>%s"):format(type, index))
end;
else
error(("%s is not a valid member of %s \"%s\""):format(index, self, self:GetFullName()))
end;
end);
});
basic.meta.__index = (function(self, access)
local proto = rawget(self, basic.override_point);
local proto_type = type(proto[access]);
if (not proto[access]) then
local retrive = rawget(self, basic.access_point)[access];
if (typeof(retrive) == "Instance") then
retrive = basic.echo(retrive);
elseif (type(retrive) == "function") then
local calling = retrive;
retrive = (function(...)
local params = ({...});
for i, param in t.pairs_extract { t.is_wrapped } (params) do
params[i] = (basic.get(param));
end
local returned = table.pack(calling(unpack(params)));
for i, v in t.pairs_extract { t.IsInstance }(returned) do
returned[i] = (basic.echo(v));
end
return unpack(returned);
end);
end
return (retrive);
else
if (proto_type == "function") then
return proto[access];
else
return get_mapping["@type"](proto[access]);
end
end
end);
basic.meta.__newindex = (function(self, access, value)
local proto = rawget(self, basic.override_point);
if (not proto[access]) then
local actual = (value);
if (t.IsWrapped(actual)) then
actual = rawget(actual, basic.access_point);
end
rawget(self, basic.access_point)[access] = (actual);
else
set_mapping["@type"](proto[access], access, value)
end
end);
function merge_memory(...)
local params = ({...});
local merged = (params[1]);
table.remove(params, 1);
for _, table in pairs(params) do
for i, v in pairs(table) do
merged[i] = v;
end
end
return (merged);
end
function merge(...)
local merged = ({});
for _, table in pairs({...}) do
for i, v in pairs(table) do
if (typeof(v) == "table") then
merged[i] = merge(v);
continue;
end
merged[i] = v;
end
end
return (merged);
end
function merge_extract(value, skip_till, ...)
local merged = ({});
local extracted = ({});
for c, proto in pairs({...}) do
for i, v in pairs(proto) do
if (i == value) then
if (c >= skip_till) then
table.insert(extracted, v)
end
else
merged[i] = v;
end
end
end
return merged, extracted;
end
local cache_saves = ({});
function basic.echo(...)
local parameters = ({...});
local compiled = ({});
for i, v in next, parameters do
if (typeof(v) == "Instance") then
if (cache_saves[v]) then
table.insert(compiled, cache_saves[v]);
else
local activators = ({});
local c_proto = ({});
local extracted = nil;
local inheritted = ({});
c_proto = merge_memory(c_proto, require(override:WaitForChild(".default")));
local add_proto = function(cmake)
c_proto, extracted = merge_extract("start", 2, c_proto, cmake);
table.insert(activators, extracted[1])
end
local function Inherit(proto)
if (proto and proto.inherit and type(proto.inherit) == "table") then
for _, mod in pairs(proto.inherit) do
if (inheritted[mod]) then
continue;
end
if (typeof(mod) == "Instance" and mod:IsA("ModuleScript")) then
local cmake = require(mod);
if (cmake) then
inheritted[mod] = true;
Inherit(cmake);
add_proto(cmake);
end
end
end
end
end
local mod = override:FindFirstChild(v.ClassName);
if (typeof(mod) == "Instance" and mod:IsA("ModuleScript")) then
local cmake = require(mod);
if (cmake) then
inheritted[mod] = true;
Inherit(cmake);
add_proto(cmake);
end
end
local self, o_meta, object = newproxy(true), ({}), ({
["@case"] = ("wrapped");
});
local meta = getmetatable(self);
setmetatable(object, merge_memory(o_meta, basic.meta, {
__tostring = function()
return tostring(v);
end;
__metatable = v.ClassName;
}));
meta.__index = (object);
meta.__newindex = (object);
meta.__tostring = (o_meta.__tostring);
rawset(object, basic.override_point, (merge(c_proto)))
rawset(object, basic.access_point, v);
cache_saves[v] = (self);
table.insert(compiled, self);
for _, start in pairs(activators) do
start(object);
end
end
else
table.insert(compiled, v);
end
end
return unpack(compiled);
end
function basic.get(class)
return class[basic.access_point];
end
return (basic);
|
local gears = require("gears")
local awful = require("awful")
local M = {}
-- Default modkey.
modkey = "Mod4"
-- {{{ Key bindings
M.globalkeys = gears.table.join(
awful.key({ modkey }, "r", function ()
local c = awful.client.restore()
-- Focus restored client
if c then
c:emit_signal(
"request::activate", "key.unminimize", {raise = true}
)
end
end,
{ description = "restore minimized", group = "client" }),awful.key({ modkey, }, "e", revelation)
)
M.clientkeys = gears.table.join(
-- your code starts
awful.key({ modkey, 'Control' }, 't',
function(c)
awful.titlebar.toggle(c)
end,
{description = 'toggle title bar', group = 'client'}))
M.clientbuttons =
gears.table.join(
awful.button(
{},
1,
function(c)
c:emit_signal("request::activate", "mouse_click", {raise = true})
end
),
awful.button(
{modkey},
1,
function(c)
c:emit_signal("request::activate", "mouse_click", {raise = true})
awful.mouse.client.move(c)
end
),
awful.button(
{modkey},
3,
function(c)
c:emit_signal("request::activate", "mouse_click", {raise = true})
awful.mouse.client.resize(c)
end
)
)
return M
|
require('ISUI/ISPanel');
require('ISUI/ISRichTextPanel');
require('ISUI/ISCollapsableWindow');
UIStoryPanel = {};
function UIStoryPanel.new(title, text)
local self = {};
self.richtext = ISRichTextPanel:new(0, 0, 500, 500);
self.richtext:initialise();
self.richtext:setAnchorBottom(true);
self.richtext:setAnchorRight(true);
self.wrapped = self.richtext:wrapInCollapsableWindow();
self.wrapped:setX((getCore():getScreenWidth() * 0.5) - (self.richtext.width * 0.5));
self.wrapped:setY((getCore():getScreenHeight() * 0.5) - (self.richtext.height * 0.5));
self.wrapped:setTitle(title);
self.wrapped:addToUIManager();
self.richtext:setWidth(self.wrapped:getWidth());
self.richtext:setHeight(self.wrapped:getHeight() - 16);
self.richtext:setY(16);
self.richtext.autosetheight = false;
self.richtext.clip = true;
self.richtext:addScrollBars();
self.richtext.textDirty = true;
self.richtext.text = text;
self.richtext:paginate();
return self;
end
|
-----------------------------------
--
-- Zone: Misareaux_Coast (25)
--
-----------------------------------
require("scripts/globals/conquest")
require("scripts/globals/helm")
local ID = require("scripts/zones/Misareaux_Coast/IDs")
local MISAREAUX_COAST = require("scripts/zones/Misareaux_Coast/globals")
-----------------------------------
function onInitialize(zone)
tpz.helm.initZone(zone, tpz.helm.type.LOGGING)
MISAREAUX_COAST.ziphiusHandleQM()
end
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(567.624, -20, 280.775, 120)
end
return cs
end
function onRegionEnter(player, region)
end
function onGameHour(zone)
local vHour = VanadielHour()
if vHour >= 22 or vHour <= 7 then
MISAREAUX_COAST.ziphiusHandleQM()
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
-- Test all the helper functions
assert(make.path.get_name(make.path.current_file()) == "tests.lua")
assert(make.path.to_os("c:/path/to") == "c:\\path\\to")
assert(make.path.from_os("c:\\path\\to") == "c:/path/to")
assert(string.lower(make.path.short("c:/program files")) == "c:/progra~1")
assert(string.lower(make.path.long("c:/progra~1")) == "c:/program files")
assert(make.path.full("foo.txt") == make.path.combine(make.dir.cd(),"foo.txt"))
assert(make.path.canonicalize("c:/path/to/../to/../.") == "c:/path")
assert(make.path.add_slash("c:/path/to") == "c:/path/to/")
assert(make.path.add_slash("c:/path/to/") == "c:/path/to/")
assert(make.path.remove_slash("c:/path/to") == "c:/path/to")
assert(make.path.remove_slash("c:/path/to/") == "c:/path/to")
assert(make.path.remove_ext("foo.cpp") == "foo")
assert(make.path.remove_ext("c:/path/to/foo.cpp") == "c:/path/to/foo")
assert(make.path.remove_ext("c:/path/to/foo.2.cpp") == "c:/path/to/foo.2") -- double extension
assert(make.path.change_ext("foo.cpp",".obj") == "foo.obj")
assert(make.path.change_ext("c:/path/to/foo.cpp",".obj") == "c:/path/to/foo.obj")
assert(make.path.change_ext("c:/path/to/foo.2.cpp",".obj") == "c:/path/to/foo.2.obj") -- double extension
assert(make.path.change_ext("c:/path/to/foo",".obj") == "c:/path/to/foo.obj")
assert(make.path.combine("c:/path","to/foo.cpp") == "c:/path/to/foo.cpp")
assert(make.path.combine("c:/path/","to/foo.cpp") == "c:/path/to/foo.cpp")
assert(make.path.combine("c:/path/to","foo.cpp") == "c:/path/to/foo.cpp")
assert(make.path.combine("c:/path","to","foo.cpp") == "c:/path/to/foo.cpp")
assert(make.path.common("c:/path/to/1.cpp","c:/path/to/2.cpp") == "c:/path/to")
assert(make.path.common("c:/path/to/1.cpp","c:/path/two/2.cpp") == "c:/path")
assert(string.lower(make.path.where("notepad.exe")) == "c:/windows/system32/notepad.exe")
assert(make.path.where("notepad.exe",{"c:/windows","c:/windows/system32"}) == "c:/windows/notepad.exe")
assert(make.path.where("notepad.exe","c:/windows;c:/windows/system32") == "c:/windows/notepad.exe")
assert(make.file.exists("c:/windows/notepad.exe"))
assert(not(make.file.exists("a-file-that-should-not-exist")))
assert(make.path.remove_ext("c:/path°/to/foo.cpp") == "c:/path°/to/foo") -- Test UTF-8 round-tripping
-- make.path.combine supports the __tostring metamethod
test = setmetatable({}, {__tostring = function() return "test"; end})
assert(tostring(test) == "test")
assert(make.path.combine("c:/path/to",test) == "c:/path/to/test")
tempfile = make.file.temp()
assert(tempfile and make.file.exists(tempfile) and make.file.size(tempfile) == 0)
make.file.delete(tempfile)
assert(not(make.file.exists(tempfile)))
assert(make.file.time(tempfile) == nil)
make.file.touch(tempfile)
assert(make.file.exists(tempfile) and make.file.size(tempfile) == 0)
timestamp = make.file.time(tempfile)
assert(timestamp and timestamp >= 0)
make.file.touch(tempfile)
timestamp2 = make.file.time(tempfile)
assert(timestamp <= timestamp2) -- we need to sleep; otherwise the timestamps are
-- always equal, and the test isn't very good
make.file.delete(tempfile)
assert(not(make.file.exists(tempfile)))
--
-- Stuff that hasn't been tested yet:
--
--[[
make.path.glob -- how to test reliably?
make.file.copy
make.file.md5
make.dir.is_dir
make.dir.is_empty
make.dir.temp
make.dir.cd
make.dir.md
make.dir.rd
make.proc.spawn
make.proc.flushio
make.proc.wait
make.proc.exit_code
make.now
make.md5
]]--
|
if CLIENT then
nadmin.hud:CreateCustom({
title = "Simple",
left = {
height = 84,
draw = function(panel, w, h)
local font = "nadmin_hud"
local y = 0
surface.SetFont(font)
-- Draw the armor
if LocalPlayer():Armor() > 0 then
y = 76
draw.RoundedBox(0, 0, 8, w, h-8, nadmin.colors.gui.theme)
-- Armor background
draw.RoundedBox(0, 4, 12, w - 8, 32, nadmin:AlphaColor(nadmin.colors.gui.armor, 25))
-- Armor bar
local aw = (w * math.Clamp(LocalPlayer():Armor()/100, 0, 1)) - 8
draw.RoundedBox(0, 4, 12, aw, 32, nadmin.colors.gui.armor)
-- Armor Text
local atw = surface.GetTextSize(tostring(LocalPlayer():Armor()))
draw.Text({
text = LocalPlayer():Armor(),
font = font,
color = Color(0, 0, 0, 150),
yalign = TEXT_ALIGN_CENTER,
pos = {math.Clamp(aw - atw, 8, (w - 8) - atw), 28}
})
-- Armor Shine
draw.RoundedBoxEx(0, 4, 12, w - 8, 8, Color(255, 255, 255, 25), true, true, false, false)
-- Armor shadow
draw.RoundedBoxEx(0, 4, 36, w - 8, 8, Color(0, 0, 0, 50), false, false, true, true)
else
y = 40 -- Where to draw the xp
draw.RoundedBox(0, 0, h-40, w, 40, nadmin.colors.gui.theme)
end
-- Draw the HP
-- Health background
draw.RoundedBox(0, 4, h-36, w - 8, 32, nadmin:AlphaColor(nadmin.colors.gui.health, 50))
-- Health bar
local hw = (w * math.Clamp(LocalPlayer():Health()/LocalPlayer():GetMaxHealth(), 0, 1)) - 8
draw.RoundedBox(0, 4, h-36, hw, 32, nadmin.colors.gui.health)
-- Health text
local htw = surface.GetTextSize(tostring(LocalPlayer():Health()))
draw.Text({
text = LocalPlayer():Health(),
font = font,
color = Color(0, 0, 0, 150),
yalign = TEXT_ALIGN_CENTER,
pos = {math.Clamp(hw - htw, 8, (w - 8) - htw), h-20}
})
-- Health shine
draw.RoundedBoxEx(0, 4, h-36, w - 8, 8, Color(255, 255, 255, 25), true, true, false, false)
-- Health shadow
draw.RoundedBoxEx(0, 4, h-12, w - 8, 8, Color(0, 0, 0, 50), false, false, true, true)
-- Draw the XP
local info = LocalPlayer():GetLevel()
if nadmin.plugins.levels and istable(info) then
-- Backround
local xPos = 4
local yPos = h - y - 8
local wid = w - 8
local ht = 8
draw.RoundedBoxEx(0, xPos, yPos, wid, ht, nadmin.colors.gui.theme, true, true, false, false)
-- XP Background
draw.RoundedBox(0, xPos + 4, yPos + 4, wid - 8, 4, nadmin:AlphaColor(nadmin.colors.gui.xp, 50))
-- XP Bar
draw.RoundedBox(0, xPos + 4, yPos + 4, (wid-8) * (info.xp/info.need), 4, nadmin.colors.gui.xp)
end
end
},
right = {
height = 40,
draw = function(panel, w, h)
if not IsValid(LocalPlayer():GetActiveWeapon()) then return end
if not LocalPlayer():Alive() then return end
local font = "nadmin_hud"
surface.SetFont(font)
surface.SetFont(font)
local wep = LocalPlayer():GetActiveWeapon()
local left = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
if wep:Clip1() < 0 or wep:GetMaxClip1() < 1 then return end
-- Main
draw.RoundedBox(0, 0, 0, w, h, nadmin.colors.gui.theme)
-- Background
draw.RoundedBox(0, 4, 4, w - 8, h - 8, nadmin:AlphaColor(nadmin.colors.gui.ammo, 50))
-- Bar
local aw = (w * math.Clamp(wep:Clip1() / wep:GetMaxClip1(), 0, 1)) - 8
draw.RoundedBox(0, 4, 4, aw, h-8, nadmin.colors.gui.ammo)
-- Text
local tw = surface.GetTextSize(tostring(wep:Clip1()) .. "/" .. wep:GetMaxClip1() .. " (" .. left .. ")")
draw.Text({
text = tostring(wep:Clip1()) .. "/" .. wep:GetMaxClip1() .. " (" .. left .. ")",
font = font,
color = Color(0, 0, 0, 150),
yalign = TEXT_ALIGN_CENTER,
pos = {math.Clamp(aw - tw, 8, (w - 8) - tw), h / 2}
})
-- Shine
draw.RoundedBoxEx(0, 4, 4, w - 8, (h-8)/4, Color(255, 255, 255, 25), true, true, false, false)
-- Shadow
draw.RoundedBoxEx(0, 4, h - 4 - ((h-8)/4), w-8, (h-8)/4, Color(0, 0, 0, 50), false, false, true, true)
end
}
})
nadmin.hud:CreateCustom({
title = "Circular",
left = {
height = 128,
draw = function(panel, w, h)
draw.NoTexture()
-- Usage of custom function
-- draw.Circle(x, y, radius, seg, arc, angOffset, col)
local hp = math.Clamp(LocalPlayer():Health() / LocalPlayer():GetMaxHealth(), 0, 1)
local ar = math.Clamp(LocalPlayer():Armor() / 100, 0, 1)
local r = h/2
local res = 45
-- Main
draw.Circle(h/2, h/2, r, res, 360, 0, nadmin.colors.gui.theme)
-- HP Background
draw.Circle(h/2, h/2, r-8, res, 180, 90, nadmin:AlphaColor(nadmin.colors.gui.health, 50))
-- HP Bar
draw.Circle(h/2, h/2, r-8, res, 180 * hp, 90, nadmin.colors.gui.health)
-- Armor Background
draw.Circle(h/2, h/2, r-8, res, 180, -90, nadmin:AlphaColor(nadmin.colors.gui.armor, 50))
-- Armor Bar
draw.CircleInverse(h/2, h/2, r-8, res, 180 * ar, 90, nadmin.colors.gui.armor)
-- Cover
draw.Circle(h/2, h/2, r-20, res, 360, 0, nadmin.colors.gui.theme)
-- XP
if nadmin.plugins.levels then
local info = LocalPlayer():GetLevel()
local xp = math.Clamp(info.xp / info.need, 0, 1)
-- Background
draw.Circle(h/2, h/2, r-24, res, 360, 0, nadmin:AlphaColor(nadmin.colors.gui.xp, 50))
-- Bar
draw.Circle(h/2, h/2, r-24, res, 360 * xp, 180, nadmin.colors.gui.xp)
-- Cover
draw.Circle(h/2, h/2, r-28, res, 360, 0, nadmin.colors.gui.theme)
end
-- Draw HP and Armor values
draw.Circle(h/2, h/2, r-32, res, 360, 0, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
draw.Text({
text = LocalPlayer():Health(),
pos = {h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
font = "nadmin_hud_small",
color = nadmin.colors.gui.health
})
draw.Text({
text = LocalPlayer():Armor(),
pos = {h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_TOP,
font = "nadmin_hud_small",
color = nadmin.colors.gui.armor
})
end
},
right = {
height = 128,
draw = function(panel, w, h)
if not LocalPlayer():Alive() then return end
if not IsValid(LocalPlayer():GetActiveWeapon()) then return end
local wep = LocalPlayer():GetActiveWeapon()
local left = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
if wep:Clip1() < 0 or wep:GetMaxClip1() < 1 then return end
local ammo = math.Clamp(wep:Clip1() / wep:GetMaxClip1(), 0, 1)
local r = h/2
local res = 45
draw.NoTexture()
-- Main
draw.Circle(w - h/2, h/2, r, res, 360, 0, nadmin.colors.gui.theme)
-- Background
draw.Circle(w - h/2, h/2, r-8, res, 360, 0, nadmin:AlphaColor(nadmin.colors.gui.ammo, 50))
-- Bar
draw.CircleInverse(w - h/2, h/2, r-8, res, 360 * ammo, -90, nadmin.colors.gui.ammo)
-- Cover
draw.Circle(w - h/2, h/2, r-20, res, 360, 0, nadmin.colors.gui.theme)
-- Text
draw.Circle(w - h/2, h/2, r-24, res, 360, 0, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
draw.Text({
text = tostring(wep:Clip1()) .. "/" .. tostring(wep:GetMaxClip1()),
pos = {w - h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
font = "nadmin_hud_small",
color = nadmin.colors.gui.xp
})
draw.Text({
text = "(" .. left .. ")",
pos = {w - h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_TOP,
font = "nadmin_hud_small",
color = nadmin.colors.gui.xp
})
end
}
})
nadmin.hud:CreateCustom({
title = "Circular Simple",
left = {
height = 128,
draw = function(panel, w, h)
draw.NoTexture()
local r = h/2
local res = 60
local hp = math.Clamp(LocalPlayer():Health() / LocalPlayer():GetMaxHealth(), 0, 1)
local ar = math.Clamp(LocalPlayer():Armor() / 100, 0, 1)
-- Main background
draw.RoundedBox(0, 0, 0, h/2, h/2, nadmin.colors.gui.theme)
draw.RoundedBox(0, h/2, h/2, h/2, h/2, nadmin.colors.gui.theme)
draw.Circle(h/2, h/2, r, res, 360, 0, nadmin.colors.gui.theme)
-- HP background
draw.Circle(h/2, h/2, r-8, res, 270, 90, nadmin:AlphaColor(nadmin.colors.gui.health, 50))
-- HP bar
draw.Circle(h/2, h/2, r-8, res, 270 * hp, 90, nadmin.colors.gui.health)
-- Armor Background
draw.Circle(h/2, h/2, r-20, res, 270, 90, nadmin.colors.gui.theme)
draw.Circle(h/2, h/2, r-20, res, 270, 90, nadmin:AlphaColor(nadmin.colors.gui.armor, 50))
-- Armor bar
draw.Circle(h/2, h/2, r-20, res, 270 * ar, 90, nadmin.colors.gui.armor)
draw.Circle(h/2, h/2, r-32, res, 270, 90, nadmin.colors.gui.theme)
-- XP
if nadmin.plugins.levels then
local info = LocalPlayer():GetLevel()
local xp = math.Clamp(info.xp / info.need, 0, 1)
draw.Circle(h/2, h/2, r-32, res, 270, 90, nadmin:AlphaColor(nadmin.colors.gui.xp, 50))
draw.Circle(h/2, h/2, r-32, res, 270 * xp, 90, nadmin.colors.gui.xp)
draw.Circle(h/2, h/2, r-38, res, 360, 0, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
else
draw.Circle(h/2, h/2, r-32, res, 360, 0, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
end
-- Text
draw.Text({
text = LocalPlayer():Health(),
pos = {h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
font = "nadmin_hud_small",
color = nadmin.colors.gui.health
})
draw.Text({
text = LocalPlayer():Armor(),
pos = {h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_TOP,
font = "nadmin_hud_small",
color = nadmin.colors.gui.armor
})
end
},
right = {
height = 128,
draw = function(panel, w, h)
if not IsValid(LocalPlayer():GetActiveWeapon()) then return end
draw.NoTexture()
local wep = LocalPlayer():GetActiveWeapon()
local left = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
if wep:Clip1() < 0 or wep:GetMaxClip1() < 1 then return end
local ammo = math.Clamp(wep:Clip1() / wep:GetMaxClip1(), 0, 1)
local r = h/2
local res = 60
-- Main
draw.RoundedBox(0, w-h, h/2, h/2, h/2, nadmin.colors.gui.theme)
draw.RoundedBox(0, w-h/2, 0, h/2, h/2, nadmin.colors.gui.theme)
draw.Circle(w-h/2, h/2, r, res, 360, 0, nadmin.colors.gui.theme)
-- Bar
draw.CircleInverse(w-h/2, h/2, r-8, res, 270, -90, nadmin:AlphaColor(nadmin.colors.gui.ammo, 50))
draw.CircleInverse(w-h/2, h/2, r-8, res, 270 * ammo, -90, nadmin.colors.gui.ammo)
-- Cover
draw.Circle(w-h/2, h/2, r-20, res, 360, 0, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
draw.Text({
text = tostring(wep:Clip1()) .. "/" .. tostring(wep:GetMaxClip1()),
pos = {w - h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
font = "nadmin_hud_small",
color = nadmin.colors.gui.xp
})
draw.Text({
text = "(" .. left .. ")",
pos = {w - h/2, h/2},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_TOP,
font = "nadmin_hud_small",
color = nadmin.colors.gui.xp
})
end
}
})
nadmin.hud:CreateCustom({
title = "Fluid",
left = {
height = 128,
draw = function(panel, w, h)
local wid = h * 0.8
draw.RoundedBox(0, 0, 0, wid, h, nadmin.colors.gui.theme)
draw.RoundedBox(0, 4, 4, wid - 8, h-8, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
local hp = math.Clamp(LocalPlayer():Health()/LocalPlayer():GetMaxHealth(), 0, 1)
local ar = math.Clamp(LocalPlayer():Armor()/100, 0, 1)
local y = (h-4) - ((h-4) * hp)
draw.Fluid({
pos = {4, y},
size = {wid-8, (h-4) - y},
color = nadmin.colors.gui.health
})
draw.RoundedBox(0, 0, 0, wid, 4, nadmin.colors.gui.theme)
draw.Text({
text = LocalPlayer():Health(),
font = "nadmin_hud",
pos = {(wid/2) - 1, h-8},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
color = Color(0, 0, 0, 150)
})
for i = 1, 9 do
local y = ((h - 8) / 10) * i
draw.RoundedBox(0, 4, 2 + y, nadmin:Ternary(i == 5, 16, 8), 4, Color(0, 0, 0, 150))
end
local x = wid
if LocalPlayer():Armor() > 0 then
x = x + wid - 4
draw.RoundedBox(0, wid-4, 0, wid, h, nadmin.colors.gui.theme)
draw.RoundedBox(0, wid, 4, wid-8, h-8, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
local y = (h-4) - ((h-4) * ar)
draw.Fluid({
pos = {wid, y},
size = {wid-9, (h-4) - y},
color = nadmin.colors.gui.armor
})
draw.RoundedBox(0, wid-4, 0, wid, 4, nadmin.colors.gui.theme)
draw.Text({
text = LocalPlayer():Armor(),
font = "nadmin_hud",
pos = {(wid*1.5) - 5, h-8},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
color = Color(0, 0, 0, 150)
})
for i = 1, 9 do
local y = ((h - 8) / 10) * i
draw.RoundedBox(0, wid, 2 + y, nadmin:Ternary(i == 5, 16, 8), 4, Color(0, 0, 0, 150))
end
end
if nadmin.plugins.levels then
local info = LocalPlayer():GetLevel()
local xp = math.Clamp(info.xp/info.need, 0, 1)
draw.RoundedBox(0, x, 0, 8, h, nadmin.colors.gui.theme)
draw.RoundedBox(0, x, 4, 4, h - 8, nadmin:AlphaColor(nadmin.colors.gui.xp, 50))
local y = (h-4) - ((h-8)*xp)
draw.RoundedBox(0, x, y, 4, h - 4 - y, nadmin.colors.gui.xp)
end
end
},
right = {
height = 128,
draw = function(panel, w, h)
if not IsValid(LocalPlayer():GetActiveWeapon()) then return end
local wep = LocalPlayer():GetActiveWeapon()
local left = LocalPlayer():GetAmmoCount(wep:GetPrimaryAmmoType())
if wep:Clip1() < 0 or wep:GetMaxClip1() < 1 then return end
local ammo = math.Clamp(wep:Clip1() / wep:GetMaxClip1(), 0, 1)
local wid = h * 0.8
draw.RoundedBox(0, w - wid, 0, wid, h, nadmin.colors.gui.theme)
draw.RoundedBox(0, w - wid + 4, 4, wid - 8, h - 8, nadmin:DarkenColor(nadmin.colors.gui.theme, 25))
local y = (h-4) - ((h-4) * ammo)
draw.Fluid({
pos = {w - wid + 3, y},
size = {wid-8, (h-4) - y},
color = nadmin.colors.gui.ammo
})
draw.RoundedBox(0, w - wid, 0, wid, 4, nadmin.colors.gui.theme)
for i = 1, 9 do
local y = ((h - 8) / 10) * i
draw.RoundedBox(0, w - wid + 4, 2 + y, nadmin:Ternary(i == 5, 16, 8), 4, Color(0, 0, 0, 150))
end
surface.SetFont("nadmin_hud_small")
local current = tostring(wep:Clip1()) .. "/" .. tostring(wep:GetMaxClip1())
local width, height = surface.GetTextSize(current)
draw.Text({
text = current,
font = "nadmin_hud_small",
pos = {w - wid/2, (h - 7) - height},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
color = Color(0, 0, 0, 150)
})
draw.Text({
text = "(" .. tostring(left) .. ")",
font = "nadmin_hud_small",
pos = {w - wid/2, h - 7},
xalign = TEXT_ALIGN_CENTER,
yalign = TEXT_ALIGN_BOTTOM,
color = Color(0, 0, 0, 150)
})
end
}
})
-- Following HUD never finished, didn't look that great
nadmin.hud:CreateCustom({
title = "Skewed (Incomplete)",
left = {
height = 84,
draw = function(panel, w, h)
if LocalPlayer():Health() <= 0 then return end
draw.NoTexture()
-- Health bar
local maxWidH = w - 14
local maxWidHT = w * (7/8)
local th = nadmin.colors.gui.theme
surface.SetDrawColor(th.r, th.g, th.b)
surface.DrawPoly({
{x = 0, y = h-32},
{x = maxWidHT, y = h-32},
{x = w, y = h},
{x = 0, y = h}
})
local hp = nadmin.colors.gui.health
surface.SetDrawColor(hp.r, hp.g, hp.b, 25)
surface.DrawPoly({
{x = 4, y = h-28},
{x = maxWidHT, y = h-28},
{x = maxWidH, y = h-4},
{x = 4, y = h-4}
})
local health = math.Clamp(LocalPlayer():Health() / LocalPlayer():GetMaxHealth(), 0, 1) * maxWidH
surface.SetDrawColor(hp.r, hp.g, hp.b)
surface.DrawPoly({
{x = 4, y = h-28},
{x = math.Clamp(health - (maxWidH - maxWidHT), 4, maxWidHT), y = h-28},
{x = math.Clamp(health, 4, maxWidH), y = h-4},
{x = 4, y = h-4}
})
-- Armor bar
if LocalPlayer():Armor() > 0 then
local maxWidA = maxWidHT
local maxWidAT = w
surface.SetDrawColor(th.r, th.g, th.b)
surface.DrawPoly({
{x = 0, y = h-64},
{x = maxWidAT, y = h-64},
{x = maxWidA, y = h-32},
{x = 0, y = h-32}
})
local ar = nadmin.colors.gui.armor
surface.SetDrawColor(ar.r, ar.g, ar.b, 25)
surface.DrawPoly({
{x = 4, y = h-60},
{x = maxWidAT - 14, y = h-60},
{x = maxWidA - 4, y = h-36},
{x = 4, y = h-36}
})
local armor = math.Clamp(LocalPlayer():Armor() / 100, 0, 1) * maxWidAT - 14
surface.SetDrawColor(ar.r, ar.g, ar.b)
surface.DrawPoly({
{x = 4, y = h-60},
{x = math.Clamp(armor - (maxWidA - maxWidAT), 4, maxWidAT), y = h-60},
{x = math.Clamp(armor, 4, maxWidA - 4), y = h-36},
{x = 4, y = h-36}
})
if nadmin.plugins.levels then
draw.RoundedBox(0, 4, h - 34, maxWidHT - 8, 4, nadmin:AlphaColor(nadmin.colors.gui.xp, 25))
end
else
end
-- surface.SetDrawColor(nadmin.colors.gui.theme.r, nadmin.colors.gui.theme.g, nadmin.colors.gui.theme.b)
-- draw.NoTexture()
-- surface.DrawPoly({
-- {x = 16, y = 0},
-- {x = w, y = 0},
-- {x = w-h, y = h},
-- {x = 16, y = h}
-- })
-- local hp = nadmin.colors.gui.health
-- surface.SetDrawColor(hp.r, hp.g, hp.b, 25)
-- local hpPoly = {
-- {x = 40, y = 4},
-- {x = w-8, y = 4},
-- {x = w-40, y = 36},
-- {x = 40, y = 36}
-- }
-- surface.DrawPoly(hpPoly)
-- surface.SetDrawColor(hp.r, hp.g, hp.b)
-- local health = math.Clamp(LocalPlayer():Health()/LocalPlayer():GetMaxHealth(), 0, 1)
-- hpPoly[2].x = (w-8) * health
-- hpPoly[3].x = (w-8) * health - 32
-- surface.DrawPoly(hpPoly)
-- local ar = nadmin.colors.gui.armor
-- surface.SetDrawColor(ar.r, ar.g, ar.b, 25)
-- local arPoly = {
-- {x = 40, y = 44},
-- {x = w-50, y = 44},
-- {x = w-h-2, y = h-4},
-- {x = 40, y = h-4}
-- }
-- surface.DrawPoly(arPoly)
-- draw.RoundedBox(0, 0, 0, 32, h, nadmin.colors.gui.theme)
end
},
right = {
height = 40,
draw = function(self, w, h)
end
}
})
end |
BuildEnv(...)
Profile = Addon:NewModule('Profile', 'AceEvent-3.0', 'LibInvoke-1.0')
function Profile:OnInitialize()
local db = {
global = {
firstLogin = true,
planList = {},
trackList = {},
friend = {},
realmFeed = {},
worldFeed = {},
serverData = {},
},
profile = {
settings = {
objectives = true,
mountBlip = false,
petBlip = false,
autoTrack = true,
},
recommend = {},
showRecomment = 0,
}
}
self.planList = {}
self.trackList = {}
self.recommend = {}
self.db = LibStub('AceDB-3.0'):New('COLLECTOR_DB', db)
---- old var
self.db.profile.settings.blip = nil
self.db.RegisterCallback(self, 'OnDatabaseShutdown')
end
function Profile.Invoke:OnEnable()
---- PlanList
for i, v in ipairs(self.db.global.planList) do
local plan = Plan:Get(split(v))
if not plan:GetObject():IsCollected() then
tinsert(self.planList, plan)
end
end
---- TrackList
for i, v in ipairs(self.db.global.trackList) do
local plan = Plan:Get(split(v))
if not plan:GetObject():IsCollected() then
tinsert(self.trackList, plan)
end
end
---- Friend Feed
local bnids = {}
for i = 1, BNGetNumFriends() do
local id, _, battleTag = BNGetFriendInfo(i)
if battleTag then
bnids[battleTag] = id
end
end
local function makeCollectList(list)
for i, v in ipairs(list) do
list[i] = Collect:New(split(v))
end
return list
end
for k, v in pairs(self.db.global.friend) do
local id = not k:find('#', nil, true) and Ambiguate(k, 'none') or bnids[k]
if id then
local friend = Friend:Get(id)
friend:SetQueryStamp(v.queryStamp)
friend:SetFeedList(makeCollectList(v.feedList))
friend:SetPlanList(makeCollectList(v.planList))
end
end
---- Realm Feed
local realm = self:GetCurrentRealm()
do
local db = self.db.global.realmFeed[realm]
if db then
for k, v in pairs(db) do
local collectType, id = split(k)
local item = Addon:GetCollectTypeClass(collectType):Get(id)
item:SetRealmFeedList(DecodeTargetList(v))
end
end
end
---- World Feed
do
for k, v in pairs(self.db.global.worldFeed) do
local collectType, id, stamp = split(k)
local item = Addon:GetCollectTypeClass(collectType):Get(id)
item:SetQueryStamp(stamp)
item:SetWorldFeedList(DecodeTargetList(v))
end
end
----- firstLogin
if self.db.global.firstLogin then
self.db.global.firstLogin = false
self:SendMessage('COLLECTOR_FIRST_LOGIN')
end
----- recommend
do
local key = date('%Y-%m-%d')
if self.db.profile.recommend[key] then
for _, line in ipairs(self.db.profile.recommend[key]) do
local collectType, id, text = split(line)
local item = Addon:GetCollectTypeClass(collectType):Get(id)
item:SetRecommend(key, text)
end
self:SendMessage('COLLECTOR_RECOMMEND_UPDATE')
end
end
---- settings
local keys = { 'mountBlip', 'petBlip', 'objectives', 'autoTrack' }
for _, key in ipairs(keys) do
self:SendMessage('COLLECTOR_SETTING_UPDATE', key, self:GetVar(key))
end
end
function Profile:GetCurrentRealm()
local realms = GetAutoCompleteRealms()
return (not realms or not realms[1]) and GetRealmName() or realms[1]
end
function Profile:OnDatabaseShutdown()
wipe(self.db.global.planList)
wipe(self.db.global.trackList)
wipe(self.db.global.friend)
wipe(self.db.global.worldFeed)
wipe(self.db.profile.recommend)
for i, plan in ipairs(self.planList) do
self.db.global.planList[i] = plan:GetToken()
end
for i, plan in ipairs(self.trackList) do
self.db.global.trackList[i] = plan:GetToken()
end
---- Friend Feed
for _, friend in Friend:IterateObjects() do
local key = friend:GetDBKey()
if key and not friend:IsQueryTimeOut() then
self.db.global.friend[key] = friend:ToDB()
end
end
---- Realm Feed
local feedKlasses = { Mount, Pet }
local realm = self:GetCurrentRealm()
do
local db = {}
self.db.global.realmFeed[realm] = db
for _, mount in Mount:IterateObjects() do
db[mount:GetDBKey()] = mount:GetRealmFeedDB()
end
end
---- World Feed
do
for _, klass in ipairs(feedKlasses) do
for _, obj in klass:IterateObjects() do
if not obj:IsQueryTimeOut() then
self.db.global.worldFeed[obj:GetDBKey(true)] = obj:GetWorldFeedDB()
end
end
end
end
---- recommend
do
for _, mount in Mount:IterateObjects() do
local key = mount:IsRecommend()
if key then
self.db.profile.recommend[key] = self.db.profile.recommend[key] or {}
tinsert(self.db.profile.recommend[key], mount:GetDBKey() .. ':' .. mount:GetRecommendKey())
end
end
end
end
function Profile:GetPlanList()
return self.planList
end
function Profile:AddPlan(collectType, id)
tinsert(self.planList, Plan:Get(collectType, id))
self:SendMessage('COLLECTOR_PLAN_ADDED', collectType, id)
self:SendMessage('COLLECTOR_PLANLIST_UPDATE')
if self:GetVar('autoTrack') then
self:AddTrack(collectType, id)
end
end
function Profile:DelPlan(collectType, id)
local plan = Plan:Get(collectType, id)
local index = tIndexOf(self.planList, plan)
if not index then
return
end
tremove(self.planList, index)
self:SendMessage('COLLECTOR_PLAN_DELETED', collectType, id)
self:SendMessage('COLLECTOR_PLANLIST_UPDATE')
self:DelTrack(collectType, id)
end
function Profile:AddOrDelPlan(collectType, id)
if self:IsInPlan(collectType, id) then
self:DelPlan(collectType, id)
else
self:AddPlan(collectType, id)
end
end
function Profile:IsInPlan(collectType, id)
return tContains(self.planList, Plan:Get(collectType, id))
end
function Profile:GetTrackList()
return self.trackList
end
function Profile:AddTrack(collectType, id)
tinsert(self.trackList, Plan:Get(collectType, id))
self:SendMessage('COLLECTOR_TRACK_ADDED', collectType, id)
self:SendMessage('COLLECTOR_TRACKLIST_UPDATE')
end
function Profile:DelTrack(collectType, id)
tDeleteItem(self.trackList, Plan:Get(collectType, id))
self:SendMessage('COLLECTOR_TRACK_DELETED', collectType, id)
self:SendMessage('COLLECTOR_TRACKLIST_UPDATE')
end
function Profile:AddOrDelTrack(collectType, id)
if self:IsInTrack(collectType, id) then
self:DelTrack(collectType, id)
else
self:AddTrack(collectType, id)
end
end
function Profile:IsInTrack(collectType, id)
return tContains(self.trackList, Plan:Get(collectType, id))
end
function Profile:MovePlanToTop(collectType, id)
local plan = Plan:Get(collectType, id)
tDeleteItem(self.planList, plan)
tinsert(self.planList, 1, plan)
self:SendMessage('COLLECTOR_PLANLIST_UPDATE')
end
function Profile:GetServerData()
return self.db.global.serverData
end
function Profile:SetVar(key, value)
self.db.profile.settings[key] = value
self:SendMessage('COLLECTOR_SETTING_UPDATE', key, value)
end
function Profile:GetVar(key)
return self.db.profile.settings[key]
end
do
local blipData = {
{ key = 'mountBlip', type = COLLECT_TYPE_MOUNT },
{ key = 'petBlip', type = COLLECT_TYPE_PET },
}
local blipKlassesCache = setmetatable({}, {__index = function(t, k)
t[k] = {}
for i, v in ipairs(blipData) do
local b = bit.band(k, bit.lshift(1, i-1))
if b > 0 then
t[k][v.type] = true
end
end
return t[k]
end})
function Profile:GetBlipClasses()
local b = 0
for i, v in ipairs(blipData) do
if self:GetVar(v.key) then
b = bit.bor(b, bit.lshift(1, i-1))
end
end
return blipKlassesCache[b]
end
end
function Profile:IsRecommendShown()
local t = date('*t')
t.hour = 0
t.min = 0
t.sec = 0
t = time(t)
local r = self.db.profile.showRecomment == t
self.db.profile.showRecomment = t
return r
end
|
-----------------------------------
-- Area: Port Bastok
-- NPC: Paujean
-- Starts & Finishes Quest: Silence of the Rams
-- !pos -93.738 4.649 34.373 236
-----------------------------------
local ID = require("scripts/zones/Port_Bastok/IDs")
require("scripts/globals/settings")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onTrade(player, npc, trade)
local SilenceOfTheRams = player:getQuestStatus(BASTOK, tpz.quest.id.bastok.SILENCE_OF_THE_RAMS)
if (SilenceOfTheRams == QUEST_ACCEPTED) then
local count = trade:getItemCount()
local LumberingHorn = trade:hasItemQty(910, 1)
local RampagingHorn = trade:hasItemQty(911, 1)
if (LumberingHorn == true and RampagingHorn == true and count == 2) then
player:startEvent(196)
end
end
end
function onTrigger(player, npc)
local SilenceOfTheRams = player:getQuestStatus(BASTOK, tpz.quest.id.bastok.SILENCE_OF_THE_RAMS)
local WildcatBastok = player:getCharVar("WildcatBastok")
if (player:getQuestStatus(BASTOK, tpz.quest.id.bastok.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok, 2) == false) then
player:startEvent(355)
elseif (SilenceOfTheRams == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 2) then
player:startEvent(195)
elseif (SilenceOfTheRams == QUEST_ACCEPTED) then
player:showText(npc, ID.text.PAUJEAN_DIALOG_1)
else
player:startEvent(25)
end
end
function onEventUpdate(player, csid, option)
-- printf("CSID2: %u", csid)
-- printf("RESULT2: %u", option)
end
function onEventFinish(player, csid, option)
if (csid == 195) then
player:addQuest(BASTOK, tpz.quest.id.bastok.SILENCE_OF_THE_RAMS)
elseif (csid == 196) then
player:tradeComplete()
player:completeQuest(BASTOK, tpz.quest.id.bastok.SILENCE_OF_THE_RAMS)
player:addFame(3, 125)
player:addItem(13201)
player:messageSpecial(ID.text.ITEM_OBTAINED, 13201)
player:addTitle(tpz.title.PURPLE_BELT)
elseif (csid == 355) then
player:setMaskBit(player:getCharVar("WildcatBastok"), "WildcatBastok", 2, true)
end
end
|
-- =============================================================
-- Copyright Roaming Gamer, LLC. 2008-2018 (All Rights Reserved)
-- =============================================================
-- Actions Library - Target Acquisition Functions
-- =============================================================
local target = {}
_G.ssk.actions = _G.ssk.actions or {}
_G.ssk.actions.target = target
-- Forward Declarations
local angle2Vector = ssk.math2d.angle2Vector
local vector2Angle = ssk.math2d.vector2Angle
local scaleVec = ssk.math2d.scale
local addVec = ssk.math2d.add
local subVec = ssk.math2d.sub
local getNormals = ssk.math2d.normals
local lenVec = ssk.math2d.length
local len2Vec = ssk.math2d.length2
local normVec = ssk.math2d.normalize
local fnn = _G.fnn
local isValid = display.isValid
-- Lua and Corona
local mAbs = math.abs
local mRand = math.random
local mDeg = math.deg
local mRad = math.rad
local mCos = math.cos
local mSin = math.sin
local mAcos = math.acos
local mAsin = math.asin
local mSqrt = math.sqrt
local mCeil = math.ceil
local mFloor = math.floor
local mAtan2 = math.atan2
local mPi = math.pi
local getTimer = system.getTimer
--
-- Utility Functions
--
-- Set the target manually
target.set = function( obj, newTarget )
if( not isValid( obj ) ) then return end
obj._target = newTarget
end
-- Get the target manually
target.get = function( obj )
return obj._target
end
--
-- Actions
--
target.loseOnDestroyed = function( obj )
-- Has valid target? Exit now.
if( not obj._target.removeSelf ) then
obj._target = nil
end
return obj._target == nil
end
target.loseAtMaxDistance = function( obj, params )
local maxDist = params.maxDist or math.huge
local targets = params.targets
maxDist = maxDist ^ 2
local dist = subVec( obj, obj._target )
dist = len2Vec( dist )
if( dist >= maxDist ) then
obj._target = nil
end
return obj._target == nil
end
target.loseAtMinAlpha = function( obj, params )
-- If alpha below 'minAlpha' lose this target
if( obj._target.alpha <= (params.alpha or 0.5) ) then
obj._target = nil
end
return obj._target == nil
end
target.loseNotVisible = function( obj )
-- If not visible, lose this target
if( obj._target.isVisible == false) then
obj._target = nil
end
return obj._target == nil
end
-- Acquire nearest target from queue
target.acquireNearest = function( obj, params )
if( not isValid( obj ) ) then return end
if( not params or not params.targets ) then return end
obj._target = nil
local maxDist = params.maxDist or math.huge
local targets = params.targets
maxDist = maxDist ^ 2
local newTarget
local dist
local pairs = pairs
for k,v in pairs( targets ) do
if( isValid( v ) and not v._targeter ) then
dist = subVec( obj, v )
dist = len2Vec( dist )
if( dist <= maxDist ) then
maxDist = dist
newTarget = v
end
end
end
obj._target = newTarget
return (obj._target ~= nil)
end
-- Acquire nearest target from queue
target.acquireRandom = function( obj, params )
if( not isValid( obj ) ) then return end
if( not params or not params.targets ) then return end
obj._target = nil
local targets = params.targets
local tmpTargets = {}
if(#targets > 0) then
tmpTargets = targets
else
for k,v in pairs( targets ) do
tmpTargets[#tmpTargets+1] = v
end
end
obj._target = table.getRandom( tmpTargets )
return (obj._target ~= nil)
end
--
-- Debug Actions
--
-- Draw line between object and target if there is one
target.drawDebugLine = function( obj, params )
if( not isValid( obj ) ) then return end
params = params or {}
if( obj._lastline ) then display.remove( obj._lastline ) end
local group = params.parent or display.currentStage
obj._lastline = display.newLine( group, obj.x, obj.y, obj._target.x, obj._target.y )
obj._lastline:toBack()
obj._lastline.timer = function( self ) display.remove(self) end
timer.performWithDelay( 1, obj._lastline )
end
-- Print current distance to
target.drawDebugDistanceLabel = function( obj, params )
if( not isValid( obj ) ) then return end
params = params or {}
if( obj._lasttext ) then display.remove( obj._lasttext ) end
local dist = subVec( obj, obj._target )
dist = lenVec( dist )
dist = mFloor( dist + 0.5 )
local group = params.parent or display.currentStage
obj._lasttext = display.newText( group, round(dist), obj.x, obj.y, native.systemFont, 14 )
obj._lasttext.x = obj.x + (params.xOffset or 0)
obj._lasttext.y = obj.y + (params.yOffset or 0)
obj._lasttext.timer = function( self ) display.remove(self) end
timer.performWithDelay( 1, obj._lasttext )
end
-- Print current distance to
target.drawDebugAngleDistanceLabel = function( obj, params )
if( not isValid( obj ) ) then return end
params = params or {}
if( obj._lasttext ) then display.remove( obj._lasttext ) end
local dist = subVec( obj, obj._target )
dist = lenVec( dist )
dist = mFloor( dist + 0.5 )
local group = params.parent or display.currentStage
local targetAngle = subVec( obj, obj._target )
targetAngle = vector2Angle( targetAngle )
local angle = mFloor((targetAngle - obj.rotation) + 0.5)
angle = (angle + 180) % 360 - 180
obj._lasttext = display.newText( group, "< a:" .. round(angle) .. ", d:" .. round(dist) .. " >", obj.x, obj.y, native.systemFont, 14 )
obj._lasttext.x = obj.x + (params.xOffset or 0)
obj._lasttext.y = obj.y + (params.yOffset or 0)
obj._lasttext.timer = function( self ) display.remove(self) end
timer.performWithDelay( 1, obj._lasttext )
end
return target |
-- Class for deciding on what actions to take based on the current state,
-- using a relatively simple strategy.
local BaseAgent = require 'agent.BaseAgent'
require 'table'
require 'codes.direction'
require 'codes.item'
require 'codes.menu'
require 'codes.terrain'
require 'codes.species'
require 'codes.weather'
require 'dynamicinfo.menuinfo'
require 'actions.basicactions'
require 'actions.smartactions'
require 'utils.pathfinder'
require 'utils.messages'
local Agent = BaseAgent:__instance__()
Agent.name = 'SimpleAgent'
-- This function will be called once at startup. If you want your bot to retain
-- state or a memory, initialize stuff here!
function Agent:init(state, visible)
self.path = nil
self.targetPos = nil
self.targetName = nil
end
-- Set the target position, with an optional name
function Agent:setTargetPos(targetPos, targetName)
if not (self.targetPos and targetPos) or
not pathfinder.comparePositions(self.targetPos, targetPos) then
self.targetPos = targetPos
self.path = nil -- Need to calculate a new path
end
self.targetName = targetName
end
-- Return the tile under an entity
local function tileUnder(entity, layout)
return layout[entity.yPosition][entity.xPosition]
end
-- Decide how to attack an enemy given the circumstances, and perform the action.
-- If you're using different Pokemon, it might be sufficient just to rewrite this
-- method, and leave the main dungeon-crawling logic as is.
function Agent:attackEnemy(enemy, state, visible)
basicactions.attack()
end
-- Perform some actions based on the current state of the dungeon (and the bot's own state)
-- This is a very simple sample strategy. Change it to fit your botting needs.
function Agent:act(state, visible)
-- If in a Yes/No prompt, try to exit
if menuinfo.getMenu() == codes.MENU.YesNo then
basicactions.selectYesNo(1)
self.turnOngoing = true -- Not turn-ending
return
end
-- If trying to learn a new move, don't
if menuinfo.getMenu() == codes.MENU.NewMove then
basicactions.selectMoveToForget(4, true)
self.turnOngoing = true -- Not turn-ending
return
end
local leader = state.player.leader()
local leaderRoom = tileUnder(leader, state.dungeon.layout()).room
-- If no target position exists, or it's been reached, set it to the stairs
if not self.targetPos or pathfinder.comparePositions(
{leader.xPosition, leader.yPosition}, self.targetPos) then
self:setTargetPos({state.dungeon.stairs()}, 'Stairs')
end
-- If on the stairs and it's the current target, climb
if pathfinder.comparePositions(self.targetPos, {state.dungeon.stairs()}) and
pathfinder.comparePositions({leader.xPosition, leader.yPosition},
{state.dungeon.stairs()}) then
-- If HP isn't full and it makes sense to rest
-- (full belly, non damaging weather, no status),
-- then rest
if leader.stats.HP < leader.stats.maxHP and leader.belly > 0 and
#leader.statuses == 0 and (not (
state.dungeon.conditions.weather() == codes.WEATHER.Sandstorm or
state.dungeon.conditions.weather() == codes.WEATHER.Hail
) or state.dungeon.conditions.weatherIsNullified()) then
-- Don't rest if there are enemies in the room
local enemyInRoom = false
for _, enemy in ipairs(state.dungeon.entities.enemies()) do
if tileUnder(enemy, state.dungeon.layout()).room == leaderRoom then
enemyInRoom = true
end
end
if not enemyInRoom then
basicactions.rest(true)
return
end
end
-- Otherwise, go up the stairs
self:setTargetPos(nil) -- Clear the target
basicactions.climbStairs(true)
return
end
-- If there are items in the room, and there's room in the bag, go to pick them up
if #state.player.bag() < state.player.bagCapacity() and pathfinder.comparePositions(
self.targetPos, {state.dungeon.stairs()}) then
if leaderRoom ~= -1 then -- -1 means hallway
for _, item in ipairs(state.dungeon.entities.items()) do
-- Don't touch Kecleon's stuff
if tileUnder(item, state.dungeon.layout()).room == leaderRoom and
not item.inShop then
-- If a path can't be found, the item is inaccessible; ignore it
local path = pathfinder.getPath(
state.dungeon.layout(),
leader.xPosition, leader.yPosition,
item.xPosition, item.yPosition
)
if path then
self:setTargetPos({item.xPosition, item.yPosition},
codes.ITEM_NAMES[item.itemType])
-- Might as well save the result of the pathfinding
-- calculation we just did
self.path = pathfinder.getMoves(path)
break
end
end
end
end
end
-- If HP is low and there's an Oran Berry in the bag, eat it
if leader.stats.HP <= leader.stats.maxHP - 100 then
if smartactions.useItemTypeIfPossible(codes.ITEM.OranBerry, state, true) then
return
end
end
-- If belly is low and there's an Apple in the bag, eat it
if leader.belly <= 50 then
if smartactions.useItemTypeIfPossible(codes.ITEM.Apple, state, true) then
return
end
end
-- If all moves are out of PP and there's a Max Elixir in the bag, use it
local remainingPP = 0
for _, move in ipairs(leader.moves) do
remainingPP = remainingPP + move.PP
end
if remainingPP == 0 then
if smartactions.useItemTypeIfPossible(codes.ITEM.MaxElixir, state, true) then
return
end
end
-- If an enemy is nearby, attack it (unless it's a shopkeeper/ally)
for _, enemy in ipairs(state.dungeon.entities.enemies()) do
if not enemy.isShopkeeper and not enemy.isAlly and pathfinder.stepDistance(
{leader.xPosition, leader.yPosition}, {enemy.xPosition, enemy.yPosition}) <= 1 then
-- Step distance is quick to calculate, but isn't 100% accurate. We
-- really need to check that the actual path distance is 1. That way
-- we won't try to (regular) attack around corners. We can attack
-- even if the enemy is standing on water/lava/chasm, so count that
-- as "walkable" for this calculation along with normal terrain
local pathToEnemy = pathfinder.getPath(
state.dungeon.layout(),
leader.xPosition, leader.yPosition,
enemy.xPosition, enemy.yPosition,
function(terrain)
return terrain == codes.TERRAIN.Normal
or terrain == codes.TERRAIN.WaterOrLava
or terrain == codes.TERRAIN.Chasm
end
)
-- Exists, and just includes start and end, so path length is 1
if pathToEnemy and #pathToEnemy == 2 then
local direction = pathfinder.getDirection(
enemy.xPosition-leader.xPosition,
enemy.yPosition-leader.yPosition
)
if leader.direction ~= direction then
basicactions.face(direction)
end
messages.report('Attacking enemy ' ..
codes.SPECIES_NAMES[enemy.features.species] .. '.')
self:attackEnemy(enemy, state, visible)
return
end
end
end
-- If nothing of interest is nearby, keep moving toward the target
if not self.path or #self.path == 0 or not pathfinder.comparePositions(
{leader.xPosition, leader.yPosition}, self.path[1].start) then
-- Path is nonexistent or obsolete. Find a new path
local path = pathfinder.getPath(
state.dungeon.layout(),
leader.xPosition, leader.yPosition,
unpack(self.targetPos)
)
if not path then
error('Something went wrong. Unable to find path.')
end
self.path = pathfinder.getMoves(path)
end
if #self.path > 0 then
-- Not already on target
local text = 'Moving toward target'
if self.targetName then
text = text .. ': ' .. self.targetName
end
text = text .. '.'
messages.report(text)
local direction = table.remove(self.path, 1).direction
basicactions.walk(direction)
end
end
return Agent |
-- This module implements the flow metering app, which records
-- IP flows as part of an IP flow export program.
module(..., package.seeall)
local bit = require("bit")
local ffi = require("ffi")
local pf = require("pf")
local consts = require("apps.lwaftr.constants")
local lib = require("core.lib")
local ntohs = lib.ntohs
local htonl, htons = lib.htonl, lib.htons
local function htonq(v) return bit.bswap(v + 0ULL) end
local function ptr_to(ctype) return ffi.typeof('$*', ctype) end
local debug = lib.getenv("FLOW_EXPORT_DEBUG")
local IP_PROTO_TCP = 6
local IP_PROTO_UDP = 17
local IP_PROTO_SCTP = 132
-- These constants are taken from the lwaftr constants module, which
-- is maybe a bad dependency but sharing code is good
-- TODO: move constants somewhere else? lib?
local ethertype_ipv4 = consts.ethertype_ipv4
local ethertype_ipv6 = consts.ethertype_ipv6
local ethernet_header_size = consts.ethernet_header_size
local ipv6_fixed_header_size = consts.ipv6_fixed_header_size
local o_ethernet_ethertype = consts.o_ethernet_ethertype
local o_ipv4_total_length = consts.o_ipv4_total_length
local o_ipv4_ver_and_ihl = consts.o_ipv4_ver_and_ihl
local o_ipv4_proto = consts.o_ipv4_proto
local o_ipv4_src_addr = consts.o_ipv4_src_addr
local o_ipv4_dst_addr = consts.o_ipv4_dst_addr
local o_ipv6_payload_len = consts.o_ipv6_payload_len
local o_ipv6_next_header = consts.o_ipv6_next_header
local o_ipv6_src_addr = consts.o_ipv6_src_addr
local o_ipv6_dst_addr = consts.o_ipv6_dst_addr
local function string_parser(str)
local idx = 1
local quote = ('"'):byte()
local ret = {}
function ret.consume_upto(char)
local start_idx = idx
local byte = char:byte()
while str:byte(idx) ~= byte do
if str:byte(idx) == quote then
idx = idx + 1
while str:byte(idx) ~= quote do idx = idx + 1 end
end
idx = idx + 1
end
idx = idx + 1
return string.sub(str, start_idx, idx - 2)
end
function ret.is_done() return idx > str:len() end
return ret
end
-- Parse out available IPFIX fields.
local function make_ipfix_element_map()
local elems = require("apps.ipfix.ipfix_information_elements_inc")
local parser = string_parser(elems)
local map = {}
while not parser.is_done() do
local id = parser.consume_upto(",")
local name = parser.consume_upto(",")
local data_type = parser.consume_upto(",")
for i=1,8 do parser.consume_upto(",") end
parser.consume_upto("\n")
map[name] = { id = id, data_type = data_type }
end
return map
end
local ipfix_elements = make_ipfix_element_map()
local swap_fn_env = { htons = htons, htonl = htonl, htonq = htonq }
-- Create a table describing the information needed to create
-- flow templates and data records.
local function make_template_info(spec)
-- Representations of IPFIX IEs.
local ctypes =
{ unsigned8 = 'uint8_t', unsigned16 = 'uint16_t',
unsigned32 = 'uint32_t', unsigned64 = 'uint64_t',
ipv4Address = 'uint8_t[4]', ipv6Address = 'uint8_t[16]',
dateTimeMilliseconds = 'uint64_t' }
local bswap = { uint16_t='htons', uint32_t='htonl', uint64_t='htonq' }
-- the contents of the template records we will send
-- there is an ID & length for each field
local length = 2 * (#spec.keys + #spec.values)
local buffer = ffi.new("uint16_t[?]", length)
-- octets in a data record
local data_len = 0
local swap_fn = {}
local function process_fields(buffer, fields, struct_def, types, swap_tmpl)
for idx, name in ipairs(fields) do
local entry = ipfix_elements[name]
local ctype = assert(ctypes[entry.data_type],
'unimplemented: '..entry.data_type)
data_len = data_len + ffi.sizeof(ctype)
buffer[2 * (idx - 1)] = htons(entry.id)
buffer[2 * (idx - 1) + 1] = htons(ffi.sizeof(ctype))
table.insert(struct_def, '$ '..name..';')
table.insert(types, ffi.typeof(ctype))
if bswap[ctype] then
table.insert(swap_fn, swap_tmpl:format(name, bswap[ctype], name))
end
end
end
table.insert(swap_fn, 'return function(o)')
local key_struct_def = { 'struct {' }
local key_types = {}
process_fields(buffer, spec.keys, key_struct_def, key_types,
'o.key.%s = %s(o.key.%s)')
table.insert(key_struct_def, '} __attribute__((packed))')
local value_struct_def = { 'struct {' }
local value_types = {}
process_fields(buffer + #spec.keys * 2, spec.values, value_struct_def,
value_types, 'o.value.%s = %s(o.value.%s)')
table.insert(value_struct_def, '} __attribute__((packed))')
table.insert(swap_fn, 'end')
local key_t = ffi.typeof(table.concat(key_struct_def, ' '),
unpack(key_types))
local value_t = ffi.typeof(table.concat(value_struct_def, ' '),
unpack(value_types))
local record_t = ffi.typeof(
'struct { $ key; $ value; } __attribute__((packed))', key_t, value_t)
gen_swap_fn = loadstring(table.concat(swap_fn, '\n'))
setfenv(gen_swap_fn, swap_fn_env)
assert(ffi.sizeof(record_t) == data_len)
return { id = spec.id,
field_count = #spec.keys + #spec.values,
buffer = buffer,
buffer_len = length * 2,
data_len = data_len,
key_t = key_t,
value_t = value_t,
record_t = record_t,
record_ptr_t = ptr_to(record_t),
swap_fn = gen_swap_fn(),
match = pf.compile_filter(spec.filter)
}
end
local uint16_ptr_t = ffi.typeof('uint16_t *')
local function get_ipv4_ihl(l3)
return bit.band((l3 + o_ipv4_ver_and_ihl)[0], 0x0f)
end
local function get_ipv4_protocol(l3) return l3[o_ipv4_proto] end
local function get_ipv6_next_header(l3) return l3[o_ipv6_next_header] end
local function get_ipv4_src_addr_ptr(l3) return l3 + o_ipv4_src_addr end
local function get_ipv4_dst_addr_ptr(l3) return l3 + o_ipv4_dst_addr end
local function get_ipv6_src_addr_ptr(l3) return l3 + o_ipv6_src_addr end
local function get_ipv6_dst_addr_ptr(l3) return l3 + o_ipv6_dst_addr end
local function read_ipv4_src_address(l3, dst)
ffi.copy(dst, get_ipv4_src_addr_ptr(l3), 4)
end
local function read_ipv4_dst_address(l3, dst)
ffi.copy(dst, get_ipv4_dst_addr_ptr(l3), 4)
end
local function read_ipv6_src_address(l3, dst)
ffi.copy(dst, get_ipv6_src_addr_ptr(l3), 16)
end
local function read_ipv6_dst_address(l3, dst)
ffi.copy(dst, get_ipv6_dst_addr_ptr(l3), 16)
end
local function get_tcp_src_port(l4)
return ntohs(ffi.cast(uint16_ptr_t, l4)[0])
end
local function get_tcp_dst_port(l4)
return ntohs(ffi.cast(uint16_ptr_t, l4)[1])
end
v4 = make_template_info {
id = 256,
filter = "ip",
keys = { "sourceIPv4Address",
"destinationIPv4Address",
"protocolIdentifier",
"sourceTransportPort",
"destinationTransportPort" },
values = { "flowStartMilliseconds",
"flowEndMilliseconds",
"packetDeltaCount",
"octetDeltaCount"}
}
function v4.extract(pkt, timestamp, entry)
local l2 = pkt.data
local l3 = l2 + ethernet_header_size
local ihl = get_ipv4_ihl(l3)
local l4 = l3 + ihl * 4
-- Fill key.
-- FIXME: Try using normal Lua assignment.
read_ipv4_src_address(l3, entry.key.sourceIPv4Address)
read_ipv4_dst_address(l3, entry.key.destinationIPv4Address)
local prot = get_ipv4_protocol(l3)
entry.key.protocolIdentifier = prot
if prot == IP_PROTO_TCP or prot == IP_PROTO_UDP or prot == IP_PROTO_SCTP then
entry.key.sourceTransportPort = get_tcp_src_port(l4)
entry.key.destinationTransportPort = get_tcp_dst_port(l4)
else
entry.key.sourceTransportPort = 0
entry.key.destinationTransportPort = 0
end
-- Fill value.
entry.value.flowStartMilliseconds = timestamp
entry.value.flowEndMilliseconds = timestamp
entry.value.packetDeltaCount = 1
-- Measure bytes starting with the IP header.
entry.value.octetDeltaCount = pkt.length - ethernet_header_size
end
function v4.accumulate(dst, new)
dst.value.flowEndMilliseconds = new.value.flowEndMilliseconds
dst.value.packetDeltaCount = dst.value.packetDeltaCount + 1
dst.value.octetDeltaCount =
dst.value.octetDeltaCount + new.value.octetDeltaCount
end
function v4.tostring(entry)
local ipv4 = require("lib.protocol.ipv4")
local key = entry.key
local protos =
{ [IP_PROTO_TCP]='TCP', [IP_PROTO_UDP]='UDP', [IP_PROTO_SCTP]='SCTP' }
return string.format(
"%s (%d) -> %s (%d) [%s]",
ipv4:ntop(key.sourceIPv4Address), key.sourceTransportPort,
ipv4:ntop(key.destinationIPv4Address), key.destinationTransportPort,
protos[key.protocolIdentifier] or tostring(key.protocolIdentifier))
end
v6 = make_template_info {
id = 257,
filter = "ip6",
keys = { "sourceIPv6Address",
"destinationIPv6Address",
"protocolIdentifier",
"sourceTransportPort",
"destinationTransportPort" },
values = { "flowStartMilliseconds",
"flowEndMilliseconds",
"packetDeltaCount",
"octetDeltaCount" }
}
function v6.extract(pkt, timestamp, entry)
local l2 = pkt.data
local l3 = l2 + ethernet_header_size
-- TODO: handle chained headers
local l4 = l3 + ipv6_fixed_header_size
-- Fill key.
-- FIXME: Try using normal Lua assignment.
read_ipv6_src_address(l3, entry.key.sourceIPv6Address)
read_ipv6_dst_address(l3, entry.key.destinationIPv6Address)
local prot = get_ipv6_next_header(l3)
entry.key.protocolIdentifier = prot
if prot == IP_PROTO_TCP or prot == IP_PROTO_UDP or prot == IP_PROTO_SCTP then
entry.key.sourceTransportPort = get_tcp_src_port(l4)
entry.key.destinationTransportPort = get_tcp_dst_port(l4)
else
entry.key.sourceTransportPort = 0
entry.key.destinationTransportPort = 0
end
-- Fill value.
entry.value.flowStartMilliseconds = timestamp
entry.value.flowEndMilliseconds = timestamp
entry.value.packetDeltaCount = 1
-- Measure bytes starting with the IP header.
entry.value.octetDeltaCount = pkt.length - ethernet_header_size
end
function v6.accumulate(dst, new)
dst.value.flowEndMilliseconds = new.value.flowEndMilliseconds
dst.value.packetDeltaCount = dst.value.packetDeltaCount + 1
dst.value.octetDeltaCount =
dst.value.octetDeltaCount + new.value.octetDeltaCount
end
function v6.tostring(entry)
local ipv6 = require("lib.protocol.ipv6")
local key = entry.key
local protos =
{ [IP_PROTO_TCP]='TCP', [IP_PROTO_UDP]='UDP', [IP_PROTO_SCTP]='SCTP' }
return string.format(
"%s (%d) -> %s (%d) [%s]",
ipv6:ntop(key.sourceIPv6Address), key.sourceTransportPort,
ipv6:ntop(key.destinationIPv6Address), key.destinationTransportPort,
protos[key.protocolIdentifier] or tostring(key.protocolIdentifier))
end
function selftest()
print('selftest: apps.ipfix.template')
local datagram = require("lib.protocol.datagram")
local ether = require("lib.protocol.ethernet")
local ipv4 = require("lib.protocol.ipv4")
local ipv6 = require("lib.protocol.ipv6")
local udp = require("lib.protocol.udp")
local packet = require("core.packet")
local function test(src_ip, dst_ip, src_port, dst_port)
local is_ipv6 = not not src_ip:match(':')
local proto = is_ipv6 and ethertype_ipv6 or ethertype_ipv4
local eth = ether:new({ src = ether:pton("00:11:22:33:44:55"),
dst = ether:pton("55:44:33:22:11:00"),
type = proto })
local ip
if is_ipv6 then
ip = ipv6:new({ src = ipv6:pton(src_ip), dst = ipv6:pton(dst_ip),
next_header = IP_PROTO_UDP, ttl = 64 })
else
ip = ipv4:new({ src = ipv4:pton(src_ip), dst = ipv4:pton(dst_ip),
protocol = IP_PROTO_UDP, ttl = 64 })
end
local udp = udp:new({ src_port = src_port, dst_port = dst_port })
local dg = datagram:new()
dg:push(udp)
dg:push(ip)
dg:push(eth)
local pkt = dg:packet()
assert(v4.match(pkt.data, pkt.length) == not is_ipv6)
assert(v6.match(pkt.data, pkt.length) == is_ipv6)
local templ = is_ipv6 and v6 or v4
local entry = templ.record_t()
local timestamp = 13
templ.extract(pkt, 13, entry)
if is_ipv6 then
assert(ip:src_eq(entry.key.sourceIPv6Address))
assert(ip:dst_eq(entry.key.destinationIPv6Address))
else
assert(ip:src_eq(entry.key.sourceIPv4Address))
assert(ip:dst_eq(entry.key.destinationIPv4Address))
end
assert(entry.key.protocolIdentifier == IP_PROTO_UDP)
assert(entry.key.sourceTransportPort == src_port)
assert(entry.key.destinationTransportPort == dst_port)
assert(entry.value.flowStartMilliseconds == timestamp)
assert(entry.value.flowEndMilliseconds == timestamp)
assert(entry.value.packetDeltaCount == 1)
assert(entry.value.octetDeltaCount == pkt.length - ethernet_header_size)
packet.free(pkt)
end
for i=1, 100 do
local src_ip, dst_ip
if math.random(1,2) == 1 then
src_ip = string.format("192.168.1.%d", math.random(1, 254))
dst_ip = string.format("10.0.0.%d", math.random(1, 254))
else
src_ip = string.format("2001:4860:4860::%d", math.random(1000, 9999))
dst_ip = string.format("2001:db8::ff00:42:%d", math.random(1000, 9999))
end
local src_port, dst_port = math.random(1, 65535), math.random(1, 65535)
test(src_ip, dst_ip, src_port, dst_port)
end
print("selftest ok")
end
|
--[[
Copyright © 2018, Langly of Quetzalcoatl
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of React nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Langly BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
-- Future: Find a successful event to trigger unbusy() for casting and abilities. (Action Complete packet most likely)
-- Added trading if set to slave (for cells)
-- Correct the issue where trading multiple times for displacers if more than 1 stack exists.
-- Fixed: Corrected issue with 'falls to the ground' from DoT. - 8.30.2018
-- Fixed: Added in Displacer usage per fight. - 8.4.2018
-- Fixed: Pyxis delay for large parties/alliances - 7.30.2018
-- Fixed: Build pet ID's into party list for detection of mob death - 7.28.2018
_addon.name = 'AutoWatch'
_addon.author = 'Langly'
_addon.version = '1.10'
_addon.date = '10.11.2018'
_addon.commands = {'autowatch', 'aw'}
packets = require('packets')
pack = require('pack')
config = require('config')
files = require('files')
res = require('resources')
texts = require('texts')
extdata = require('extdata')
require('coroutine')
require('tables')
require('strings')
require('logger')
require('sets')
----------------------------------------------------------------
-- Globals
----------------------------------------------------------------
-- Text Setup
defaults = {}
defaults.display = {}
defaults.display.pos = {}
defaults.display.pos.x = 0
defaults.display.pos.y = 0
defaults.display.bg = {}
defaults.display.bg.red = 0
defaults.display.bg.green = 0
defaults.display.bg.blue = 0
defaults.display.bg.alpha = 150
defaults.display.text = {}
defaults.display.text.font = 'Arial'
defaults.display.text.red = 255
defaults.display.text.green = 255
defaults.display.text.blue = 255
defaults.display.text.alpha = 255
defaults.display.text.size = 9
settings = config.load(defaults)
settings:save()
text_box = texts.new(settings.display, settings)
info = {}
-- Character
Player = windower.ffxi.get_player()
info.player_target = 'None'
info.player_displacer = 0
info.player_name = Player.name
info.player_hpp = 0
info.player_mpp = 0
info.player_tp = 0
info.player_x = 0
info.player_y = 0
info.player_z = 0
info.busy = false
info.status = 'None'
info.once = T{}
info.limbo2_time = 0
info.settings = {}
info.settings.target = 'None'
info.settings.master = true
info.settings.slave = false
info.settings.leech = false
info.settings.actions = T{}
info.settings.trusts = T{}
info.settings.should_engage = true
info.settings.displacer = 0
info.settings.rubicund = 0
info.settings.cells = false
----------------------------------------------------------------
-- Automation Params
----------------------------------------------------------------
switch = false
busy = false
command_delay = 0
target = {}
runtarget = {}
pyxis_delay = 0
use_displacers = 0
windower.register_event('load', function()
initialize()
profile = files.new(Player.name..'_'..Player.main_job..'.lua')
notice('Welcome to AutoWatch, type //aw help for a list of commands.')
if profile:exists() then
notice('Using configurations specified in: '..Player.name..'_'..Player.main_job..'.lua')
else
notice('Generated configuration file.')
profile:write('return ' .. T(info.settings):tovstring())
end
info.settings = require(Player.name..'_'..Player.main_job)
end)
function initialize(text, settings)
local infobox = L{}
infobox:append(' Character: ${player_name|None} Status: ${status|None}')
infobox:append(' Vitals > HPP: ${player_hpp|0} MPP: ${player_mpp|0} TP: ${player_tp|0}')
infobox:append(' Position > X: ${player_x|0} Y: ${player_y|0} Z: ${player_z|0}')
infobox:append(' Busy: ${busy|false} Target: ${player_target|None}')
infobox:append(' ------------------------------------------------------------- ')
infobox:append(' AutoWatch: ${switch|Off} Use Displacers: ${displacers|0}')
text_box:clear()
text_box:append(infobox:concat('\n'))
end
text_box:register_event('reload', initialize)
----------------------------------------------------------------
-- Commands
----------------------------------------------------------------
windower.register_event('addon command', function (command, ...)
command = command and command:lower()
local args = T{...}
if command == "help" then
notice('AutoWatch will smite a VW target ad infinitum.')
notice('Provided you have stones available to pop the NM.')
notice('Commands: ')
notice(' //aw target <name> will set your target.')
notice(' //aw start will engage the bot and begin work.')
notice(' //aw stop will disengage the bot and let you resume control.')
notice(' //aw slave will toggle the bot between active and passive behavior.')
notice(' //aw action will add actions to your master/slave lists.')
notice(' //Example: //aw action "Tachi: Fudo" tp 1000')
notice(' //Example: //aw action "Erratic Flutter" absent Haste')
notice(' //Example: //aw action "Ramuh" absent pet')
notice(' //Example: //aw action Berserk ready')
notice('Please start the bot near the Planar Rift you wish to use.')
return
end
if command == "target" then
if args[1] then
info.settings.target = args[1]
notice('Target: '..args[1]..'.')
end
update_configuration()
return
end
if command == "start" then
if info.settings.target == nil then
warning('AutoWatch must have a target to operate.')
return
end
notice('Starting AutoWatch.')
switch = true
if info.status == 'None' and info.settings.master then
info.status = 'Build Party'
else
info.status = 'Trade Cells'
end
return
end
if command == "stop" then
notice('Stopping AutoWatch.')
switch = false
return
end
if command == 'slave' then
if slave then
info.settings.slave = false
notice('Slave Mode: Off')
else
info.settings.slave = true
info.settings.master = false
info.settings.leech = false
notice('Slave Mode: On')
end
update_configuration()
return
end
if command == 'leech' then
if leech then
info.settings.leech = false
notice('Leech Mode: Off')
else
info.settings.leech = true
info.settings.slave = false
info.settings.master = false
info.settings.should_engage = false
notice('Leech Mode: On')
end
update_configuration()
return
end
if command == 'master' then
if master then
info.settings.master = false
notice('Master Mode: Off')
else
info.settings.master = true
info.settings.slave = false
info.settings.leech = false
notice('Master Mode: On')
end
update_configuration()
return
end
if command == "displacer" then
local n = tonumber(args[1])
if n then
notice('Using displacers: '..n..' per fight.')
info.settings.displacer = n
update_configuration()
return
end
end
if command == "rubicund" then
local n = tonumber(args[1])
if n and n <= 1 then
notice('Using Rubicund Cells: '..n..' per fight.')
info.settings.rubicund = n
update_configuration()
return
else
notice('Rubicund can only be 0 or 1.')
end
end
if command == 'engage' then
if args[1] then
info.settings.should_engage = args[1]
notice('This character is set to engage the target: '..args[1]..'.')
else
if info.settings.should_engage then
info.settings.should_engage = false
notice('Should engage target: Off')
else
info.settings.should_engage = true
notice('Should engage target: On')
end
end
update_configuration()
return
end
if command == "status" then
info.status = args[1]
return
end
if command == "action" then
add_action(args)
update_configuration()
return
end
if command == 'list' then
listrules()
return
end
if command == 'test' then
update_configuration()
end
if command == 'yiss' or command == 'snap' or command == 'shucks' then
notice('Blorb.')
send_cmd('input /dance4 motion')
end
if command == 'shit' then
send_cmd('input /s Hnggg')
end
if command == 'trust' then
manage_trusts(args)
update_configuration()
return
end
end)
----------------------------------------------------------------
-- Events
----------------------------------------------------------------
windower.register_event('outgoing chunk', function(id, data)
if id == 0x015 then
local p = packets.parse('outgoing', data)
info.player_h = p["Rotation"]
end
end)
windower.register_event('prerender', function()
update_info_panel()
test_limbo2_time()
if busy == true then windower.ffxi.run(false) end
if switch == true and busy == false then
update_status_based_on_role()
if info.status == 'Waiting for Pop' then
return
end
if info.settings.master or info.settings.rubicund > 0 then
if info.status == 'Build Party' and busy == false and info.settings.master then
gather_trusts()
end
if info.status == 'Trade Cells' and busy == false then
if info.settings.displacer > 0 or info.settings.rubicund > 0 then
local rift = pick_nearest(get_marray('Planar Rift'))
if rift[1].valid_target then
face_target(rift[1].id)
if distance(rift[1].x,rift[1].y) < 6 then
notice('Trading displacers to Rift.')
local rubicund_left = info.settings.rubicund
local displacer_left = info.settings.displacer
local trade_packet = packets.new('outgoing', 0x36, {
['Target'] = rift[1].id,
['Target Index'] = rift[1].index,})
local inventory = windower.ffxi.get_items(0)
local idx = 1
for index=1,inventory.max do
if inventory[index].id == 3853 and phase_displacers_available() > 0 and displacer_left > 0 then
trade_packet['Item Index %d':format(idx)] = index
if phase_displacers_available() > info.settings.displacer then
trade_packet['Item Count %d':format(idx)] = info.settings.displacer
displacer_left = displacer_left - info.settings.displacer
else
trade_packet['Item Count %d':format(idx)] = phase_displacers_available()
displacer_left = displacer_left - phase_displacers_available()
end
idx = idx + 1
elseif inventory[index].id == 3435 and rubicund_available() > 0 and rubicund_left > 0 then
trade_packet['Item Index %d':format(idx)] = index
trade_packet['Item Count %d':format(idx)] = 1
idx = idx + 1
rubicund_left = rubicund_left - 1
end
end
trade_packet['Number of Items'] = idx
packets.inject(trade_packet)
use_displacers = info.settings.displacer
busy = true
info.status = 'Attempting Pop'
coroutine.schedule(unbusy, 1)
return
else
runto(rift[1])
end
end
return
end
if info.settings.displacer == 0 then
info.status = 'Attempting Pop'
return
end
end
if info.status == 'Attempting Pop' then
local rift = pick_nearest(get_marray('Planar Rift'))
if rift[1].valid_target then
face_target(rift[1].id)
if distance(rift[1].x,rift[1].y) < 6 then
notice('Injecting 0x01A on Rift.')
poke_npc(rift[1].id, rift[1].index)
info.status = 'Limbo'
busy = true
coroutine.schedule(unbusy, 3)
return
else
runto(rift[1])
end
end
return
end
end
if (not info.settings.leech) then
local player = windower.ffxi.get_player()
locate_target()
if info.status == 'Combat' then
if info.settings.should_engage == true then
if player.status ~= 1 and target.id then
local mob = windower.ffxi.get_mob_by_id(target.id)
if mob.valid_target then
attack(target.id,target.index)
end
return
end
end
if player.status == 1 or info.settings.slave then
if player.target_locked then
send_cmd('input /lockon')
end
if info.settings.should_engage == true then
if busy == true then windower.ffxi.run(false) return end
face_target(target.id)
check_distance(target.id)
end
test_actions()
return
end
end
end
if info.status == 'Pyxis' and busy == false then
local pyxis = pick_nearest(get_marray('Riftworn Pyxis'))
if pyxis[1].valid_target then
notice('Found valid Pyxis.')
face_target(pyxis[1].id)
if distance(pyxis[1].x,pyxis[1].y) < 6 then
notice('Injecting 0x01A on Pyxis after delay.')
info.status = 'Limbo2'
info.limbo2_time = os.time()
coroutine.schedule(poke_pyxis, determine_pyxis_delay())
else
notice('Closing in on Pyxis.')
runto(pyxis[1])
end
end
end
end
end)
windower.register_event('incoming chunk',function(id,data,modified,injected,blocked)
if switch then
if id == 0x29 then -- Mob died
local p = packets.parse('incoming',data)
local target_id = p['Target'] --data:unpack('I',0x09)
local player_id = p['Actor']
local message_id = p['Message'] --data:unpack('H',0x19)%32768
-- 6 == actor defeats target
if message_id == 6 and windower.ffxi.get_mob_by_id(target_id).name == info.settings.target then
local party_table = windower.ffxi.get_party()
local party_ids = T{}
for _,member in pairs(party_table) do
if type(member) == 'table' and member.mob then
party_ids:append(member.mob.id)
end
end
for i,v in pairs(party_ids) do
local pet_idx = windower.ffxi.get_mob_by_id(v).pet_index or nil
if pet_idx then
party_ids:append(windower.ffxi.get_mob_by_index(pet_idx).id)
end
end
if player_id == windower.ffxi.get_player().id or party_ids:contains(player_id) then
notice('Killed by '..windower.ffxi.get_mob_by_id(player_id).name..'.')
table.clear(target)
windower.ffxi.run(false)
busy = true
info.status = 'Pyxis'
coroutine.schedule(unbusy, 2)
end
end
-- 20 == target falls to the ground
if message_id == 20 and windower.ffxi.get_mob_by_id(target_id).name == info.settings.target then
notice('Killed by dot.')
table.clear(target)
windower.ffxi.run(false)
busy = true
info.status = 'Pyxis'
coroutine.schedule(unbusy, 2)
end
end
if id == 0x034 then
local p = packets.parse('incoming',data)
if windower.ffxi.get_mob_by_id(p.NPC).name == 'Planar Rift' and info.status == 'Limbo' then
local disp_option = {[0] = 0x01, [1] = 0x11, [2] = 0x21, [3] = 0x31, [4] = 0x41, [5] = 0x51}
notice('Received 0x034 from Rift. Blocking menu.')
notice('Popping VW nm.')
vwpop(p["NPC"],p["NPC Index"],p["Zone"],p["Menu ID"],disp_option[use_displacers])
use_displacers = 0
info.status = 'Combat'
end
if windower.ffxi.get_mob_by_id(p.NPC).name == 'Riftworn Pyxis' and info.status == 'Limbo2' then
local rare_item = false
local total_items = 0
local rare_items = 0
local pickup = T{}
local pulsable = T{[18457] = 'Murasamemaru',[18542] = 'Aytanri',[18904] = 'Ephemeron',[19144] = 'Coruscanti',[19145] = 'Asteria',[19174] = 'Borealis',[19794] = 'Delphinius',}
local option_index = nil
local pulse = nil
notice('Received 0x034 from Pyxis. Blocking menu.')
for i=1,8 do
local itm = p['Menu Parameters']:unpack('I', 1 + (i - 1)*4)
if not (itm == 0) then
if rare(itm) and have_item(itm) then
rare_item = true
rare_items = rare_items +1
end
if pulsable[itm] and have_item(itm) then
pickup.item = itm
pulse = 1
end
total_items = total_items + 1
end
if itm == 5910 then
send_cmd('input /p Woohoo~!')
end
end
if pickup.index then
--Send the packet to pickup the pulsed item.
pyxis(p["NPC"],p["NPC Index"],p["Zone"],p["Menu ID"],pickup.item,1)
busy = true
notice('Pulsing item. Will re-enter menu.')
coroutine.schedule(unbusy, 2)
info.status = 'Pyxis'
info.limbo2_time = 0
else
if rare_items == total_items then
notice('Relinquishing remainder of rare items.')
pyxis(p["NPC"],p["NPC Index"],p["Zone"],p["Menu ID"],9,0)
notice('Attempting Pop.')
info.status = 'Trade Cells'
info.limbo2_time = 0
else
if rare_item then
notice('Would obtain all but need to re-enter to relinquish remainder of rare items.')
notice('Obtaining all Spoils.')
busy = true
pyxis(p["NPC"],p["NPC Index"],p["Zone"],p["Menu ID"],10,0)
coroutine.schedule(unbusy, 2)
info.status = 'Pyxis'
info.limbo2_time = 0
else
notice('Obtaining all Spoils.')
busy = true
pyxis(p["NPC"],p["NPC Index"],p["Zone"],p["Menu ID"],10,0)
coroutine.schedule(unbusy, 2)
notice('Attempting Pop.')
info.status = 'Trade Cells'
info.limbo2_time = 0
end
end
end
end
return true
end
end
end)
windower.register_event('job change', function()
send_cmd('lua r autowatch')
end)
----------------------------------------------------------------
-- Builders
----------------------------------------------------------------
function update_info_panel()
if windower.ffxi.get_player() then
local player = windower.ffxi.get_player()
local position = windower.ffxi.get_mob_by_index(player.index) or {x=0,y=0,z=0}
info.player_name = player.name
info.player_status = res.statuses[player.status].en
info.player_hpp = player.vitals.hpp
info.player_mpp = player.vitals.mpp
info.player_tp = player.vitals.tp
info.player_target = info.settings.target
info.player_x = string.format('%.2f', tostring(position.x or 0))
info.player_y = string.format('%.2f', tostring(position.y or 0))
info.player_z = string.format('%.2f', tostring(position.z or 0))
info.busy = busy
info.switch = switch
info.displacers = info.settings.displacer
text_box:update(info)
text_box:show()
end
end
function commaformat(number) -- Prettys up some numbers for human consumption
return string.format("%d", number):reverse():gsub( "(%d%d%d)" , "%1," ):reverse():gsub("^,","")
end
function add_action(args)
local abil_name = args[1] or nil
local abil_prefix = 'none'
local abil_condition = args[2] or nil
local abil_modifier = args[3] or nil
local allowed_conditions = T{'absent','tp','ready'}
local abil_count = table.getn(info.settings.actions) + 1
if abil_name then
local action = res.spells:with('en',abil_name) or res.job_abilities:with('en',abil_name) or res.weapon_skills:with('en',abil_name) or args[1]
if action and args[2] == 'raw' and args[3] then
info.settings.actions[abil_count] = {}
info.settings.actions[abil_count].action = action
info.settings.actions[abil_count].prefix = ''
info.settings.actions[abil_count].condition = 'raw'
info.settings.actions[abil_count].modifier = args[3] -- Must be tied to a recast like 'Monster'
notice('Adding raw command tied to ability timer '..args[3]..'.')
return
end
if action == nil or args[2] == nil then
warning('AutoWatch cannot find action: '..abil_name..'. Or you did not specify a condition.')
return
else
abil_name = action.name
abil_prefix = action.prefix
if table.find(allowed_conditions, args[2]) then
if abil_condition == 'tp' then
if tonumber(args[3]) < 1000 then
abil_modifier = 1000
end
elseif abil_condition == 'absent' then
if args[3] == nil then
warning('The absent condition requires a specified status paired with this condition. Ex: //aw action "Erratic Flutter" absent Haste')
return
end
elseif abil_condition == 'ready' then
abil_modifier = ''
end
else
warning('Unrecognized condition specified: '..args[2]..'. Please use an allowed condition. (absent, tp, ready)')
return
end
info.settings.actions[abil_count] = {}
info.settings.actions[abil_count].action = abil_name
info.settings.actions[abil_count].prefix = abil_prefix
info.settings.actions[abil_count].condition = abil_condition
info.settings.actions[abil_count].modifier = abil_modifier
notice('Successfully added action '..abil_name..' when '..abil_condition..' '..abil_modifier..'.')
end
end
end
function update_configuration()
profile:write('return ' .. T(info.settings):tovstring())
end
function test_actions()
local actions = info.settings.actions
local mob = windower.ffxi.get_mob_by_id(target.id)
local player = windower.ffxi.get_player()
for i,v in ipairs(actions) do
if v.condition == 'tp' then
if tonumber(player.vitals.tp) >= tonumber(v.modifier) and distance(mob.x,mob.y) < 3 then
busy = true
send_cmd('input '..v.prefix..' '..v.action)
coroutine.schedule(unbusy, 3)
end
else
--Determine Recast Eligibility
local action = res.spells:with('en',v.action) or res.job_abilities:with('en',v.action) or res.weapon_skills:with('en',v.action)
local ability_recast = 0
local charges = 0
if v.prefix == "/jobability" then
ability_recast = windower.ffxi.get_ability_recasts()[res.job_abilities[res.job_abilities:with('en',v.action).id].recast_id]
elseif v.prefix == "/magic" or v.prefix == "/ninjutsu" or v.prefix == "/song" then
ability_recast = windower.ffxi.get_spell_recasts()[res.spells[res.spells:with('en',v.action).id].recast_id]
elseif v.prefix == "/pet" then
local ability = res.job_abilities[action.id]
if ability.type == "BloodPactRage" then
ability_recast = windower.ffxi.get_ability_recasts()[173]
elseif ability.type == "BloodPactWard" then
ability_recast = windower.ffxi.get_ability_recasts()[174]
end
end
if v.condition == 'raw' and v.modifier == "Monster" then
ability_recast = windower.ffxi.get_ability_recasts()[102]
charges = math.floor(((15 * 3) - ability_recast) / 15)
end
if v.condition == 'absent' then
if v.modifier:lower() == 'pet' then
local pet = windower.ffxi.get_mob_by_target('pet') or nil
if pet == nil then
busy = true
send_cmd('input '..v.prefix..' "'..v.action..'"')
coroutine.schedule(unbusy, 4)
end
end
if (not has_buff(v.modifier)) and ability_recast == 0 and v.modifier ~= 'pet' then
busy = true
send_cmd('input '..v.prefix..' '..v.action)
if v.prefix == "/magic" or v.prefix == "/ninjutsu" or v.prefix == "/song" then
-- Fix this, to detect when my status is not casting rather than a blanket 5 seconds.
coroutine.schedule(unbusy, 5)
else
coroutine.schedule(unbusy, 3)
end
end
elseif v.condition == 'ready' then
if ability_recast == 0 then
if v.prefix == "/pet" then
busy = true
send_cmd('input '..v.prefix..' "'..v.action..'" <bt>')
coroutine.schedule(unbusy, 3)
end
busy = true
send_cmd('input '..v.prefix..' '..v.action)
coroutine.schedule(unbusy, 3)
end
elseif v.condition == 'raw' and v.modifier == 'Monster' then
if charges > 0 then
busy = true
send_cmd(v.action)
coroutine.schedule(unbusy, 3)
end
end
end
end
end
function listrules()
if info.settings.actions then
notice('Actions for current file are as listed: ')
for i,v in pairs(info.settings.actions) do
notice('Use '..v.action..' when '..v.condition..' '..v.modifier..'.')
end
else
notice('No actions found in current file.')
end
end
----------------------------------------------------------------
-- Asserts
----------------------------------------------------------------
function headingto(x,y)
local x = x - windower.ffxi.get_mob_by_id(windower.ffxi.get_player().id).x
local y = y - windower.ffxi.get_mob_by_id(windower.ffxi.get_player().id).y
local h = math.atan2(x,y)
return h - 1.5708
end
function inventory_space()
local inventory = windower.ffxi.get_bag_info(0)
local free = inventory.max - inventory.count
return free
end
function distance(x, y)
local self_vector = windower.ffxi.get_mob_by_index(windower.ffxi.get_player().index or 0)
local dx = x - self_vector.x
local dy = y - self_vector.y
return math.sqrt(dx*dx + dy*dy)
end
function in_party(name)
local name = name or 'None'
local party = windower.ffxi.get_party()
for _,v in pairs(party) do
if type(v) == 'table' then
if v.name == name then
return true
end
end
end
return false
end
function inventory_space()
local inventory = windower.ffxi.get_bag_info(0)
local free = inventory.max - inventory.count
return free
end
function check_claim(id)
local id = id or 0
local player_id = windower.ffxi.get_player().id
local mob = windower.ffxi.get_mob_by_id(id)
local party_table = windower.ffxi.get_party()
local party_ids = T{}
for _,member in pairs(party_table) do
if type(member) == 'table' and member.mob then
party_ids:append(member.mob.id)
end
end
for i,v in pairs(party_ids) do
local pet_idx = windower.ffxi.get_mob_by_id(v).pet_index or nil
if pet_idx then
party_ids:append(windower.ffxi.get_mob_by_index(pet_idx).id)
end
end
if party_ids:contains(mob.claim_id) then
return true
end
return false
end
function has_buff(buff)
local buffs = convert_buff_list(windower.ffxi.get_player()['buffs'])
for _,v in pairs(buffs) do
if v == buff then
return true
end
end
return false
end
function convert_buff_list(bufflist)
local buffarr = {}
for i,v in pairs(bufflist) do
if res.buffs[v] then
buffarr[#buffarr+1] = res.buffs[v].english
end
end
return buffarr
end
function phase_displacers_available()
local count = 0
local inventory = windower.ffxi.get_items().inventory
for index=1,inventory.max do
if inventory[index].id == 3853 then
count = inventory[index].count
end
end
return count
end
function rubicund_available()
local count = 0
local inventory = windower.ffxi.get_items().inventory
for index=1,inventory.max do
if inventory[index].id == 3435 then
count = inventory[index].count
end
end
return count
end
function locate_target()
local marray = get_marray(info.settings.target)
for _,v in pairs(marray) do
if check_claim(v.id) then
target.id,target.index = v.id,v.index
end
end
end
function get_marray(--[[optional]]name)
--[[ Format of new Mob Array
Returns an array of comprehensive mob data. Useful fields below.
number:
id, index, claim_id, x, y, z, distance, facing, entity type, target index,
spawn_type, status, model_scale, heading, model_size, movement_speed,
string:
name,
booleans:
is_npc, in_alliance, charmed, in_party, valid_target
--]]
local marray = windower.ffxi.get_mob_array()
local target_name = name or nil
local new_marray = T{}
for i,v in pairs(marray) do
if v.id == 0 or v.index == 0 then
marray[i] = nil
end
end
-- If passed a target name, strip those that do not match
if target_name then
for i,v in pairs(marray) do
if v.name ~= target_name then
marray[i] = nil
end
end
end
for i,v in pairs(marray) do
new_marray[#new_marray + 1] = windower.ffxi.get_mob_by_index(i)
end
return new_marray
end
function pick_nearest(--[[optional]]mob_table)
local dist_target = 0
local closest_key = 0
local marray = mob_table or get_marray()
local new_marray = T{}
for k,v in pairs(marray) do
if dist_target == 0 then
closest_key = k
dist_target = math.sqrt(v['distance'])
elseif math.sqrt(v['distance']) < dist_target then
closest_key = k
dist_target = math.sqrt(v['distance'])
end
end
for k,v in pairs(marray) do
if k == closest_key then
new_marray[1] = v
end
end
return new_marray
end
----------------------------------------------------------------
-- Actors
----------------------------------------------------------------
function poke_npc(id, index)
if id and index then
local packet = packets.new('outgoing', 0x01A, {
["Target"]=id,
["Target Index"]=index,
["Category"]=0,
["Param"]=0,
["_unknown1"]=0})
packets.inject(packet)
end
end
function attack(id, index)
if id then
local packet = packets.new('outgoing', 0x01A, {
["Target"]=id,
["Target Index"]=index,
["Category"]=2,
["Param"]=0,
["_unknown1"]=0})
packets.inject(packet)
end
end
function poke_pyxis()
local pyxis = pick_nearest(get_marray('Riftworn Pyxis'))
local id = pyxis[1].id
local index = pyxis[1].index
local packet = packets.new('outgoing', 0x01A, {
["Target"]=id,
["Target Index"]=index,
["Category"]=0,
["Param"]=0,
["_unknown1"]=0})
packets.inject(packet)
end
function pyxis(id, index, zone, menuid, option_index, pulse)
local option_index = option_index or 10
local pulse = pulse or 0
local packet = packets.new('outgoing', 0x05B, {
["Target"]=id,
["Target Index"]=index,
["_unknown1"]=pulse,
["Automated Message"]=false,
["_unknown2"]=0,
["Option Index"]=option_index,
["Menu ID"]=menuid,
["Zone"]=zone})
packets.inject(packet)
end
-- Uses max displacers by using 0x51
function vwpop(id, index, zone, menuid, displacer)
local packet = packets.new('outgoing', 0x05B, {
["Target"]=id,
["Target Index"]=index,
["Option Index"]=displacer,
["_unknown1"]=0,
["Automated Message"]=false,
["_unknown2"]=0,
["Menu ID"]=menuid,
["Zone"]=zone})
packets.inject(packet)
end
function trade_displacers()
end
function unbusy()
busy = false
end
function manage_trusts(args)
local cmd = args[1] or nil
local trust = args[2] or nil
local trust_list = info.settings.trusts
local trust_count = table.getn(info.settings.trusts)
if cmd == nil then
return
end
if cmd == 'add' then
if trust_count >= 5 then
notice('Five trusts already exist in trust table.')
return
end
info.settings.trusts[trust_count + 1] = trust
notice('Adding '..trust..' to your trust table.')
elseif cmd == 'remove' then
for i,v in pairs(info.settings.trusts) do
if v == trust then
table.delete(info.settings.trusts, trust)
notice('Removing '..trust..' from your trust table.')
end
end
end
end
function update_status_based_on_role()
if info.settings.master then
return
end
if info.settings.leech then
if info.status ~= 'Pyxis' or info.status ~= 'Limbo2' then
info.status = 'Pyxis'
return
end
end
if info.settings.slave then
if info.settings.rubicund > 0 and info.status == 'None' then
info.status = 'Trade Cells'
end
if info.status == 'Trade Cells' and info.settings.rubicund == 0 then
info.status = 'Waiting for Pop'
end
if info.status == 'None' then
info.status = 'Waiting for Pop'
end
if info.status == 'Attempting Pop' or info.status == "Build Party" then
info.status = 'Waiting for Pop'
end
if info.status == 'Waiting for Pop' then
locate_target()
if target.id then
local mob = windower.ffxi.get_mob_by_id(target.id)
if mob.valid_target and mob.hpp > 0 then
info.status = 'Combat'
end
end
end
end
end
function runto(target)
runtarget.x = target.x
runtarget.y = target.y
local self_vector = windower.ffxi.get_mob_by_index(windower.ffxi.get_player().index or 0)
local angle = (math.atan2((target.y - self_vector.y), (target.x - self_vector.x))*180/math.pi)*-1
windower.ffxi.run((angle):radian())
end
function face_target(target)
local destX = windower.ffxi.get_mob_by_id(target).x
local destY = windower.ffxi.get_mob_by_id(target).y
local direction = math.abs(info.player_h - math.deg(headingto(destX,destY)))
if direction > 10 then
windower.ffxi.turn(headingto(destX,destY))
end
end
function gather_trusts()
local party = windower.ffxi.get_party()
local trusts = info.settings.trusts
local trust_count = table.length(trusts)
local n = 0
for i,v in pairs(trusts) do
if in_party(v) then
n = n +1
end
end
if party.party1_count == 6 or n == trust_count then
notice('At maximum party members - or all trusts specified have been summoned.')
info.status = 'Trade Cells'
return
end
if busy == false then
for i,v in ipairs(trusts) do
if not in_party(v) then
notice(v..' not in party. Summoning.')
summon_trust(v)
return
end
end
end
end
function summon_trust(name)
busy = true
local name = name or 'None'
if name == 'Apururu' then
name = 'apururuuc'
end
if name == 'yoran-oran' then
name = 'yoran-oran uc'
end
windower.send_command(name)
coroutine.schedule(unbusy, 5)
end
function send_cmd(str)
local cmd = str or nil
if cmd then
windower.send_command(cmd)
end
end
function determine_pyxis_delay()
local self = windower.ffxi.get_player().name
local members = {}
for k, v in pairs(windower.ffxi.get_party()) do
if type(v) == 'table' then
members[#members + 1] = v.name
end
end
table.sort(members)
for k, v in pairs(members) do
if v == self then
return (k - 1) * .4 + 1
end
end
end
function player_update()
local packet = packets.new('outgoing', 0x016, {["Target Index"]=windower.ffxi.get_mob_by_id(windower.ffxi.get_player().id).index,})
packets.inject(packet)
end
function rare(id)
if res.items[id].flags['Rare'] then
return true
end
return false
end
function have_item(id)
local items = windower.ffxi.get_items()
local bags = {'inventory'}
for k, v in pairs(bags) do
for index = 1, items["max_%s":format(v)] do
if items[v][index].id == id then
return true
end
end
end
return false
end
function test_limbo2_time()
if info.status == 'Limbo2' then
local now_time = os.time()
if os.difftime(now_time, info.limbo2_time) >= 6 then
info.status = 'Pyxis'
end
end
end
function check_distance(id)
if busy == true then windower.ffxi.run(false) return end
local target_id = id or 0
local self_vector = windower.ffxi.get_mob_by_index(windower.ffxi.get_player().index or 0)
local mob = pick_nearest(get_marray(info.settings.target))
local angle = (math.atan2((mob[1].y - self_vector.y), (mob[1].x - self_vector.x))*180/math.pi)*-1
local distance = mob[1].distance:sqrt()
if distance > 3 then
windower.ffxi.run((angle):radian())
elseif distance < .9 then
local angle = (math.atan2((mob[1].y - self_vector.y), (mob[1].x - self_vector.x))*180/math.pi)*-1
windower.ffxi.run((angle+180):radian())
else
windower.ffxi.run(false)
end
end
|
local wrapper = require("core.lib.wrapper")
local EventUtil = require("core.EventUtil")
return {
event = function(state)
return function(self, socket, args)
local say = EventUtil.genSay(socket)
local write = EventUtil.genWrite(socket)
if not args.dontwelcome then
write("<cyan>Confirm your password:");
socket:command("toggleEcho");
end
socket:once("data", function(pass)
socket:command("toggleEcho");
if not args.account:checkPassword(wrapper.trim(pass)) then
say("<red>Passwords do not match.");
return socket:emit("change-password", socket, args);
end
say(""); -- echo was disabled, the user's Enter didn't make a newline
return socket:emit(args.nextStage, socket, args);
end)
end
end,
}
|
DCT_Opfont_CurFontID = 4
DCT_Opfont_ColorList = {
{0,0,0},
{0,0,0},
{0,0,0},
{0.4,0.4,0.9},
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
{0,0,0},
}
function DCT_Opfont_FontRefresh()
DCTFontOption:Hide()
DCTFontOption:Show()
end
function DCT_Opfont_OnShow(self)
local obj
for i = 1,12 do
getglobal("DCTFontOptionFontFrame"..i):SetPoint("TOPLEFT", "DCTFontOption", "TOPLEFT", 35, 20 - 30 * i )
getglobal("DCTFontOptionFontFrame"..i.."N"):SetBackdropColor(DCT_Opfont_ColorList[i][1],DCT_Opfont_ColorList[i][2],DCT_Opfont_ColorList[i][3])
getglobal("DCTFontOptionFontFrame"..i.."P"):SetBackdropColor(DCT_Opfont_ColorList[i][1],DCT_Opfont_ColorList[i][2],DCT_Opfont_ColorList[i][3])
getglobal("DCTFontOptionFontFrame"..i.."N_Text"):SetText(DCT_Font[i].name)
getglobal("DCTFontOptionFontFrame"..i.."P_Text"):SetText(DCT_Font[i].path)
getglobal("DCTFontOptionFontFrame"..i.."_Label"):SetText(i.."."..DCT_TEXT_OPFONT_NAME)
getglobal("DCTFontOptionFontFrame"..i.."_Path"):SetText(DCT_TEXT_OPFONT_PATH)
if DCT_Font[i].active then
getglobal("DCTFontOptionFontFrame"..i.."N_Text"):SetTextColor(1,1,1)
getglobal("DCTFontOptionFontFrame"..i.."P_Text"):SetTextColor(1,1,1)
else
getglobal("DCTFontOptionFontFrame"..i.."N_Text"):SetTextColor(0.4,0.4,0.4)
getglobal("DCTFontOptionFontFrame"..i.."P_Text"):SetTextColor(0.4,0.4,0.4)
end
end
DCTFontOptionEditN.EnterPressFunc = DCT_Opfont_EditNPress
DCTFontOptionEditN:SetText(DCT_Font[DCT_Opfont_CurFontID].name)
DCTFontOptionEditNLabel:SetText(DCT_TEXT_OPFONT_NAME)
DCTFontOptionEditP.EnterPressFunc = DCT_Opfont_EditPPress
DCTFontOptionEditP:SetText(DCT_Font[DCT_Opfont_CurFontID].path)
DCTFontOptionEditPLabel:SetText(DCT_TEXT_OPFONT_PATH)
DCTFontOption_EditTitle:SetText(DCT_TEXT_OPFONT_EDIT)
end
function DCT_Opfont_EditNPress(self)
DCT_Font[DCT_Opfont_CurFontID].name = self:GetText()
DCT_CheckAllFont()
DCT_Opfont_FontRefresh()
end
function DCT_Opfont_EditPPress(self)
DCT_Font[DCT_Opfont_CurFontID].path = self:GetText()
DCT_CheckAllFont()
DCT_Opfont_FontRefresh()
end
function DCT_Opfont_Frame_OnMouseDown(self, button)
local objname = self:GetName()
local c = string.len(objname)
local key = tonumber(string.sub(objname,23,c))
if key > 3 and key ~= DCT_Opfont_CurFontID then
DCT_Opfont_ColorList[DCT_Opfont_CurFontID] = {0,0,0}
getglobal("DCTFontOptionFontFrame"..DCT_Opfont_CurFontID.."N"):SetBackdropColor(0,0,0)
getglobal("DCTFontOptionFontFrame"..DCT_Opfont_CurFontID.."P"):SetBackdropColor(0,0,0)
DCT_Opfont_CurFontID = key
DCT_Opfont_ColorList[DCT_Opfont_CurFontID][1] = 0.4
DCT_Opfont_ColorList[DCT_Opfont_CurFontID][2] = 0.4
DCT_Opfont_ColorList[DCT_Opfont_CurFontID][3] = 0.9
DCTFontOptionEditN:SetText(DCT_Font[DCT_Opfont_CurFontID].name)
DCTFontOptionEditP:SetText(DCT_Font[DCT_Opfont_CurFontID].path)
end
end
|
do --- operators
local y = 0
for i=1,100 do local a, b = 23, 11; y = a+b end; assert(y == 23+11)
for i=1,100 do local a, b = 23, 11; y = a-b end; assert(y == 23-11)
for i=1,100 do local a, b = 23, 11; y = a*b end; assert(y == 23*11)
for i=1,100 do local a, b = 23, 11; y = a/b end; assert(y == 23/11)
for i=1,100 do local a, b = 23, 11; y = a%b end; assert(y == 23%11)
for i=1,100 do local a, b = 23, 11; y = a^b end; assert(y == 23^11)
for i=1,100 do local a, b = 23.5, 11.5; y = a+b end; assert(y == 23.5+11.5)
for i=1,100 do local a, b = 23.5, 11.5; y = a-b end; assert(y == 23.5-11.5)
for i=1,100 do local a, b = 23.5, 11.5; y = a*b end; assert(y == 23.5*11.5)
for i=1,100 do local a, b = 23.5, 11.5; y = a/b end; assert(y == 23.5/11.5)
for i=1,100 do local a, b = 23.5, 11.5; y = a%b end; assert(y == 23.5%11.5)
end
do --- abs
local y = 0
for i=1,100 do local a=23; y = math.abs(a) end; assert(y == math.abs(23))
for i=1,100 do local a=-23; y = math.abs(a) end; assert(y == math.abs(-23))
for i=1,100 do local a=23.5; y = math.abs(a) end; assert(y == math.abs(23.5))
for i=1,100 do local a=-23.5; y = math.abs(a) end; assert(y==math.abs(-23.5))
for i=1,100 do local a=-2^31; y = math.abs(a) end; assert(y==math.abs(-2^31))
end
do --- atan2 ldexp
local y = 0
for i=1,100 do local a, b = 23, 11; y = math.atan2(a, b) end
assert(y == math.atan2(23, 11))
for i=1,100 do local a, b = 23, 11; y = math.ldexp(a, b) end
assert(y == math.ldexp(23, 11))
end
do --- minmax
local y = 0
for i=1,100 do local a, b = 23, 11; y = math.min(a, b) end
assert(y == math.min(23, 11))
for i=1,100 do local a, b = 23, 11; y = math.max(a, b) end
assert(y == math.max(23, 11))
for i=1,100 do local a, b = 23.5, 11.5; y = math.min(a, b) end
assert(y == math.min(23.5, 11.5))
for i=1,100 do local a, b = 23.5, 11.5; y = math.max(a, b) end
assert(y == math.max(23.5, 11.5))
for i=1,100 do local a, b = 11, 23; y = math.min(a, b) end
assert(y == math.min(11, 23))
for i=1,100 do local a, b = 11, 23; y = math.max(a, b) end
assert(y == math.max(11, 23))
for i=1,100 do local a, b = 11.5, 23.5; y = math.min(a, b) end
assert(y == math.min(11.5, 23.5))
for i=1,100 do local a, b = 11.5, 23.5; y = math.max(a, b) end
assert(y == math.max(11.5, 23.5))
end
do --- floorceil
local y = 0
for i=1,100 do local a=23; y=math.floor(a) end assert(y==math.floor(23))
for i=1,100 do local a=23.5; y=math.floor(a) end assert(y==math.floor(23.5))
for i=1,100 do local a=-23; y=math.floor(a) end assert(y==math.floor(-23))
for i=1,100 do local a=-23.5; y=math.floor(a) end assert(y==math.floor(-23.5))
for i=1,100 do local a=-0; y=math.floor(a) end assert(y==math.floor(-0))
for i=1,100 do local a=23; y=math.ceil(a) end assert(y==math.ceil(23))
for i=1,100 do local a=23.5; y=math.ceil(a) end assert(y==math.ceil(23.5))
for i=1,100 do local a=-23; y=math.ceil(a) end assert(y==math.ceil(-23))
for i=1,100 do local a=-23.5; y=math.ceil(a) end assert(y==math.ceil(-23.5))
for i=1,100 do local a=-0; y=math.ceil(a) end assert(y==math.ceil(-0))
end
do --- sqrt exp log trig
local y = 0
for i=1,100 do local a=23; y=math.sqrt(a) end assert(y==math.sqrt(23))
for i=1,100 do local a=23; y=math.exp(a) end assert(y==math.exp(23))
for i=1,100 do local a=23; y=math.log(a) end assert(y==math.log(23))
for i=1,100 do local a=23; y=math.log10(a) end assert(y==math.log10(23))
for i=1,100 do local a=23; y=math.sin(a) end assert(y==math.sin(23))
for i=1,100 do local a=23; y=math.cos(a) end assert(y==math.cos(23))
-- UJIT: An ugly temporary hack for macOS where math functions from VM core
-- UJIT: and libm yield different results
if jit and jit.os == "Linux" then
for i=1,100 do local a=23; y=math.tan(a) end assert(y==math.tan(23))
end
end
do --- exp -luajit==2.0
assert((10^-2 - 0.01) == 0)
end
|
local _, G = ...
G.Eventer({
PLAYER_LOGIN = function()
ChatFrame1:ClearAllPoints()
ChatFrame1:SetClampRectInsets(0, 0, 0, 0)
ChatFrame1:SetPoint('BOTTOMLEFT', UIParent, 2, 30)
ChatFrame1:SetHeight(180)
ChatFrame1:SetWidth(400)
ChatFrame1:SetUserPlaced(true)
end,
})
|
--
-- Many colors support 'active', 'inactive', and 'disabled' states.
-- They can all be set to the same color with the syntax:
--
-- key = '<color>'
--
-- Or set individually with syntax like:
--
-- key = { active = '<color>', inactive = '<color>', disabled = '<color>' }
--
-- Use the 'default' key set one state individually and the remainder
-- to a default value:
--
-- key = { default = '<color>', disabled = '<color>' }
--
-- generic colors used to render borders and separators
-- { default, active, inactive, disabled }
theme['palette'] = {
-- These names correspond to a dark on light theme.
-- The values should be inverted in light on dark themes.
light = '#1E1F23', -- inverse of dark
midlight = '#212226', -- inverse of middark
middark = '#2D2E34', -- inverse of midlight
dark = '#36373E', -- inverse of light
-- This should always be a dark color.
shadow = '#212226'
}
-- the colors of text entry, list view, and other widgets
-- { default, active, inactive, disabled }
theme['widget'] = {
text = { default = '#E1E5F2', disabled = '#555B65' },
bright_text = '#AAB2BE',
background = '#212226',
highlight = { active = '#2A82DA', inactive = '#1B5B9B' },
highlighted_text = { active = '#E1E5F2', inactive = '#E1E5F2' },
}
-- window colors
-- { default, active, inactive, disabled }
theme['window'] = {
text = '#E1E5F2',
background = '#2D2E34'
}
-- button colors
-- { default, active, inactive, disabled, checked, pressed }
theme['button'] = {
text = { default = '#E1E5F2', inactive = '#555B65', disabled = '#555B65' },
background = { default = '#2D2E34', checked = '#2A82DA', pressed = '#2A82DA' }
}
-- commit list colors
-- { default, active, inactive, disabled }
theme['commits'] = {
text = '#E1E5F2',
bright_text = '#AAB2BE',
background = '#2D2E34',
highlight = { active = '#2A82DA', inactive = '#1B5B9B' },
highlighted_text = { active = '#E1E5F2', inactive = '#E1E5F2' },
highlighted_bright_text = { active = '#A6CBF0', inactive = '#9090A5' }
}
-- file list colors
-- { default, active, inactive, disabled }
theme['files'] = {
text = '#E1E5F2',
background = '#36373E',
alternate = '#2D2E34', -- an alternate background color for list rows
highlight = { active = '#2A82DA', inactive = '#1B5B9B' },
highlighted_text = { active = '#E1E5F2', inactive = '#E1E5F2' },
}
-- status badge colors
-- { normal, selected, conflicted, head, notification }
theme['badge'] = {
foreground = {
normal = '#E1E5F2',
selected = '#2A82DA'
},
background = {
normal = '#2A82DA', -- the default color
selected = '#E1E5F2', -- the color when a list item is selected
conflicted = '#DA2ADA', -- the color of conflicted items
head = '#52A500', -- a bolder color to indicate the HEAD
notification = '#8C2026' -- the color of toolbar notifications badges
}
}
-- blame margin heatmap background colors
theme['blame'] = {
cold = '#282940',
hot = '#5E3638'
}
-- graph edge colors
theme['graph'] = {
edge1 = '#53AFEC',
edge2 = '#82DA2A',
edge3 = '#DA2ADA',
edge4 = '#DA822A',
edge5 = '#2ADADA',
edge6 = '#DA2A82',
edge7 = '#84A896',
edge8 = '#2ADA82',
edge9 = '#822ADA',
edge10 = '#66D1E0',
edge11 = '#D3C27E',
edge12 = '#95CB80',
edge13 = '#50D4BE',
edge14 = '#2ADA82',
edge15 = '#DA822A'
}
-- checkbox colors
-- { default, active, inactive, disabled }
theme['checkbox'] = {
text = '#E1E5F2',
fill = '#535359',
outline = '#3C3C42'
}
-- diff view colors
theme['diff'] = {
addition = '#394734', -- added lines
deletion = '#5E3638', -- deleted lines
plus = '#207A00', -- plus icon
minus = '#BC0009', -- minus icon
ours = '#000060', -- ours conflict lines
theirs = '#600060', -- theirs conflict lines
word_addition = '#296812', -- added words
word_deletion = '#781B20', -- deleted words
note = '#E1E5F2', -- note squiggle
warning = '#E8C080', -- warning background
error = '#7E494B' -- error background
}
-- link colors
-- { default, active, inactive, disabled }
theme['link'] = {
link = '#2A82DA',
link_visited = '#FF00FF'
}
-- menubar background color
theme['menubar'] = {
text = '#212226',
background = '#F0F0F0'
}
-- tabbar background color (uncomment lines to customize)
theme['tabbar'] = {
-- text = theme['widget']['text'],
-- base = theme['palette']['dark'],
-- selected = theme['window']['background'],
}
-- remote comment colors
theme['comment'] = {
background = '#212228',
body = '#AAB2BE',
author = '#378BDD',
timestamp = '#E1E5F2'
}
-- star fill color
theme['star'] = {
fill = '#FFFFFF'
}
-- titlebar background color (currently only supported on macOS)
theme['titlebar'] = {
background = '#36383D'
}
-- popup tooltip colors
-- { default, active, inactive, disabled }
theme['tooltip'] = {
text = '#E1E5F2',
background = '#2A82DA'
}
-- editor styles
-- Styles are composed of a string like:
-- fore:<color>,back:<color>,bold,italics,underline
-- Symbolic style names are allowed:
-- $(style.name)
-- http://www.scintilla.org/MyScintillaDoc.html#Styling
-- colors
theme.property['color.red'] = '#994D4D'
theme.property['color.yellow'] = '#99994D'
theme.property['color.green'] = '#4D994D'
theme.property['color.teal'] = '#4D9999'
theme.property['color.purple'] = '#994D99'
theme.property['color.orange'] = '#E6994D'
theme.property['color.blue'] = '#4D99E6'
theme.property['color.black'] = '#1A1A1A'
theme.property['color.grey'] = '#808080'
theme.property['color.white'] = '#E6E6E6'
-- styles
theme.property['style.bracebad'] = 'fore:#CC8080'
theme.property['style.bracelight'] = 'fore:#80CCFF'
theme.property['style.calltip'] = 'fore:#AAB2BE,back:#333333'
theme.property['style.class'] = 'fore:#F6E9D0'
theme.property['style.comment'] = 'fore:#E2D9C9'
theme.property['style.constant'] = 'fore:#E8C080'
theme.property['style.controlchar'] = '$(style.nothing)'
theme.property['style.default'] = 'fore:#AAB2BE,back:#212228'
theme.property['style.definition'] = 'fore:#F6E9D0'
theme.property['style.embedded'] = '$(style.tag),back:#333333'
theme.property['style.error'] = 'fore:#994D4D,italics'
theme.property['style.function'] = 'fore:#4D99E6'
theme.property['style.identifier'] = '$(style.nothing)'
theme.property['style.indentguide'] = 'fore:#333333,back:#333333'
theme.property['style.keyword'] = 'fore:#53AFEC,bold'
theme.property['style.label'] = 'fore:#E8C080'
theme.property['style.linenumber'] = 'fore:#5F6672,back:#2A2B30,bold'
theme.property['style.nothing'] = ''
theme.property['style.number'] = 'fore:#4D99E6'
theme.property['style.operator'] = 'fore:#CCCCCC,bold'
theme.property['style.preprocessor'] = 'fore:#CC77DA,bold'
theme.property['style.regex'] = 'fore:#80CC80'
theme.property['style.string'] = 'fore:#93C37E'
theme.property['style.tag'] = 'fore:#CCCCCC'
theme.property['style.type'] = 'fore:#CC77DA'
theme.property['style.variable'] = 'fore:#80CCFF'
theme.property['style.whitespace'] = ''
|
local class = require("thirdparty.pl.class")
local lexer = require("kotaro.parser.lexer")
local utils = require("kotaro.utils")
local NodeTypes = require("kotaro.parser.node_types")
-- Takes tokenized source and converts it to a Concrete Syntax Tree
-- (CST), which preserves whitespace and comments. The intent is to be
-- able to serialize the CST into a string containing the original
-- source exactly as passed.
local cst_parser = class()
function cst_parser:_init(src, filename)
self.src = tostring(src)
self.filename = filename or "<string>"
self.lexer = lexer(self.src, filename)
end
function cst_parser:generate_error(msg)
local t = self.lexer:peekToken()
local err = string.format("%s:%s:%s: %s\n", self.filename, t.line, t.column, msg)
--find the line
local lineNum = 0
local context = 2
if type(self.src) == 'string' then
for line in self.src:gmatch("[^\n]*\n?") do
if line:sub(-1,-1) == '\n' then line = line:sub(1,-2) end
lineNum = lineNum+1
if lineNum >= t.line - context and lineNum < t.line + context then
err = err..">> "..line:gsub('\t',' ').."\n"
if lineNum == t.line then
for i = 1, t.column do
local c = line:sub(i,i)
if c == '\t' then
err = err..' '
else
err = err..' '
end
end
err = err.." ^^^^"
end
end
end
end
return err
end
--
--
-- Expressions
--
--
function cst_parser:parse_function_args_and_body()
local l_lparen = self.lexer:consumeSymbol("(")
if not l_lparen then
return false, self:generate_error("`(` expected")
end
local args = {}
local l_rparen = self.lexer:consumeSymbol(")")
while not l_rparen do
if self.lexer:tokenIs("Ident") then
args[#args+1] = self.lexer:consumeToken()
local l_comma = self.lexer:consumeSymbol(",")
if l_comma then
args[#args+1] = l_comma
else
l_rparen = self.lexer:consumeSymbol(")")
if not l_rparen then
return false, self:generate_error("`)` expected")
end
end
else
local l_varargs = self.lexer:consumeSymbol("...")
if l_varargs then
args[#args+1] = l_varargs
l_rparen = self.lexer:consumeSymbol(")")
if not l_rparen then
return false, self:generate_error("`...` must be the last argument of a function")
end
else
return false, self:generate_error("argument name or `...` expected")
end
end
end
local st, body = self:parse_statement_list()
if not st then return st, body end
-- BUG: prevent usage of expressions here
local arglist = NodeTypes.ident_list(args)
-- TODO: funcdef --> (def -> name -> parameters -> suite)
return true, NodeTypes.function_parameters_and_body(l_lparen, arglist, l_rparen, body)
end
function cst_parser:parse_parenthesized_expression()
local l_lparen = self.lexer:consumeSymbol("(")
assert(l_lparen)
local st, expr = self:parse_expression()
if not st then return st, expr end
local l_rparen = self.lexer:consumeSymbol(")")
if not l_rparen then return false, self:generate_error("`)` expected") end
local paren = NodeTypes.parenthesized_expression(l_lparen, expr, l_rparen)
-- if there is an index or call statement directly after this
-- expression, wrap a suffixed expression around it.
--
-- (a or b):method()
if self.lexer:tokenIsSymbol(":")
or self.lexer:tokenIsSymbol(".")
or self.lexer:tokenIsSymbol("(")
or self.lexer:tokenIsSymbol("[")
or self.lexer:tokenIs("String")
or self.lexer:tokenIsSymbol("{")
then
return self:parse_suffixed_expression("all", paren)
end
return true, paren
end
function cst_parser:parse_suffixed_expression(mode, primary)
if primary == nil then
if not self.lexer:tokenIs("Ident") then
-- Return a blank expression for zero-argument function
-- calls.
return true, NodeTypes.suffixed_expression({})
end
primary = self.lexer:consumeToken()
end
local expr
local exprs = { primary }
if mode == "local" then
return true, NodeTypes.suffixed_expression(exprs)
end
local only_dots = mode == "dots_and_colon"
while true do
if self.lexer:tokenIsSymbol(".") or self.lexer:tokenIsSymbol(":") then
local l_dot_or_colon = self.lexer:consumeToken()
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("<Ident> expected.")
end
local id = self.lexer:consumeToken()
expr = NodeTypes.member_expression(l_dot_or_colon, id)
elseif not only_dots and self.lexer:tokenIsSymbol("[") then
local l_lbracket = self.lexer:consumeToken()
local st, ex = self:parse_expression()
if not st then return st, ex end
local l_rbracket = self.lexer:consumeSymbol("]")
if not l_rbracket then
return false, self:generate_error("`]` expected")
end
expr = NodeTypes.index_expression(l_lbracket, ex, l_rbracket)
elseif not only_dots and self.lexer:tokenIsSymbol("(") then
local args = {}
local l_lparen = self.lexer:consumeToken()
local l_rparen
while not l_rparen do
local st, ex = self:parse_expression()
if not st then return st, ex end
args[#args+1] = ex
local l_comma = self.lexer:consumeSymbol(",")
if l_comma then
args[#args+1] = l_comma
else
l_rparen = self.lexer:consumeSymbol(")")
if not l_rparen then
return false, self:generate_error("`)` expected")
end
end
end
local arglist = NodeTypes.expression_list(args)
expr = NodeTypes.call_expression(l_lparen, arglist, l_rparen)
elseif not only_dots and self.lexer:tokenIs("String") then
local l_str = self.lexer:consumeToken()
expr = NodeTypes.string_call_expression(l_str)
elseif not only_dots and self.lexer:tokenIsSymbol("{") then
local st, ex = self:parse_simple_expression()
if not st then return st, ex end
-- FIXME
expr = NodeTypes.table_call_expression(ex)
else
break
end
exprs[#exprs+1] = expr
end
return true, NodeTypes.suffixed_expression(exprs)
end
function cst_parser:parse_constructor_key_value()
-- literal key like [1] or ["some.key"]
local l_lbracket = self.lexer:consumeSymbol("[")
assert(l_lbracket)
local st, key = self:parse_expression()
if not st then return st, key end
local l_rbracket = self.lexer:consumeSymbol("]")
if not l_rbracket then
return false, self:generate_error("`]` expected")
end
local l_equals = self.lexer:consumeSymbol("=")
if not l_equals then
return false, self:generate_error("`=` expected")
end
local st, val = self:parse_expression()
if not st then return st, val end
local cons_key = NodeTypes.constructor_key(l_lbracket, key, l_rbracket)
local cons_val = val
return true, NodeTypes.key_value_pair(cons_key, l_equals, cons_val)
end
function cst_parser:parse_value_or_key_value_pair()
local lookahead = self.lexer:peekToken(2)
if lookahead.leaf_type == "Symbol" and lookahead.value == "=" then
local key = self.lexer:consumeToken()
local l_equals = self.lexer:consumeSymbol("=")
if not l_equals then
return false, self:generate_error("value expression expected")
end
local st, value = self:parse_expression()
if not st then return st, value end
return true, NodeTypes.key_value_pair(key, l_equals, value)
end
return self:parse_expression()
end
function cst_parser:parse_constructor_entry()
local result
if self.lexer:tokenIsSymbol("[") then
local st, key = self:parse_constructor_key_value()
if not st then return st, key end
result = key
elseif self.lexer:tokenIs("Ident") then
local st, value_or_kv_pair = self:parse_value_or_key_value_pair()
if not st then return st, value_or_kv_pair end
result = value_or_kv_pair
else
local l_rbracket = self.lexer:consumeSymbol("}")
if l_rbracket then
return true, l_rbracket
else
local st, value = self:parse_expression()
if not st then return false, self:generate_error("value expected") end
return true, value
end
end
assert(result)
return true, result
end
function cst_parser:parse_constructor_expression()
local l_lbracket = self.lexer:consumeSymbol("{")
assert(l_lbracket)
local l_rbracket
local entries = {}
while true do
local ok, entry = self:parse_constructor_entry()
if not ok then return false, entry end
if entry[1] == "leaf" and entry.value == "}" then
l_rbracket = entry
break
else
entries[#entries+1] = entry
end
ok = false
local l_semicolon = self.lexer:consumeSymbol(";")
if l_semicolon then
entries[#entries+1] = l_semicolon
ok = true
else
local l_comma = self.lexer:consumeSymbol(",")
if l_comma then
entries[#entries+1] = l_comma
ok = true
end
end
if not ok then
l_rbracket = self.lexer:consumeSymbol("}")
if l_rbracket then
break
end
end
if not ok then
return false, self:generate_error("`}` or table entry expected")
end
end
return true, NodeTypes.constructor_expression(l_lbracket, entries, l_rbracket)
end
function cst_parser:parse_function_expression()
local l_function = self.lexer:consumeKeyword("function")
assert(l_function)
local st, body = self:parse_function_args_and_body()
if not st then return st, body end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected")
end
return true, NodeTypes.function_expression(l_function, body, l_end)
end
function cst_parser:parse_simple_expression()
if self.lexer:tokenIs("Number") then
return true, self.lexer:consumeToken()
elseif self.lexer:tokenIs("String") then
return true, self.lexer:consumeToken()
elseif self.lexer:tokenIs("Nil") then
return true, self.lexer:consumeToken()
elseif self.lexer:tokenIs("Boolean") then
return true, self.lexer:consumeToken()
elseif self.lexer:tokenIsSymbol("...") then
return true, self.lexer:consumeToken()
elseif self.lexer:tokenIsSymbol("{") then
return self:parse_constructor_expression()
elseif self.lexer:tokenIsKeyword("function") then
return self:parse_function_expression()
end
return self:parse_suffixed_expression()
end
local unops = utils.set{'-', 'not', '#'}
local unopprio = 8
local priority = {
['+'] = {6,6};
['-'] = {6,6};
['%'] = {7,7};
['/'] = {7,7};
['*'] = {7,7};
['^'] = {10,9}; -- right-associative
['..'] = {5,4}; -- right-associative
['=='] = {3,3};
['<'] = {3,3};
['<='] = {3,3};
['~='] = {3,3};
['>'] = {3,3};
['>='] = {3,3};
['and'] = {2,2};
['or'] = {1,1};
}
function cst_parser:parse_primary_expression()
local st, expr
if self.lexer:tokenIsSymbol("(") then
st, expr = self:parse_parenthesized_expression()
if not st then return st, expr end
return true, expr
end
if unops[self.lexer:peekToken().value] then
local ops = {}
local op = self.lexer:consumeToken()
ops[1] = op
local st, exp = self:parse_primary_expression()
if not exp then return st, exp end
ops[2] = exp
return true, NodeTypes.expression(ops)
end
return self:parse_simple_expression()
end
-- Implements the precedence climbing method.
-- https://en.wikipedia.org/wiki/Operator-precedence_parser#Precedence_climbing_method
function cst_parser:parse_expression_1(lhs, min_priority)
local st, exp
local lookahead = self.lexer:peekToken().value
local continue_lhs = function(tok)
local prio = priority[tok]
return prio and prio[1] >= min_priority
end
local continue_rhs = function(tok, first_prio)
local prio = priority[tok]
return prio and prio[2] > first_prio[1]
end
while continue_lhs(lookahead) do
local first_op = self.lexer:consumeToken()
local first_op_prio = priority[first_op.value]
assert(first_op_prio)
local st, rhs = self:parse_primary_expression()
if not st then return st, rhs end
lookahead = self.lexer:peekToken().value
while continue_rhs(lookahead, first_op_prio) do
local second_op_prio = priority[lookahead]
assert(second_op_prio)
st, rhs = self:parse_expression_1(rhs, second_op_prio[1])
if not st then return st, rhs end
lookahead = self.lexer:peekToken().value
end
lhs = NodeTypes.expression({lhs, first_op, rhs})
end
return true, lhs
end
function cst_parser:parse_expression()
local st, primary = self:parse_primary_expression()
if not st then return st, primary end
local st, lhs = self:parse_expression_1(primary, 0)
if not st then return st, lhs end
if lhs[1] ~= "expression" then
lhs = NodeTypes.expression({lhs})
end
return true, lhs
end
--
--
-- Blocks
--
--
function cst_parser:parse_if_block()
assert(self.lexer:tokenIsKeyword("if"))
local l_if = self.lexer:consumeToken()
local nodes = { l_if }
local l_elseif
repeat
local st, cond = self:parse_expression()
if not st then return false, cond end
nodes[#nodes+1] = cond
local l_then = self.lexer:consumeKeyword("then")
if not l_then then
return false, self:generate_error("`then` expected.")
end
nodes[#nodes+1] = l_then
local st, body = self:parse_statement_list()
if not st then return false, body end
nodes[#nodes+1] = body
l_elseif = self.lexer:consumeKeyword("elseif")
if l_elseif then
nodes[#nodes+1] = l_elseif
end
until not l_elseif
local l_else = self.lexer:consumeKeyword("else")
if l_else then
nodes[#nodes+1] = l_else
local st, body = self:parse_statement_list()
if not st then return false, body end
nodes[#nodes+1] = body
end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected.")
end
nodes[#nodes+1] = l_end
return true, NodeTypes.if_block(nodes)
end
function cst_parser:parse_while_block()
local l_while = self.lexer:consumeKeyword("while")
assert(l_while)
local st, cond = self:parse_expression()
if not st then return false, cond end
local l_do = self.lexer:consumeKeyword("do")
if not l_do then
return false, self:generate_error("`do` expected.")
end
local st, body = self:parse_statement_list()
if not st then return false, body end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected.")
end
return true, NodeTypes.while_block(l_while, cond, l_do, body, l_end)
end
function cst_parser:parse_do_block()
local l_do = self.lexer:consumeKeyword("do")
assert(l_do)
local st, body = self:parse_statement_list()
if not st then return false, body end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected.")
end
return true, NodeTypes.do_block(l_do, body, l_end)
end
function cst_parser:parse_numeric_for_range(var_name)
local l_equals = self.lexer:consumeSymbol("=")
assert(l_equals)
local st, start_expr = self:parse_expression()
if not st then return false, start_expr end
local l_comma_a = self.lexer:consumeSymbol(",")
if not l_comma_a then
return false, self:generate_error("`,` expected.")
end
local st, end_expr = self:parse_expression()
if not st then return false, end_expr end
local step_expr
local l_comma_b = self.lexer:consumeSymbol(",")
if l_comma_b then
st, step_expr = self:parse_expression()
if not st then return false, step_expr end
end
return true, NodeTypes.numeric_for_range(var_name, l_equals, start_expr, l_comma_a, end_expr, l_comma_b, step_expr)
end
function cst_parser:parse_generic_for_range(var_name)
local vars = { var_name }
local l_comma = self.lexer:consumeSymbol(",")
while l_comma do
vars[#vars+1] = l_comma
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("for variable expected.")
end
vars[#vars+1] = self.lexer:consumeToken()
l_comma = self.lexer:consumeSymbol(",")
end
local l_in = self.lexer:consumeKeyword("in")
if not l_in then
return false, self:generate_error("`in` expected.")
end
local generators = {}
local st, first_generator = self:parse_expression()
if not st then return false, first_generator end
generators[1] = first_generator
l_comma = self.lexer:consumeSymbol(",")
while l_comma do
generators[#generators+1] = l_comma
local st, gen = self:parse_expression()
if not st then return st, gen end
generators[#generators+1] = gen
l_comma = self.lexer:consumeSymbol(",")
end
local vars_node = NodeTypes.ident_list(vars)
local generators_node = NodeTypes.expression_list(generators)
return true, NodeTypes.generic_for_range(vars_node, l_in, generators_node)
end
function cst_parser:parse_for_block()
local l_for = self.lexer:consumeKeyword("for")
assert(l_for)
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("<ident> expected.")
end
local var_name = self.lexer:consumeToken()
local st, for_range
if self.lexer:tokenIsSymbol("=") then
st, for_range = self:parse_numeric_for_range(var_name)
else
st, for_range = self:parse_generic_for_range(var_name)
end
if not st then return st, for_range end
local l_do = self.lexer:consumeKeyword("do")
if not l_do then
return false, self:generate_error("`do` expected.")
end
local st, block = self:parse_statement_list()
if not st then return st, block end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected.")
end
return true, NodeTypes.for_block(l_for, for_range, l_do, block, l_end)
end
function cst_parser:parse_repeat_block()
local l_repeat = self.lexer:consumeKeyword("repeat")
assert(l_repeat)
local st, block = self:parse_statement_list()
if not st then return st, block end
local l_until = self.lexer:consumeKeyword("until")
if not l_until then
return false, self:generate_error("`until` expected.")
end
local st, cond = self:parse_expression()
if not st then return false, cond end
return true, NodeTypes.repeat_block(l_repeat, block, l_until, cond)
end
function cst_parser:parse_function_declaration()
local l_function = self.lexer:consumeKeyword("function")
assert(l_function)
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("Function name expected")
end
local st, name = self:parse_suffixed_expression("dots_and_colon")
if not st then return false, name end
local st, func = self:parse_function_args_and_body()
if not st then return false, func end
local l_end = self.lexer:consumeKeyword("end")
if not l_end then
return false, self:generate_error("`end` expected")
end
return true, NodeTypes.function_declaration(l_function, name, func, l_end)
end
--
--
-- Statements
--
--
function cst_parser:parse_local()
local l_local = self.lexer:consumeKeyword("local")
assert(l_local)
if self.lexer:tokenIs("Ident") then
local st, suff = self:parse_suffixed_expression("local")
if not st then return st, suff end
local st, assign = self:parse_assignment(suff, "local")
if not st then return st, assign end
return true, NodeTypes.assignment_statement__local(l_local, assign)
elseif self.lexer:tokenIsKeyword("function") then
local st, func = self:parse_function_declaration()
if not st then return st, func end
return true, NodeTypes.function_declaration__local(l_local, func)
end
return false, self:generate_error("local var or function def expected")
end
function cst_parser:parse_label()
local l_colons_a = self.lexer:consumeSymbol("::")
assert(l_colons_a)
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("Label name expected")
end
local label = self:consumeToken()
local l_colons_b = self.lexer:consumeSymbol("::")
if not l_colons_b then
return false, self:generate_error("`::` expected")
end
return true, NodeTypes.label(l_colons_a, label, l_colons_b)
end
function cst_parser:parse_return()
local l_return = self.lexer:consumeKeyword("return")
assert(l_return)
local exprs = {}
if not self.lexer:tokenIsKeyword("end") then
local st, first_expr = self:parse_expression()
if st then
exprs[1] = first_expr
local l_comma = self.lexer:consumeSymbol(",")
while l_comma do
exprs[#exprs+1] = l_comma
local st, ex = self:parse_expression()
if not st then return false, ex end
exprs[#exprs+1] = ex
l_comma = self.lexer:consumeSymbol(",")
end
end
end
local expr_list = NodeTypes.expression_list(exprs)
return true, NodeTypes.return_statement(l_return, expr_list)
end
function cst_parser:parse_break()
local l_break = self.lexer:consumeKeyword("break")
assert(l_break)
return true, NodeTypes.break_statement(l_break)
end
function cst_parser:parse_goto()
local l_goto = self.lexer:consumeKeyword("l_goto")
assert(l_goto)
if not self.lexer:tokenIs("Ident") then
return false, self:generate_error("Label expected")
end
local label = self:consumeToken()
return true, NodeTypes.goto_statement(l_goto, label)
end
function cst_parser:parse_assignment(suffixed, mode)
if suffixed:type() == "parenthesized_expression" then
return false, self:generate_error("Cannot assign to a parenthesized expression, is not an lvalue")
end
local lhs = { suffixed }
local l_comma = self.lexer:consumeSymbol(",")
while l_comma do
lhs[#lhs+1] = l_comma
local st, lhs_part = self:parse_suffixed_expression(mode)
if not st then return st, lhs_part end
lhs[#lhs+1] = lhs_part
l_comma = self.lexer:consumeSymbol(",")
end
local lhs_node = NodeTypes.ident_list(lhs)
local l_equals = self.lexer:consumeSymbol("=")
if not l_equals then
if mode == "local" then
return true, NodeTypes.assignment_statement(lhs_node)
else
return false, self:generate_error("`=` expected")
end
end
local rhs = {}
local st, first_rhs = self:parse_expression()
if not st then return st, first_rhs end
rhs[1] = first_rhs
l_comma = self.lexer:consumeSymbol(",")
while l_comma do
rhs[#rhs+1] = l_comma
local st, rhs_part = self:parse_expression()
if not st then return false, rhs_part end
rhs[#rhs+1] = rhs_part
l_comma = self.lexer:consumeSymbol(",")
end
local rhs_node = NodeTypes.expression_list(rhs)
return true, NodeTypes.assignment_statement(lhs_node, l_equals, rhs_node)
end
function cst_parser:parse_assignment_or_call()
local st, suffixed = self:parse_suffixed_expression()
if not st then return st, suffixed end
if #suffixed <= 1 then
return false, self:generate_error("expected ident")
end
local stmt = suffixed
if self.lexer:tokenIsSymbol(",") or self.lexer:tokenIsSymbol("=") then
st, stmt = self:parse_assignment(suffixed)
if not st then return st, stmt end
end
return true, stmt
end
function cst_parser:parse_statement()
local st, stmt
local lookahead = self.lexer:peekToken()
if lookahead.leaf_type == "Keyword" then
if lookahead.value == "if" then
st, stmt = self:parse_if_block()
elseif lookahead.value == "while" then
st, stmt = self:parse_while_block()
elseif lookahead.value == "do" then
st, stmt = self:parse_do_block()
elseif lookahead.value == "for" then
st, stmt = self:parse_for_block()
elseif lookahead.value == "repeat" then
st, stmt = self:parse_repeat_block()
elseif lookahead.value == "function" then
st, stmt = self:parse_function_declaration()
elseif lookahead.value == "local" then
st, stmt = self:parse_local()
elseif lookahead.value == "::" then
st, stmt = self:parse_label()
elseif lookahead.value == "return" then
st, stmt = self:parse_return()
elseif lookahead.value == "break" then
st, stmt = self:parse_break()
elseif lookahead.value == "goto" then
st, stmt = self:parse_goto()
else
st, stmt = self:parse_assignment_or_call()
end
else
st, stmt = self:parse_assignment_or_call()
end
local l_semicolon
if self.lexer:tokenIsSymbol(";") then
l_semicolon = self.lexer:consumeToken()
end
return st, stmt, l_semicolon
end
local block_end_kwords = utils.set{"end", "else", "elseif", "until"}
function cst_parser:parse_statement_list()
local statements = {}
while not (block_end_kwords[self.lexer:peekToken().value] or self.lexer:isEof()) do
local st, statement, l_semicolon = self:parse_statement()
if not st then return false, statement end
assert(statement)
statements[#statements+1] = statement
if l_semicolon then
statements[#statements+1] = l_semicolon
end
end
return true, NodeTypes.statement_list(statements)
end
function cst_parser:parse()
local st, tree = self:parse_statement_list()
if not st then
return false, tree
end
assert(self.lexer:isEof())
local l_eof = self.lexer:peekToken()
local program = NodeTypes.program(tree, l_eof)
program:changed()
return true, program
end
return cst_parser
|
object_tangible_furniture_all_frn_all_statuette_cityhall_naboo = object_tangible_furniture_all_shared_frn_all_statuette_cityhall_naboo:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_statuette_cityhall_naboo, "object/tangible/furniture/all/frn_all_statuette_cityhall_naboo.iff")
|
local DateUtil = {}
DateUtil.__DebugFlag = false
function DateUtil:YangLi2NongLiDate(st)
--天干名称
local cTianGan = {"甲","乙","丙","丁","戊","己","庚","辛","壬","癸"}
--地支名称
local cDiZhi = {"子","丑","寅","卯","辰","巳","午", "未","申","酉","戌","亥"}
--属相名称
local cShuXiang = {"鼠","牛","虎","兔","龙","蛇", "马","羊","猴","鸡","狗","猪"}
--农历日期名
local cDayName =
{
"*","初一","初二","初三","初四","初五",
"初六","初七","初八","初九","初十",
"十一","十二","十三","十四","十五",
"十六","十七","十八","十九","二十",
"廿一","廿二","廿三","廿四","廿五",
"廿六","廿七","廿八","廿九","三十"
}
--农历月份名
local cMonName = {"*","正","二","三","四","五","六", "七","八","九","十","十一","腊"}
--公历每月前面的天数
local wMonthAdd = {0,31,59,90,120,151,181,212,243,273,304,334}
-- 农历数据
local wNongliData = {2635,333387,1701,1748,267701,694,2391,133423,1175,396438
,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877}
local wCurYear,wCurMonth,wCurDay;
local nTheDate,nIsEnd,m,k,n,i,nBit;
local szNongli, szNongliDay,szShuXiang;
---取当前公历年、月、日---
wCurYear = st.year
wCurMonth = st.month
wCurDay = st.day
---计算到初始时间1921年2月8日的天数:1921-2-8(正月初一)---
nTheDate = (wCurYear - 1921) * 365 + (wCurYear - 1921) / 4 + wCurDay + wMonthAdd[wCurMonth] - 38
if (((wCurYear % 4) == 0) and (wCurMonth > 2)) then
nTheDate = nTheDate + 1
end
--计算农历天干、地支、月、日---
nIsEnd = 0;
m = 0;
while nIsEnd ~= 1 do
if wNongliData[m+1] < 4095 then
k = 11;
else
k = 12;
end
n = k;
while n>=0 do
--获取wNongliData(m)的第n个二进制位的值
nBit = wNongliData[m+1];
for i=1,n do
nBit = math.floor(nBit/2);
end
nBit = nBit % 2;
if nTheDate <= (29 + nBit) then
nIsEnd = 1;
break;
end
nTheDate = nTheDate - 29 - nBit;
n = n - 1;
end
if nIsEnd ~= 0 then
break;
end
m = m + 1;
end
wCurYear = 1921 + m
wCurMonth = k - n + 1
wCurDay = math.floor(nTheDate)
if k == 12 then
if wCurMonth == wNongliData[m+1] / 65536 + 1 then
wCurMonth = 1 - wCurMonth;
elseif wCurMonth > wNongliData[m+1] / 65536 + 1 then
wCurMonth = wCurMonth - 1;
end
end
if self.__DebugFlag then
print('农历', wCurYear, wCurMonth, wCurDay)
end
--生成农历天干、地支、属相 ==> wNongli--
szShuXiang = cShuXiang[(((wCurYear - 4) % 60) % 12) + 1]
szNongli = szShuXiang .. '(' .. cTianGan[(((wCurYear - 4) % 60) % 10)+1] .. cDiZhi[(((wCurYear - 4) % 60) % 12) + 1] .. ')年'
--szNongli,"%s(%s%s)年",szShuXiang,cTianGan[((wCurYear - 4) % 60) % 10],cDiZhi[((wCurYear - 4) % 60) % 12]);
--生成农历月、日 ==> wNongliDay--*/
if wCurMonth < 1 then
szNongliDay = "闰" .. cMonName[(-1 * wCurMonth) + 1]
else
szNongliDay = cMonName[wCurMonth+1]
end
szNongliDay = szNongliDay .. "月" .. cDayName[wCurDay+1]
return {year = wCurYear, month = wCurMonth, day = wCurDay}, szNongli .. szNongliDay
end
function DateUtil:GetNextMonth(date)
if date.month >= 12 then
return {year = date.year + 1, month = 1, day = date.day}
end
return {year = date.year , month = 1 + date.month, day = date.day}
end
function DateUtil:GetPreviousMonth(date)
if date.month <= 1 then
return {year = date.year - 1, month = 12, day = date.day}
end
return {year = date.year , month = date.month - 1, day = date.day}
end
function DateUtil:GetYangLiNextDay(date)
local date2Time = os.time({year=date.year,month=date.month,day=date.day,hour=8,min=0,sec=0,isdst=false})
return os.date("*t", date2Time + 24* 3600)
end
function DateUtil:IsSameDate(day1, day2, bIgnoreYear)
if not bIgnoreYear then
if day1.year ~= day2.year then return false end
end
if day1.month ~= day2.month then return false end
if day1.day ~= day2.day then return false end
return true
end
function DateUtil:IsBirthdayDateNear(yangLiTime, nongliDate2, bIgnoreYear, range)
local base = yangLiTime
if range == -1 then return true end
for i = - range, range do
local targetDayTime = base + i * 24 * 3600
local targetDate = os.date("*t", targetDayTime)
local targetNongli = self:YangLi2NongLiDate({year = targetDate.year, month = targetDate.month, day = targetDate.day})
if self:IsSameDate(nongliDate2, targetNongli, true) then
return true
end
end
end
-- 阳历和农历比较,第一个参数是阳历,1表示前面的大,0表示相等
function DateUtil:YangLiCompareNongLi(yDate, nDate)
local y2n = self:YangLi2NongLiDate(yDate)
if self:IsSameDate(y2n, nDate) then return 0 end
if y2n.year > nDate.year then return 1 end
if y2n.year < nDate.year then return -1 end
if y2n.month > nDate.month then return 1 end
if y2n.month < nDate.month then return -1 end
if y2n.day > nDate.day then return 1 end
return -1
end
function DateUtil:NongLi2ThisYearYangLi(target)
local today = os.date("*t", os.time())
local needed = {
year = today.year,
month = target.month,
day = target.day,
isleap = 0,
isLeap = 0
}
return calender.lunartosolar(needed)
end
-- 农历转阳历
function DateUtil:NongLi2YangLiDate(target)
if true then
local needed = {
year = target.year,
month = target.month,
day = target.day,
isleap = 0
}
return calender.lunartosolar(needed)
end
-- 找到这个月的阳历月初
local try = {year = target.year, month = target.month, day = 1}
-- 阳历一般比农历往后延1个月
try = self:GetNextMonth(try)
if self:YangLiCompareNongLi(try, target) == 0 then return try end
local yTest
while self:YangLiCompareNongLi(try, target) == 1 do
if self.__DebugFlag then
print("move to next month")
end
try = self:GetPreviousMonth(try)
end
if self:YangLiCompareNongLi(try, target) == 0 then return try end
yTest = try
for i = 1, 62 do
if self:YangLiCompareNongLi(yTest, target) == 0 then
return yTest
end
if self.__DebugFlag then
print("move to next day")
end
yTest = self:GetYangLiNextDay(yTest)
end
if self.__DebugFlag then
print("fail to find")
end
return nil
end
function DateUtil:__test_entry(bOPenDebug)
self.__DebugFlag = bOPenDebug
local st = {}
st.year = 2019
st.month = 6
st.day = 25
self:YangLi2NongLiDate(st)
local target = {year = 1992, month = 5, day = 23}
local res = self:NongLi2YangLiDate(target)
print("input is "..target.year,target.month,target.day,"\ntarget yangli is ", res.year, res.month, res.day)
end
return DateUtil
|
-- Copyright 2016 John Regan <[email protected]>
local string_sub = string.sub
local string_len = string.len
local string_byte = string.byte
local M = {
_VERSION = '1.0.6'
}
local function _decode(a)
local i=1
local len = 0;
local max_len = string_len(a)
repeat
local t = string_byte(a,i) - 48
if(t >= 0 and t<=9) then
len = (len * 10) + t
i = i + 1
end
until ( t<0 or t>9 or i > max_len )
if (i > max_len) then
return nil, nil
end
-- ascii 58 == colon
if string_byte(a,i) ~= 58 then
return nil, nil
end
i = i + 1
if(i+len > max_len) then
return nil, nil
end
-- ascii 44 == comma
if(string_byte(a,i+len) ~= 44) then
return nil, nil
end
if(len == 0) then
return i, ''
end
return i+len, string_sub(a,i,i+len - 1)
end
local function _encode(a)
return string_len(a) .. ':' .. a .. ','
end
local function _order(a,b)
local ta = type(a)
local tb = type(b)
if(ta == "number" and tb == "number") then
return a<b
elseif (ta== "number" and tb =="string") then
return true
elseif (ta=="string" and tb == "number") then
return false
elseif (ta=="string" and tb=="string") then
return a<b
end
end
function M.decode(a)
local i = 1
local results = {}
while(i<#a) do
local j,val = _decode(string_sub(a,i))
if j then
table.insert(results,val)
i = i + j
else
break
end
end
if #results == 0 then
results = nil
end
return results, string_sub(a,i)
end
function M.encode(...)
local r = ""
local err = {}
local args = {...}
for i in pairs(args) do
local a = args[i]
local ta = type(a)
if ta == 'table' then
-- grab table keys and sort
local keys = {}
for k in pairs(a) do keys[#keys+1] = k end
table.sort(keys,_order)
for _,k in ipairs(keys) do
if(type(k) ~= "number") then
table.insert(err,'arg ' .. i .. ' key "' .. k .. '" is not numeric')
else
r = r .. _encode(a[k])
end
end
elseif ta ~= 'nil' then
r = r .. _encode(a)
end
end
if(#err == 0) then
err = nil
end
if(#r == 0) then
r = nil
end
return r, err
end
return M
|
local math = require('math')
local memory = require('memory')
local settings = require('settings')
local windower = require('core.windower')
local defaults = {
gameplay = {
auto_target = true,
inventory = {
sort = false,
type = 1,
},
},
graphics = {
aspect_ratio = {
auto = true,
value = 16 / 9,
},
gamma = {
red = 1.5,
green = 1.5,
blue = 1.5,
},
framerate = 60,
animation_framerate = 60,
clipping_plane = 10,
},
audio = {
volume = {
effects = 1.0,
music = 1.0,
},
footstep_effects = true,
},
system = {
auto_disconnect = {
enabled = false,
time = 60,
},
language_filter = {
enabled = false,
},
},
}
local options = settings.load(defaults)
local window_aspect_ratio = (4 / 3) / (windower.settings.client_size.width / windower.settings.client_size.height)
local math_ceil = math.ceil
coroutine.schedule(function()
while true do
do -- graphics
local graphics = memory.graphics
local gamma = graphics.gamma
local render = graphics.render
local graphics_options = options.graphics
local aspect_ratio_options = graphics_options.aspect_ratio
local gamma_options = graphics_options.gamma
gamma.red = gamma_options.red
gamma.green = gamma_options.green
gamma.blue = gamma_options.blue
render.aspect_ratio = aspect_ratio_options.auto and window_aspect_ratio or ((4 / 3) / aspect_ratio_options.value)
render.framerate_divisor = graphics_options.framerate == 'unlimited' and 0 or math_ceil(60 / graphics_options.framerate)
graphics.clipping_plane_entity = graphics_options.clipping_plane
graphics.clipping_plane_map = graphics_options.clipping_plane
end
do -- system
local auto_disconnect = memory.auto_disconnect
local language_filter = memory.language_filter
local system_options = options.system
local auto_disconnect_options = system_options.auto_disconnect
local language_filter_options = system_options.language_filter
auto_disconnect.enabled = auto_disconnect_options.enabled
auto_disconnect.timeout_time = auto_disconnect_options.time
language_filter.disabled = not language_filter_options.enabled
end
coroutine.sleep_frame()
end
end)
--[[
Copyright © 2018, Windower Dev Team
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Windower Dev Team nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE WINDOWER DEV TEAM BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
|
function sysCall_info()
autoStart=sim.getNamedBoolParam('visualizationStream.autoStart')
if autoStart==nil then autoStart=false end
return {autoStart=autoStart,menu='Connectivity\nVisualization stream'}
end
function sysCall_init()
appPath=sim.getStringParam(sim.stringparam_application_path)
pathSep=package.config:sub(1,1)
baseName='simAddOnVisualization stream'
zmqEnable=sim.getNamedBoolParam('visualizationStream.zmq.enable')
wsEnable=sim.getNamedBoolParam('visualizationStream.ws.enable')
if wsEnable==nil then wsEnable=true end
if zmqEnable and simZMQ then
simZMQ.__raiseErrors(true) -- so we don't need to check retval with every call
zmqPUBPort=sim.getNamedInt32Param('visualizationStream.zmq.pub.port') or 23010
zmqREPPort=sim.getNamedInt32Param('visualizationStream.zmq.rep.port') or (zmqPUBPort+1)
print('Add-on "Visualization stream": ZMQ endpoint on ports '..tostring(zmqPUBPort)..', '..tostring(zmqREPPort)..'...')
zmqContext=simZMQ.ctx_new()
zmqPUBSocket=simZMQ.socket(zmqContext,simZMQ.PUB)
simZMQ.bind(zmqPUBSocket,string.format('tcp://*:%d',zmqPUBPort))
zmqREPSocket=simZMQ.socket(zmqContext,simZMQ.REP)
simZMQ.bind(zmqPUBSocket,string.format('tcp://*:%d',zmqREPPort))
elseif zmqEnable then
sim.addLog(sim.verbosity_errors,'Visualization stream: the ZMQ plugin is not available')
zmqEnable=false
end
if wsEnable and simWS then
wsPort=sim.getNamedInt32Param('visualizationStream.ws.port') or 23020
print('Add-on "Visualization stream": WS endpoint on port '..tostring(wsPort)..'...')
if sim.getNamedBoolParam('visualizationStream.ws.retryOnStartFailure') then
while true do
local r,e=pcall(function() wsServer=simWS.start(wsPort) end)
if r then break end
print('Add-on "Visualization stream": WS failed to start ('..e..'). Retrying...')
sim.wait(0.5,false)
end
else
wsServer=simWS.start(wsPort)
end
simWS.setOpenHandler(wsServer,'onWSOpen')
simWS.setCloseHandler(wsServer,'onWSClose')
simWS.setMessageHandler(wsServer,'onWSMessage')
simWS.setHTTPHandler(wsServer,'onWSHTTP')
wsClients={}
elseif wsEnable then
sim.addLog(sim.verbosity_errors,'Visualization stream: the WS plugin is not available')
wsEnable=false
end
if not zmqEnable and not wsEnable then
sim.addLog(sim.verbosity_errors,'Visualization stream: aborting because no RPC backend available')
return {cmd='cleanup'}
end
codec=sim.getNamedStringParam('visualizationStream.codec') or 'cbor'
if codec=='json' then
json=require('dkjson')
encode=json.encode
decode=json.decode
opcode=simWS.opcode.text
elseif codec=='cbor' then
cbor=require('org.conman.cbor')
--encode=cbor.encode
encode=function(d) return sim.packTable(d,1) end -- faster
decode=cbor.decode
opcode=simWS.opcode.binary
else
error('unsupported codec: '..codec)
end
base64=require('base64')
url=require('socket.url')
localData={}
remoteData={}
uidToHandle={}
end
function sysCall_addOnScriptSuspend()
return {cmd='cleanup'}
end
function sysCall_nonSimulation()
processZMQRequests()
scan()
end
function sysCall_sensing()
processZMQRequests()
scan()
end
function sysCall_suspended()
processZMQRequests()
scan()
end
function sysCall_cleanup()
if zmqPUBSocket or zmqREPSocket then
if zmqPUBSocket then simZMQ.close(zmqPUBSocket) end
if zmqREPSocket then simZMQ.close(zmqREPSocket) end
simZMQ.ctx_term(zmqContext)
end
if wsServer then
simWS.stop(wsServer)
end
end
function sim.getHandleByUID(uid)
local handle=uidToHandle[uid]
if handle==nil then return nil end
local uid1=sim.getObjectInt32Param(handle,sim.objintparam_unique_id)
if uid==uid1 then return handle else return nil end
end
function getFileContents(path)
local f=assert(io.open(path,"rb"))
local content=f:read("*all")
f:close()
return content
end
function processZMQRequests()
if not zmqREPSocket then return end
while true do
local rc,revents=simZMQ.poll({zmqREPSocket},{simZMQ.POLLIN},0)
if rc<=0 then break end
local rc,req=simZMQ.recv(zmqREPSocket,0)
local resp=onZMQRequest(decode(req))
simZMQ.send(zmqREPSocket,encode(resp),0)
end
end
function onZMQRequest(data)
local resp={}
if data.cmd=='getbacklog' then
-- send current objects:
for uid,data in pairs(remoteData) do
local d=objectAdded(uid)
if d then table.insert(resp,d) end
end
for uid,data in pairs(remoteData) do
local d=objectChanged(uid)
if d then table.insert(resp,d) end
end
end
return resp
end
function onWSOpen(server,connection)
if server==wsServer then
local events={}
wsClients[connection]=1
-- send current objects:
for uid,data in pairs(remoteData) do
table.insert(events,objectAdded(uid))
end
for uid,data in pairs(remoteData) do
table.insert(events,objectChanged(uid))
end
if #events>0 then
sendEvent(events,connection)
end
end
end
function onWSClose(server,connection)
if server==wsServer then
wsClients[connection]=nil
end
end
function onWSMessage(server,connection,message)
end
function onWSHTTP(server,connection,resource,data)
resource=url.unescape(resource)
if resource=='/' or resource=='/'..baseName..'.html' then
local c=getFileContents(appPath..pathSep..baseName..'.html')
c=string.gsub(c,'const wsPort = 23020;','const wsPort = '..wsPort..';')
c=string.gsub(c,'const codec = "cbor";','const codec = "'..codec..'";')
return 200,c
elseif resource=='/'..baseName..'.js' then
return 200,getFileContents(appPath..pathSep..baseName..'.js')
else
sim.addLog(sim.verbosity_errors,'resource not found: '..resource)
end
end
function getObjectData(handle)
local data={}
data.handle=handle
data.uid=sim.getObjectInt32Param(handle,sim.objintparam_unique_id)
data.name=sim.getObjectAlias(handle,0)
data.parentHandle=sim.getObjectParent(handle)
if data.parentHandle==-1 then
data.parentUid=-1
else
data.parentUid=sim.getObjectInt32Param(data.parentHandle,sim.objintparam_unique_id)
end
data.pose=sim.getObjectPose(handle,data.parentHandle)
--data.absolutePose=sim.getObjectPose(handle,-1)
data.visible=sim.getObjectInt32Param(handle,sim.objintparam_visible)>0
-- fetch type-specific data:
local t=sim.getObjectType(handle)
if t==sim.object_shape_type then
--local _,o=sim.getShapeColor(handle,'',sim.colorcomponent_transparency)
---- XXX: opacity of compounds is always 0.5
---- XXX: sim.getShapeViz doesn't return opacity... maybe it should?
--data.opacity=o
elseif t==sim.object_joint_type then
local st=sim.getJointType(handle)
if st~=sim_joint_spherical_subtype then
data.jointPosition=sim.getJointPosition(handle)
cyclic,interval=sim.getJointInterval(handle)
data.jointCyclic=cyclic
if not cyclic then
data.jointMin=interval[1]
data.jointMax=interval[1]+interval[2]
end
end
local jointMatrix=sim.getJointMatrix(handle)
local p={jointMatrix[4],jointMatrix[8],jointMatrix[12]}
local q=sim.getQuaternionFromMatrix(jointMatrix)
data.jointPose={p[1],p[2],p[3],q[1],q[2],q[3],q[4]}
elseif t==sim.object_graph_type then
elseif t==sim.object_camera_type then
elseif t==sim.object_light_type then
elseif t==sim.object_dummy_type then
elseif t==sim.object_proximitysensor_type then
elseif t==sim.object_octree_type then
elseif t==sim.object_pointcloud_type then
elseif t==sim.object_visionsensor_type then
elseif t==sim.object_forcesensor_type then
end
return data
end
function objectDataChanged(a,b)
local wl,wa=1,17.5
local function poseChanged(a,b)
if a==nil and b==nil then return false end
local d=sim.getConfigDistance(a,b,{wl,wl,wl,wa,wa,wa,wa},{0,0,0,2,2,2,2})
return d>0.0001
end
local function vector3Changed(a,b)
if a==nil and b==nil then return false end
local d=sim.getConfigDistance(a,b,{wl,wl,wl},{0,0,0})
return d>0.0001
end
local function quaternionChanged(a,b)
if a==nil and b==nil then return false end
local d=sim.getConfigDistance(a,b,{wa,wa,wa,wa},{2,2,2,2})
return d>0.0001
end
local function numberChanged(a,b)
if a==nil and b==nil then return false end
return math.abs(a-b)>0.0001
end
return false
or poseChanged(a.pose,b.pose)
or poseChanged(a.absolutePose,b.absolutePose)
or quaternionChanged(a.jointQuaternion,b.jointQuaternion)
or numberChanged(a.jointPosition,b.jointPosition)
or a.parentUid~=b.parentUid
or a.name~=b.name
end
function scan()
localData={}
for i,handle in ipairs(sim.getObjectsInTree(sim.handle_scene)) do
local uid=sim.getObjectInt32Param(handle,sim.objintparam_unique_id)
uidToHandle[uid]=handle
localData[uid]=getObjectData(handle)
end
local events={}
for uid,_ in pairs(remoteData) do
if localData[uid]==nil or remoteData[uid].uid~=uid then
table.insert(events,objectRemoved(uid))
remoteData[uid]=nil
end
end
for uid,data in pairs(localData) do
if remoteData[uid]==nil then
table.insert(events,objectAdded(uid))
end
end
for uid,data in pairs(localData) do
if remoteData[uid]==nil or objectDataChanged(localData[uid],remoteData[uid]) then
table.insert(events,objectChanged(uid))
remoteData[uid]=data
end
end
if #events>0 then
sendEvent(events)
end
end
function objectAdded(uid)
local data={
event='objectAdded',
uid=uid,
}
local handle=sim.getHandleByUID(uid)
if handle==nil then return nil end
data.handle=handle
data.visible=sim.getObjectInt32Param(handle,sim.objintparam_visible)>0
local objProp=sim.getObjectProperty(handle)
data.selectModelBaseInstead=(objProp&sim.objectproperty_selectmodelbaseinstead)>0
local modelProp=sim.getModelProperty(handle)
data.modelBase=(modelProp&sim.modelproperty_not_model)==0
local t=sim.getObjectType(handle)
if t==sim.object_shape_type then
data.type="shape"
data.meshData={}
for i=0,1000000000 do
local meshData=sim.getShapeViz(handle,i)
if meshData==nil then break end
if meshData.texture then
local im=meshData.texture.texture
local res=meshData.texture.resolution
local imPNG=sim.saveImage(im,res,1,'.png',-1)
meshData.texture.texture=base64.encode(imPNG)
end
table.insert(data.meshData,meshData)
end
elseif t== sim.object_joint_type then
data.type="joint"
local st=sim.getJointType(handle)
if st==sim_joint_revolute_subtype then
data.subtype='revolute'
elseif st==sim_joint_prismatic_subtype then
data.subtype='prismatic'
elseif st==sim_joint_spherical_subtype then
data.subtype='spherical'
end
elseif t==sim.object_graph_type then
data.type="graph"
elseif t==sim.object_camera_type then
data.type="camera"
-- XXX: trick for giving an initial position for the default frontend camera
data.absolutePose=sim.getObjectPose(handle,-1)
-- XXX: from name we assume camera type
data.name=sim.getObjectAlias(handle,0)
data.near=sim.getObjectFloatParam(handle,sim.camerafloatparam_near_clipping)
data.far=sim.getObjectFloatParam(handle,sim.camerafloatparam_far_clipping)
data.fov=sim.getObjectFloatParam(handle,sim.camerafloatparam_perspective_angle)
data.orthoSize=sim.getObjectFloatParam(handle,sim.camerafloatparam_ortho_size)
elseif t==sim.object_light_type then
data.type="light"
elseif t==sim.object_dummy_type then
data.type="dummy"
elseif t==sim.object_proximitysensor_type then
data.type="proximitysensor"
elseif t==sim.object_octree_type then
data.type="octree"
elseif t==sim.object_pointcloud_type then
data.type="pointcloud"
data.points=sim.getPointCloudPoints(handle)
elseif t==sim.object_visionsensor_type then
data.type="visionsensor"
elseif t==sim.object_forcesensor_type then
data.type="forcesensor"
end
return data
end
function objectRemoved(uid)
local data={
event='objectRemoved',
uid=uid,
}
return data
end
function objectChanged(uid)
local data={
event='objectChanged',
uid=uid,
}
for field,value in pairs(localData[uid]) do
data[field]=value
end
return data
end
function sendEvent(d,conn)
if d==nil then return end
if verbose()>0 then
print('Visualization stream:',d)
end
d=encode(d)
sendEventRaw(d,conn)
end
function sendEventRaw(d,conn)
if d==nil then return end
if zmqPUBSocket then
simZMQ.send(zmqPUBSocket,d,0)
end
if wsServer then
for connection,_ in pairs(wsClients) do
if conn==nil or conn==connection then
simWS.send(wsServer,connection,d,opcode)
end
end
end
end
function verbose()
return sim.getNamedInt32Param('visualizationStream.verbose') or 0
end
|
local L = LibStub("AceLocale-3.0"):NewLocale("MakePeopleGreetAgain", "enUS", true)
-- Put the language in this locale here
L["Loaded language"] = "English"
--------------------------------------------------
-- General
--------------------------------------------------
L["MPGA_Title"] = "Make People Greet Again!"
L["MPGA_Title_Short"] = "MPGA!"
L["MPGA_Yes"] = "Yes"
L["MPGA_No"] = "No"
L["MPGA_PerformReload"] = "The interface needs to be reloaded to keep MakePeopleGreetAgain working properly.\n\nDo you want to reload the UI now?"
L["MPGA_NotReloaded"] = "The interface was not reloaded. Your changes are not active yet."
--------------------------------------------------
-- UI elements
--------------------------------------------------
L["MPGA_MMBTooltipTitle"] = "Make people greet again!"
L["MPGA_MMBTooltipInfo"] = "\124cffFF4500Left mouse:\124r Show/hide the window.\n\124cffFF4500Right mouse:\124r Open the interface options."
L["MPGA_EnableButton_Desc"] = "Activate/deactivate button"
L["MPGA_SetLayout"] = "Select layout"
L["MPGA_Layout_Default"] = "Default"
L["MPGA_Layout_SingleRow"] = "One row"
L["MPGA_Layout_SingleColumn"] = "One column"
L["MPGA_Layout_TwoColumns"] = "Two columns"
L["MPGA_MinimapButton"] = "Minimap button"
L["MPGA_MinimapButton_Desc"] = "Shows or hides the button on the minimap."
L["MPGA_GuildGreeting"] = "Greeting for guild members"
L["MPGA_GuildGreeting_Button"] = "Hi"
L["MPGA_GuildGreeting_Button_Tooltip"] = "Greeting for guild members"
L["MPGA_GuildGreeting_Desc"] = "The various texts used to greet guild members."
--
L["MPGA_GuildFarewell"] = "Farewell for guild members"
L["MPGA_GuildFarewell_Button"] = "Bye"
L["MPGA_GuildFarewell_Button_Tooltip"] = "Farewell for guild members"
L["MPGA_GuildFarewell_Desc"] = "The various texts used to say goodbye to guild members."
--
L["MPGA_GuildCongratulations"] = "Congratulations for guild members"
L["MPGA_GuildCongratulations_Button"] = "GZ"
L["MPGA_GuildCongratulations_Button_Tooltip"] = "Congratulations for guild members"
L["MPGA_GuildCongratulations_Desc"] = "The various texts used to congratulate guild members."
--
L["MPGA_GuildThanks"] = "Thanks for guild members"
L["MPGA_GuildThanks_Button"] = "Thx"
L["MPGA_GuildThanks_Button_Tooltip"] = "Thanks for guild members"
L["MPGA_GuildThanks_Desc"] = "The various texts used for thanking guild members."
L["MPGA_PartyGreeting"] = "Greeting for party members"
L["MPGA_PartyGreeting_Button"] = "Hi"
L["MPGA_PartyGreeting_Button_Tooltip"] = "Greeting for party members"
L["MPGA_PartyGreeting_Desc"] = "The various texts used to greet party members."
--
L["MPGA_PartyFarewell"] = "Farewell for party members"
L["MPGA_PartyFarewell_Button"] = "Bye"
L["MPGA_PartyFarewell_Button_Tooltip"] = "Farewell for party members"
L["MPGA_PartyFarewell_Desc"] = "The various texts used to say goodbye to party members."
L["MPGA_InstanceGreeting"] = "Greeting for instance party members"
L["MPGA_InstanceGreeting_Button"] = "Hi"
L["MPGA_InstanceGreeting_Button_Tooltip"] = "Greeting for instance party members"
L["MPGA_InstanceGreeting_Desc"] = "The various texts used to greet instance party members."
--
L["MPGA_InstanceFarewell"] = "Farewell for instance party members"
L["MPGA_InstanceFarewell_Button"] = "Bye"
L["MPGA_InstanceFarewell_Button_Tooltip"] = "Farewell for instance party members"
L["MPGA_InstanceFarewell_Desc"] = "The various texts used to say goodbye to instance party members."
--------------------------------------------------
-- Error messages
--------------------------------------------------
|
script/admin = "acb227"
local p = Instance.new("Part")
p.Parent = Workspace
p.Size = Vector3.new(1,1,1)
p.formFactor = 0
p.BrickColor = BrickColor.new("Bright red")
p.Anchored = true
p.Locked = true
if script.Parent.className ~= "HopperBin" then
local h = Instance.new("HopperBin")
h.Parent = game.Players[admin].Backpack
h.Name = "Lazor"
script.Parent = h
end
hold = false
tool = script.Parent
tool.Selected:connect(function(mouse)
mouse.Button1Up:connect(function() hold = false
p.Parent = nil
end)
mouse.Button1Down:connect(function()
if mouse.Target == nil then return end
p.Parent = Workspace
hold = true
while hold == true do
wait()
To = mouse.Hit.p
From = Workspace[admin]["Right Arm"]
p.CFrame = CFrame.new((To+From.Position)/2, From.Position)*CFrame.Angles((math.pi/2),0,0)
local c = Instance.new("CylinderMesh")
c.Parent = p
c.Scale = Vector3.new(.15,(To-From.Position).magnitude,.15)
h = mouse.Target.Parent:findFirstChild("Humanoid")
if h ~= nil then
while true do
h:TakeDamage(15)
end
end
end)
end)
f = Instance.new("ForceField")
f.Parent = Game.Workspace[admin]
|
object_tangible_wearables_necklace_necklace_trando_scale_of_honor_wke_m = object_tangible_wearables_necklace_shared_necklace_trando_scale_of_honor_wke_m:new {
}
ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_trando_scale_of_honor_wke_m, "object/tangible/wearables/necklace/necklace_trando_scale_of_honor_wke_m.iff")
|
local args = ...;
local dc = args.PiroGame:load('DrawableComponent.lua');
local tc = args.PiroGame.class('TextComponent', dc);
function tc:initialize(font, text)
self.text = text;
self.font = font;
end
function tc:activate()
self.drawable = love.graphics.newText(self.font, self.text);
end
return tc;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.