content stringlengths 5 1.05M |
|---|
----------------------------------------------------------
-- RamReader.lua: put variables on your video via AviUtl.
----------------------------------------------------------
if not aviutl then
error("This script runs under Lua for AviUtl.")
end
----------------------------------------------------------
-- Import frame data first
----------------------------------------------------------
local frame
-- TODO: modify the file paths below
local basedir = ""
local frameDataPath = basedir.."framedata.txt"
function importFrameData(path)
local file = io.open(path, "r")
if file == nil then
error("File could not be opened.")
end
frame = {}
local f = 1
while true do
local i
frame[f] = {}
-- TODO: modify the following code to fit the content of log output.
frame[f].count = file:read("*n")
if frame[f].count == nil then
frame[f] = nil
break
end
frame[f].lagcount = file:read("*n")
i = file:read("*n"); frame[f].lagged = ((i ~= 0) and true or false)
frame[f].x = file:read("*n")
frame[f].y = file:read("*n")
frame[f].xv = file:read("*n")
frame[f].yv = file:read("*n")
frame[f].time = file:read("*n")
-- i = file:read("*n"); frame[f].A = ((i ~= 0) and true or false)
f = f + 1
end
file:close()
end
importFrameData(frameDataPath)
----------------------------------------------------------
-- Extra functions
----------------------------------------------------------
aviutl.draw_bordered_text = function(ycp, x, y, text, R, G, B, tr,
border_width, borderR, borderG, borderB, borderTr,
face, fh, fw, angle1, angle2, weight, italic, under, strike)
-- FIXME: transparency won't work well.
for yoff = -border_width, border_width do
for xoff = -border_width, border_width do
aviutl.draw_text(ycp, x + xoff, y + yoff, text,
borderR, borderG, borderB, borderTr,
face, fh, fw, angle1, angle2, weight,
italic, under, strike)
end
end
aviutl.draw_text(ycp, x, y, text, R, G, B, tr, face, fh, fw, angle1, angle2, weight, italic, under, strike)
end
-- xx seconds => h:mm:ss.ss
function formatseconds(seconds)
local h, m, s
s = seconds % 60
m = math.floor(seconds / 60)
h = math.floor(m / 60)
m = m % 60
return string.format("%d:%02d:%05.2f", h, m, s)
end
----------------------------------------------------------
-- Image processor
----------------------------------------------------------
function func_proc()
local f = aviutl.get_frame() + 1
if frame[f] == nil then
return -- for safety...
end
local ycp_edit = aviutl.get_ycp_edit()
-- TODO: write your own drawing code here
aviutl.draw_bordered_text(ycp_edit,
2, 2, -- x, y
string.format("%d/%d\nspeed (%d, %d)\ningame: %s",
frame[f].count, frame[f].lagcount,
frame[f].xv, frame[f].yv,
formatseconds(frame[f].time/60.0)
),
255, 255, 255, 0, -- RGBA (0<alpha<4096)
2, 0, 0, 0, 2700, -- RGBA (0<alpha<4096)
"Verdana", 18, 8, 0, 0, 1000 -- font family, height, width, angle 1&2, weight
)
end
----------------------------------------------------------
-- Script terminated
----------------------------------------------------------
function func_exit()
end
|
StringBuilder = luanet.import_type("System.Text.StringBuilder");
local sb = StringBuilder();
for i = 0,1000,1 do
sb:Append(".");
end;
return sb:ToString(); |
Option = require('nvim.utils.option')
Variable = require('nvim.utils.variable')
Keybind = require('nvim.utils.keybind')
Command = require('nvim.utils.command')
Editor = require('nvim.utils.editor')
Vim = {
Option = Option,
Variable = Variable,
Keybind = Keybind,
Command = Command,
Editor = Editor,
}
|
--[[
Updater Script
]]--
local path = ...
print(path)
local handle = http.get("https://raw.githubusercontent.com/ccTCP/Delta/master/Releases/latest.lua")
local f = loadstring(handle.readAll())
setfenv(f,_G)
f(path)
--Just a test |
yatm_fluid_pipe_valves.valve_mesecon_rules = {
{x = 0, y = 0, z = -1},
{x = 1, y = 0, z = 0},
{x = -1, y = 0, z = 0},
{x = 0, y = 0, z = 1},
{x = 1, y = 1, z = 0},
{x = 1, y = -1, z = 0},
{x = -1, y = 1, z = 0},
{x = -1, y = -1, z = 0},
{x = 0, y = 1, z = 1},
{x = 0, y = -1, z = 1},
{x = 0, y = 1, z = -1},
{x = 0, y = -1, z = -1},
}
local fsize = (8 / 16.0) / 2
local size = (6 / 16.0) / 2
yatm_fluid_pipe_valves.valve_nodebox = {
type = "connected",
fixed = {-fsize, -fsize, -fsize, fsize, fsize, fsize},
connect_top = {-size, -size, -size, size, 0.5, size}, -- y+
connect_bottom = {-size, -0.5, -size, size, size, size}, -- y-
connect_front = {-size, -size, -0.5, size, size, size}, -- z-
connect_back = {-size, -size, size, size, size, 0.5 }, -- z+
connect_left = {-0.5, -size, -size, size, size, size}, -- x-
connect_right = {-size, -size, -size, 0.5, size, size}, -- x+
}
|
ayne = Entity:new({
img = love.graphics.newImage( "graphics/ayne.png" ),
state = "down",
states = {
movedown = {
quads = {
love.graphics.newQuad(0, 0, 32, 48, 96, 192),
love.graphics.newQuad(64, 0, 32, 48, 96, 192)
},
framedelay = 5,
move = function(self)
self.y = self.y + self.speed
if self.y + 48 > 600 then self.y = 600 - 48; self.state = "down"; frame = 1 end
end
},
moveup = {
quads = {
love.graphics.newQuad(0, 48, 32, 48, 96, 192),
love.graphics.newQuad(64, 48, 32, 48, 96, 192)
},
framedelay = 5,
move = function(self)
self.y = self.y - self.speed
if self.y < 30 then self.y = 30; self.state = "up"; frame = 1 end
end
},
moveleft = {
quads = {
love.graphics.newQuad(0, 96, 32, 48, 96, 192),
love.graphics.newQuad(32, 96, 32, 48, 96, 192),
love.graphics.newQuad(64, 96, 32, 48, 96, 192)
},
framedelay = 4,
move = function(self)
self.x = self.x - self.speed
if self.x < 0 then self.x = 0; self.state = "left"; frame = 1 end
end
},
moveright = {
quads = {
love.graphics.newQuad(0, 144, 32, 48, 96, 192),
love.graphics.newQuad(32, 144, 32, 48, 96, 192),
love.graphics.newQuad(64, 144, 32, 48, 96, 192)
},
framedelay = 4,
move = function(self)
self.x = self.x + self.speed
if self.x + 32 > 800 then self.x = 800 - 32; self.state = "right"; frame = 1 end
end
},
down = { quads = { love.graphics.newQuad(32, 0, 32, 48, 96, 192) } },
up = { quads = { love.graphics.newQuad(32, 48, 32, 48, 96, 192) } },
left = { quads = { love.graphics.newQuad(32, 96, 32, 48, 96, 192) } },
right = { quads = { love.graphics.newQuad(32, 144, 32, 48, 96, 192) } }
},
speed = 4,
x = 380,
y = 250,
update = function ()
timer = timer + 1
if timer == tickdelay then
timer = 1
if game.field.player.states[game.field.player.state].framedelay ~= nil then
framedelay = framedelay + 1
if framedelay >= game.field.player.states[game.field.player.state].framedelay then
framedelay = 1
frame = frame + 1
if frame > table.getn(game.field.player.states[game.field.player.state].quads) then frame = 1 end
end
end
end
if game.field.player.states[game.field.player.state] and game.field.player.states[game.field.player.state].move then game.field.player.states[game.field.player.state].move(game.field.player) end
end
}) |
onTalk(function(name, level, mode, text, channelId, pos)
if mode == 34 then
if string.find(text, "world will suffer for") then
say("Are you ever going to fight or do you prefer talking!")
elseif string.find(text, "feet when they see me") then
say("Even before they smell your breath?")
elseif string.find(text, "from this plane") then
say("Too bad you barely exist at all!")
elseif string.find(text, "ESDO LO") then
say("SEHWO ASIMO, TOLIDO ESD")
elseif string.find(text, "will soon rule this world") then
say("Excuse me but I still do not get the message!")
elseif string.find(text, "honourable and formidable") then
say("Then why are we fighting alone right now?")
elseif string.find(text, "appear like a worm") then
say("How appropriate, you look like something worms already got the better of!")
elseif string.find(text, "will be the end of mortal") then
say("Then let me show you the concept of mortality before it!")
elseif string.find(text, "virtues of chivalry") then
say("Dare strike up a Minnesang and you will receive your last accolade!")
end
end
end) |
-- parent base:
component = {}
component.__index = component
component.colors = {
blue = {0.01, 0.46, 0.85, 1.0},
green = {0.36, 0.72, 0.36, 1.0},
cyan = {0.36, 0.75, 0.87, 1.0},
orange = {0.94, 0.68, 0.31, 1.0},
red = {0.85, 0.33, 0.31, 1.0},
black = {0.0, 0.0, 0.0, 1.0},
white = {1.0, 1.0, 1.0, 1.0},
clearGray = {0.97, 0.97, 0.97, 1.0},
darkGray = {0.16, 0.17, 0.17, 1.0},
darkGrayAlpha = {0.16, 0.17, 0.17, 0.59},
}
component.style = {
bgColor = component.colors.blue,
fgColor = component.colors.white, -- Foreground color
tooltipFont = love.graphics.newFont(love.window.toPixels(11)), -- tooltips are smaller than the main font
radius = 2, -- raw pixels
innerRadius = 2, -- raw pixels
showBorder = true, -- border for components
borderColor = component.colors.blue,
borderWidth = love.window.toPixels(2), -- in pixels
borderStyle = "smooth", -- or "smooth"
font = love.graphics.newFont(love.window.toPixels(13)),
}
local currId = -1
function genId()
currId = currId + 1
return currId;
end
local circleRes = 30
----------------------------------------------------------------------------
-------------------------- Component creator ----------------------------
----------------------------------------------------------------------------
function component.new(t, x, y, w, h, group)
local c = {}
c.id = genId()
c.type = t
c.x = x
c.y = y
c.w = w
c.h = h
c.enabled = true
c.visible = true
c.hasFocus = false
c.pressed = false
c.group = group or "default"
c.tooltip = nil
c.smallerSide = c.h
if c.w < c.h then
c.smallerSide = c.w
end
c.timerTooltip = 0
c.showTooltip = false
function c:setTooltip(text, reset)
self.tooltip = text or self.tooltip
if reset then
self.timerTooltip = 0
self.showTooltip = false
end
return self
end
c.touch = nil-- Stores the touch which is on this component.
c.opaque = true-- If false, the component base will never be drawn.
c.events = {p = nil, r = nil, m = nil}
function c:onPress(f)
c.events.p = f
return self
end
function c:onRelease(f)
c.events.r = f
return self
end
function c:onMoved(f)
c.events.m = f
return self
end
function c:bg(color)
if not color then
return self.style.bgColor
end
if type(color) == "string" then
color = gooi.toRGBA(color)
end
self.style.bgColor = color
self.style.borderColor = {color[1], color[2], color[3], 1}
self:make3d()
return self
end
function c:fg(color)
if not color then
return self.style.fgColor
end
self.style.fgColor = color
if type(color) == "string" then
self.style.fgColor = gooi.toRGBA(color)
end
return self
end
function c:setRadius(r, ri)
if not r then return self.style.radius, self.style.innerRadius; end
self.style.radius = r
if ri then
self.style.innerRadius = ri
end
return self
end
function c:border(w, color, style)
if not w then return self.style.borderWidth, self.style.borderColor; end
self.style.borderWidth = w
self.style.borderColor = color or {0.05, 0.72, 0.95, 1}
if type(color) == "string" then
self.style.borderColor = gooi.toRGBA(color)
self.style.borderColor[4] = 1
end
self.style.borderStyle = style or "smooth"
self.style.showBorder = true
return self
end
function c:noGlass()
self.glass = false
return self
end
function c:no3D()
self.mode3d = false
return self
end
c.style = gooi.deepcopy(component.style)
function c:make3d()
-- For a 3D look:
self.colorTop = self.style.bgColor
self.colorBot = self.style.bgColor
self.colorTop = changeBrig(self.style.bgColor, 0.06)
self.colorBot = changeBrig(self.style.bgColor, -0.06)
self.colorTopHL = changeBrig(self.style.bgColor, 0.1)
self.colorBotHL = changeBrig(self.style.bgColor, -0.02)
self.imgData3D = love.image.newImageData(1, 2)
self.imgData3D:setPixel(0, 0, self.colorTop[1], self.colorTop[2], self.colorTop[3], self.colorTop[4])
self.imgData3D:setPixel(0, 1, self.colorBot[1], self.colorBot[2], self.colorBot[3], self.colorBot[4])
self.imgData3DHL = love.image.newImageData(1, 2)
self.imgData3DHL:setPixel(0, 0, self.colorTopHL[1], self.colorTopHL[2], self.colorTopHL[3], self.colorTopHL[4])
self.imgData3DHL:setPixel(0, 1, self.colorBotHL[1], self.colorBotHL[2], self.colorBotHL[3], self.colorBotHL[4])
self.img3D = love.graphics.newImage(self.imgData3D)
self.img3DHL = love.graphics.newImage(self.imgData3DHL)
self.img3D:setFilter("linear", "linear")
self.img3DHL:setFilter("linear", "linear")
self.imgDataGlass = love.image.newImageData(1, 2)
self.imgDataGlass:setPixel(0, 0, 1, 1, 1, 0.31)
self.imgDataGlass:setPixel(0, 1, 1, 1, 1, 0.16)
self.imgGlass = love.graphics.newImage(self.imgDataGlass)
self.imgGlass:setFilter("linear", "linear")
end
function c:makeShadow()
self.heightShadow = 6
self.imgDataShadow = love.image.newImageData(1, self.heightShadow)
self.imgDataShadow:setPixel(0, 0, 0, 0, 0, 0.31)
self.imgDataShadow:setPixel(0, 1, 0, 0, 0, 0.12)
self.imgDataShadow:setPixel(0, 2, 0, 0, 0, 0.02)
self.imgShadow = love.graphics.newImage(self.imgDataShadow)
self.imgShadow:setFilter("linear", "linear")
end
c:makeShadow()
function c:primary() self:bg(component.colors.blue); return self end
function c:success() self:bg(component.colors.green); return self end
function c:info() self:bg(component.colors.cyan); return self end
function c:warning() self:bg(component.colors.orange); return self end
function c:danger() self:bg(component.colors.red); return self end
function c:opacity(o) self.style.bgColor[4] = o; return self end
function c:secondary()
self:bg(component.colors.clearGray)
self:fg(component.colors.darkGray)
return self
end
function c:inverted()
self:bg(component.colors.darkGray)
self:fg(component.colors.clearGray)
return self
end
c:make3d()
return setmetatable(c, component)
end
----------------------------------------------------------------------------
-------------------------- Draw the component ---------------------------
----------------------------------------------------------------------------
function component:draw()-- Every component has the same base:
local style = self.style
if self.opaque and self.visible then
local focusColorChange = 0.06
local fs = - 1
if not self.enabled then focusColorChange = 0 end
local newColor = style.bgColor
-- Generate bgColor for over and pressed:
if self:overIt() and self.type ~= "label" then
if not self.pressed then fs = 1 end
newColor = changeBrig(newColor, focusColorChange * fs)
if self.tooltip then
self.timerTooltip = self.timerTooltip + love.timer.getDelta()
if self.timerTooltip >= 0.5 then
self.showTooltip = true
end
end
else
self.timerTooltip = 0
self.showTooltip = false
end
love.graphics.setColor(newColor)
if not self.enabled then
love.graphics.setColor(1/4, 1/4, 1/4, style.bgColor[4] or 1)
end
local radiusCorner = style.radius
love.graphics.stencil(function()
love.graphics.rectangle("fill",
math.floor(self.x),
math.floor(self.y),
math.floor(self.w),
math.floor(self.h),
self.style.radius,
self.style.radius,
circleRes)
end, "replace", 1)
love.graphics.setStencilTest("greater", 0)
local scaleY = 1
local img = self.img3D
if self:overIt() then
img = self.img3DHL
if self.pressed then
img = self.img3D
if self.type == "button" then
scaleY = scaleY * -1
end
end
end
-- Correct light effect when 2 modes are set:
if self.mode3d and self.glass then
scaleY = -1
end
if self.mode3d then
love.graphics.setColor(1, 1, 1, style.bgColor[4] or 1)
if not self.enabled then
love.graphics.setColor(0, 0, 0, style.bgColor[4] or 1)
end
love.graphics.draw(img,
math.floor(self.x + self.w / 2),
math.floor(self.y + self.h / 2),
0,
math.floor(self.w),
self.h / 2 * scaleY,
img:getWidth() / 2,
img:getHeight() / 2)
else
love.graphics.rectangle("fill",
math.floor(self.x),
math.floor(self.y),
math.floor(self.w),
math.floor(self.h),
self.style.radius,
self.style.radius,
50
)
end
if self.glass then
love.graphics.setColor(1, 1, 1)
love.graphics.draw(self.imgGlass,
self.x,
self.y,
0,
math.floor(self.w),
self.h / 4)
end
if self.bgImage then
love.graphics.setColor(1, 1, 1)
love.graphics.draw(self.bgImage,
math.floor(self.x),
math.floor(self.y),
0,
self.w / self.bgImage:getWidth(),
self.h / self.bgImage:getHeight())
end
love.graphics.setStencilTest()
-- Border:
if style.showBorder then
love.graphics.setColor(newColor)
if not self.enabled then
love.graphics.setColor(1/4, 1/4, 1/4)
end
love.graphics.rectangle("line",
math.floor(self.x),
math.floor(self.y),
math.floor(self.w),
math.floor(self.h),
self.style.radius,
self.style.radius,
50)
end
end
end
function component:drawShadowPressed()
if self.pressed and self.type == "button" and self.shadow then
love.graphics.stencil(function()
love.graphics.rectangle("fill",
math.floor(self.x),
math.floor(self.y),
math.floor(self.w),
math.floor(self.h),
self.style.radius,
self.style.radius,
50)
end, "replace", 1)
love.graphics.setStencilTest("greater", 0)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(self.imgShadow,
self.x + self.w / 2,
self.y + self.h / 2,
0,
math.floor(self.w),
self.h / self.heightShadow,
self.imgShadow:getWidth() / 2,
self.imgShadow:getHeight() / 2
)
love.graphics.setStencilTest()
end
end
function component:setVisible(b)
self.visible = b
if self.sons then
for i = 1, #self.sons do
self.sons[i].ref.visible = b
end
end
end
function component:setEnabled(b)
self.enabled = b
if self.sons then
for i = 1, #self.sons do
local c = self.sons[i].ref
c.enabled = b
c.glass = b
c.mode3d = b
end
end
end
function component:setGroup(g)
self.group = g
if self.sons then
for i = 1, #self.sons do
self.sons[i].ref.group = g
end
end
return self
end
function component:wasReleased()
local b = self:overIt() and self.enabled and self.visible
if self.type == "text" then
if b then
love.keyboard.setTextInput(true)
end
end
if gooi.vibration and b then
love.system.vibrate(gooi.delayVibration)
end
return b
end
function component:overItAux(x, y)
-- Scale:
local xm = love.mouse.getX() / gooi.sx
local ym = love.mouse.getY() / gooi.sy
if self.touch then
xm, ym = self.touch.x, self.touch.y-- Already scaled.
end
-- Scale:
if x and y then
xm, ym = x, y
end
local radiusCorner = self.style.radius
local theX = self.x
local theY = self.y
local theW = self.w
local theH = self.h
-- Check if one of the "two" rectangles is on the mouse/finger:
local b = not (
xm < theX or
ym < theY + radiusCorner or
xm > theX + theW or
ym > theY + theH - radiusCorner
) or not (
xm < theX + radiusCorner or
ym < theY or
xm > theX + theW - radiusCorner or
ym > theY + theH
)
-- Check if mouse/finger is over one of the 4 "circles":
local x1, x2, y1, y2 =
theX + radiusCorner,
theX + theW - radiusCorner,
theY + radiusCorner,
theY + theH - radiusCorner
local hyp1 = math.sqrt(math.pow(xm - x1, 2) + math.pow(ym - y1, 2))
local hyp2 = math.sqrt(math.pow(xm - x2, 2) + math.pow(ym - y1, 2))
local hyp3 = math.sqrt(math.pow(xm - x1, 2) + math.pow(ym - y2, 2))
local hyp4 = math.sqrt(math.pow(xm - x2, 2) + math.pow(ym - y2, 2))
return (hyp1 < radiusCorner or
hyp2 < radiusCorner or
hyp3 < radiusCorner or
hyp4 < radiusCorner or b), index, xm, ym
end
function component:overIt(x, y)-- x and y if it's the first time pressed (no touch defined yet).
if self.type == "panel" or self.type == "label" then
return false
end
-- Not applicable in this case:
if not (self.enabled or self.visible) then return false end
if self.noFlag or self.okFlag or self.yesFlag then
return self:overItAux(x, y)
else
if gooi.showingDialog then
return false
else
return self:overItAux(x, y)
end
end
end
function component:setBounds(x, y, w, h)
local theX = x or self.x
local theY = y or self.y
local theW = w or self.w
local theH = h or self.h
self.x, self.y, self.w, self.h = theX, theY, theW, theH
if self.type == "joystick" or self.type == "knob" then
self.smallerSide = self.h
if self.w < self.h then
self.smallerSide = self.w
end
self.w, self.h = self.smallerSide, self.smallerSide
self:rebuild()
end
return self
end
function component:setBGImage(image)
if type(image) == "string" then
image = love.graphics.newImage(image)
end
self.bgImage = image
return self
end
function component:setOpaque(b)
self.opaque = b
return self
end
function changeBrig(color, amount)
if type(color) == "string" then
color = gooi.toRGBA(color)
end
local r, g, b, a = color[1], color[2], color[3], color[4] or 1
r = r + amount
g = g + amount
b = b + amount
--a = a + amount
if r < 0 then r = 0 end
if r > 1 then r = 1 end
if g < 0 then g = 0 end
if g > 1 then g = 1 end
if b < 0 then b = 0 end
if b > 1 then b = 1 end
--if a < 0 then a = 0 end
--if a > 1 then a = 1 end
return {r, g, b, a}
end |
author '¡SpyrokTVᵈᵉᵛ#0001'
description 'Logs server By ¡SpyrokTVᵈᵉᵛ#0001'
version '1.0'
game 'gta5'
fx_version 'bodacious'
server_script {
"server.lua",
"config.lua"
}
client_script 'client.lua'
|
ITEM.name = "Toothpaste"
ITEM.description = "A tube of toothpaste."
ITEM.longdesc = "A tube of toothpaste. Handy for keeping oral hygiene."
ITEM.model = "models/illusion/eftcontainers/toothpaste.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.price = 200
ITEM.flatweight = 0.020
ITEM.img = ix.util.GetMaterial("vgui/hud/valuable/toothpaste.png") |
function exec(context, arg)
return load(arg)()
end
function eval(context, arg)
return load("return " .. arg)()
end
|
local parser_config = require('nvim-treesitter.parsers').get_parser_configs()
parser_config.org = {
install_info = {
url = 'https://github.com/milisims/tree-sitter-org',
revision = 'f110024d539e676f25b72b7c80b0fd43c34264ef',
files = { 'src/parser.c', 'src/scanner.cc' },
},
filetype = 'org',
}
require('nvim-treesitter.configs').setup({
highlight = {
enable = true,
additional_vim_regex_highlighting = { 'org' },
},
playground = {
enable = true,
disable = {},
updatetime = 25, -- Debounced time for highlighting nodes in the playground from source code
persist_queries = false, -- Whether the query persists across vim sessions
keybindings = {
toggle_query_editor = 'o',
toggle_hl_groups = 'i',
toggle_injected_languages = 't',
toggle_anonymous_nodes = 'a',
toggle_language_display = 'I',
focus_language = 'f',
unfocus_language = 'F',
update = 'R',
goto_node = '<cr>',
show_help = '?',
},
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = 'gnn',
node_incremental = '.',
scope_incremental = 'grc',
node_decremental = ',',
},
},
refactor = {
highlight_definitions = {
enable = true,
},
smart_rename = {
enable = true,
keymaps = {
smart_rename = 'grr',
},
},
navigation = {
enable = true,
keymaps = {
goto_definition = 'gnd',
list_definitions = 'gnD',
},
},
},
textobjects = {
enable = true,
disable = {},
select = {
enable = true,
keymaps = {
['af'] = '@function.outer',
['if'] = '@function.inner',
['aC'] = '@class.outer',
['iC'] = '@class.inner',
['ac'] = '@conditional.outer',
['ic'] = '@conditional.inner',
['ae'] = '@block.outer',
['ie'] = '@block.inner',
['al'] = '@loop.outer',
['il'] = '@loop.inner',
['is'] = '@statement.inner',
['as'] = '@statement.outer',
['ad'] = '@comment.outer',
['am'] = '@call.outer',
['im'] = '@call.inner',
},
},
swap = {
enable = true,
swap_next = {
['<leader>a'] = '@parameter.inner',
},
swap_previous = {
['<leader>A'] = '@parameter.inner',
},
},
move = {
enable = true,
goto_next_start = {
[']m'] = '@function.outer',
[']]'] = '@class.outer',
},
goto_next_end = {
[']M'] = '@function.outer',
[']['] = '@class.outer',
},
goto_previous_start = {
['[m'] = '@function.outer',
['[['] = '@class.outer',
},
goto_previous_end = {
['[M'] = '@function.outer',
['[]'] = '@class.outer',
},
},
lsp_interop = {
enable = false,
},
},
ensure_installed = { 'javascript', 'typescript', 'php', 'go', 'python', 'lua', 'jsdoc', 'org', 'comment' },
})
|
local Overlay = {}
-- --- --- --- --
-- Constants
-- --- --- --- --
local nbShoots = 8
-- To get the final score when combos are made, a little waiting time is required
-- (between the first head(s) and the last head(s))
local nbFramesToWaitBeforeSavingScore = 60
-- --- --- --- --
-- Variables
-- --- --- --- --
-- Current shoot
local indexShoot = nil
-- The work on variables begins only when the service mode is started
-- (to avoid getting misleading values on memory)
local isReady = false
-- Just a "keep the last value of" score
local lastScore = 0
-- @see : nbFramesToWaitBeforeSavingScore
local saveScoreAtThisFrame
-- Accumulated score (to compute score by shoot)
local sumScore = 0
-- --- --- --- --- --
-- Memory Variables
-- --- --- --- --- --
local currentRest -- number of shoots remaining
local currentScore
-- --- --- --- --- --- --
-- GUI Specific values
-- --- --- --- --- --- --
local x
local y
local scoreShown
local scoreboardWidth = 410
local scoreboardHeight = 65
local xScoreBoard = 700
local yScoreBoard = 80
local xScoreShift = 50
local xCenterShift = 11
local xHead = 660
local yHead = 195
local xHeadShift = 30
local yHeadShift = 25
-- --- --- --- --- --- --
-- TAS Specific values
-- --- --- --- --- --- --
-- Heads' location
local headsGrid = {
{ '2', ' ', '4', '2', '1', ' ', ' ', '1', ' ', ' ', '1', '2', '4', ' ', '2' },
{ '1', ' ', ' ', '3', ' ', ' ', ' ', '4', ' ', ' ', ' ', '3', ' ', ' ', '1' },
{ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' },
{ '4', ' ', ' ', ' ', ' ', ' ', ' ', '0', ' ', ' ', ' ', ' ', ' ', ' ', '4' },
{ ' ', '0', '4', ' ', '0', ' ', '3', '1', '3', ' ', '0', ' ', '4', ' ', '0' },
{ ' ', ' ', ' ', ' ', ' ', ' ', ' ', '4', ' ', ' ', ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', ' ', '2', '3', ' ', ' ', ' ', ' ', ' ', '3', '2', ' ', ' ', ' ' },
{ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' },
{ ' ', ' ', '0', ' ', '1', ' ', ' ', ' ', ' ', ' ', '1', ' ', '0', ' ', ' ' },
{ ' ', ' ', '4', ' ', '2', ' ', ' ', '4', ' ', ' ', '2', ' ', '4', ' ', ' ' },
}
-- Heads which will be smashed per shoot
local headsByShoots = {
{
{ line = 9, column = 3 },
{ line = 9, column = 5 },
{ line = 10, column = 3 },
{ line = 10, column = 5 },
},
{
{ line = 4, column = 1 },
{ line = 5, column = 2 },
{ line = 5, column = 3 },
},
{
{ line = 5, column = 5 },
{ line = 7, column = 4 },
{ line = 7, column = 5 },
},
{
{ line = 1, column = 3 },
{ line = 1, column = 4 },
{ line = 1, column = 5 },
{ line = 2, column = 4 },
},
{
{ line = 4, column = 8 },
{ line = 5, column = 7 },
{ line = 5, column = 8 },
{ line = 5, column = 9 },
{ line = 6, column = 8 },
},
{
{ line = 1, column = 11 },
{ line = 1, column = 12 },
{ line = 1, column = 13 },
{ line = 2, column = 12 },
},
{
{ line = 4, column = 15 },
{ line = 5, column = 13 },
{ line = 5, column = 15 },
},
{
{ line = 9, column = 11 },
{ line = 9, column = 13 },
{ line = 10, column = 11 },
{ line = 10, column = 13 },
},
}
local scoreByShoots = { '-', '-', '-', '-', '-', '-', '-', '-' }
-- --- --- --
-- Overlay
-- --- --- --
local function serviceMode(fc)
-- [[ Compute score and update heads smashed ]] --
currentRest = memory.read_s32_le(0x1FE6D0)
currentScore = memory.read_s32_le(0x1F1F18)
if currentRest == 8 and currentScore == 0 then
isReady = true
end
if isReady then
-- When a change in the score is detected, we save it in a certain amount of frames
if currentScore ~= lastScore and saveScoreAtThisFrame == nil then
saveScoreAtThisFrame = fc + nbFramesToWaitBeforeSavingScore
end
-- When it's time ...
if fc == saveScoreAtThisFrame then
saveScoreAtThisFrame = nil
indexShoot = math.abs(currentRest - nbShoots)
-- ... save the score ...
scoreByShoots[indexShoot] = currentScore - sumScore
-- ... save the heads smashed location into the grid
for _, headProperties in ipairs(headsByShoots[indexShoot]) do
headsGrid[headProperties['line']][headProperties['column']] = '*'
end
sumScore = sumScore + scoreByShoots[indexShoot]
lastScore = currentScore
end
end
-- [[ Draw the GUI ]] --
-- Header
x = 750
y = 22
gui.drawText(x, y, '[TAS] Rival Schools - Service Mode', 'white', 'black', 15)
-- Scoreboard (layout)
gui.drawText(xScoreBoard, yScoreBoard - 20, 'Score by shoot', 'white', 'black', 15)
gui.drawRectangle(xScoreBoard, yScoreBoard, scoreboardWidth, scoreboardHeight)
gui.drawLine(
xScoreBoard,
math.floor(yScoreBoard + (scoreboardHeight / 2)),
xScoreBoard + scoreboardWidth,
math.floor(yScoreBoard + (scoreboardHeight / 2))
)
-- Scoreboard (values)
x = xScoreBoard + 10
y = yScoreBoard + 10
for index = 1, nbShoots do
x = x + (index == 1 and 0 or xScoreShift)
gui.drawText(x + xCenterShift, y, index, 'white', 'black', 15)
end
x = xScoreBoard + 10
y = yScoreBoard + 40
for index = 1, nbShoots do
x = x + (index == 1 and 0 or xScoreShift)
scoreShown = scoreByShoots[index]
gui.drawText(x + (scoreShown == '-' and xCenterShift or 0), y, scoreShown, 'white', 'black', 15)
end
-- Heads (values)
gui.drawText(xHead + 175, yHead - 25, 'Heads location', 'white', 'black', 15)
gui.drawText(xHead + 42, yHead - 5, '0:Raizo 1:Roberto 2:Sakura 3:Hinata 4:Shoma', 'white', 'black', 15)
gui.drawBox(
math.floor(xHead + (xHeadShift / 2)),
yHead - 7,
math.floor(xHead + xHeadShift + (#headsGrid[1] * xHeadShift)),
yHead + yHeadShift + (#headsGrid * yHeadShift)
)
gui.drawLine(
math.floor(xHead + (xHeadShift / 2)),
yHead + 15,
math.floor(xHead + xHeadShift + (#headsGrid[1] * xHeadShift)),
yHead + 15
)
for line, columns in ipairs(headsGrid) do
for column, value in ipairs(columns) do
gui.drawText(xHead + (column * xHeadShift), yHead + (line * yHeadShift), value, 'white', 'black', 15)
end
end
-- Heads (groups smashed)
for index = 1, nbShoots do
if scoreByShoots[index] ~= '-' then
local minLine, maxLine, minColumn, maxColumn
for _, headProperties in ipairs(headsByShoots[index]) do
local line = headProperties['line']
if minLine == nil or line < minLine then
minLine = line
end
if maxLine == nil or line > maxLine then
maxLine = line
end
local column = headProperties['column']
if minColumn == nil or column < minColumn then
minColumn = column
end
if maxColumn == nil or column > maxColumn then
maxColumn = column
end
end
gui.drawBox(
math.floor(xHead + (minColumn * xHeadShift)),
math.floor(yHead + (minLine * yHeadShift)),
math.floor(xHead + (xHeadShift / 2) + (maxColumn * xHeadShift)),
math.floor(yHead + (yHeadShift / 2) + (maxLine * yHeadShift))
)
end
end
end
local function applySubscriptions(mediator)
mediator:subscribe({ 'frame.displayed' }, function(fc)
serviceMode(fc)
end)
end
Overlay.applySubscriptions = applySubscriptions
return Overlay |
--------------------------------
-- @module PhysicsJointGroove
-- @extend PhysicsJoint
-- @parent_module cc
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] setAnchr2
-- @param self
-- @param #vec2_table anchr2
-- @return PhysicsJointGroove#PhysicsJointGroove self (return value: cc.PhysicsJointGroove)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] setGrooveA
-- @param self
-- @param #vec2_table grooveA
-- @return PhysicsJointGroove#PhysicsJointGroove self (return value: cc.PhysicsJointGroove)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] setGrooveB
-- @param self
-- @param #vec2_table grooveB
-- @return PhysicsJointGroove#PhysicsJointGroove self (return value: cc.PhysicsJointGroove)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] getGrooveA
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] getGrooveB
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] getAnchr2
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] createConstraints
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#PhysicsJointGroove] construct
-- @param self
-- @param #cc.PhysicsBody a
-- @param #cc.PhysicsBody b
-- @param #vec2_table grooveA
-- @param #vec2_table grooveB
-- @param #vec2_table anchr2
-- @return PhysicsJointGroove#PhysicsJointGroove ret (return value: cc.PhysicsJointGroove)
return nil
|
-- A convenience wrapper to support the convention of having the
-- cdefs for a library held in the global variable cdef_string.
local ffi=require 'ffi'
ffi.cdef 'char *cdef_string'
function ffi.load_with_cdefs(shared_object_name)
local shared_object = ffi.load(shared_object_name)
ffi.cdef(ffi.string(shared_object.cdef_string))
return shared_object
end
function ffi.require_and_load(library, so_file)
local handle = require(library)
if handle then
setmetatable(handle,
{__index=ffi.load_with_cdefs(so_file)})
end
return handle
end
return ffi
|
--影六武衆-リハン
--Shadow Six Samurai – Rihan
--Scripted by Eerie Code
--Fusion procedure by edo9300
function c100419006.initial_effect(c)
c:EnableReviveLimit()
--spsummon condition
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_SPSUMMON_CONDITION)
e0:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e0:SetValue(c100419006.splimit)
c:RegisterEffect(e0)
--Fusion procedure
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCondition(c100419006.fscon)
e1:SetOperation(c100419006.fsop)
c:RegisterEffect(e1)
--special summon rule
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPSUMMON_PROC)
e2:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e2:SetRange(LOCATION_EXTRA)
e2:SetCondition(c100419006.sprcon)
e2:SetOperation(c100419006.sprop)
c:RegisterEffect(e2)
--fusion limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CANNOT_BE_FUSION_MATERIAL)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(1)
c:RegisterEffect(e3)
--remove
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(100419006,0))
e4:SetCategory(CATEGORY_REMOVE)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1)
e4:SetCost(c100419006.rmcost)
e4:SetTarget(c100419006.rmtg)
e4:SetOperation(c100419006.rmop)
c:RegisterEffect(e4)
--destroy replace
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e5:SetCode(EFFECT_DESTROY_REPLACE)
e5:SetRange(LOCATION_GRAVE)
e5:SetTarget(c100419006.reptg)
e5:SetValue(c100419006.repval)
e5:SetOperation(c100419006.repop)
c:RegisterEffect(e5)
end
function c100419006.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA)
end
function c100419006.ffilter(c,fc)
return c:IsFusionSetCard(0x3d) and not c:IsHasEffect(6205579) and c:IsCanBeFusionMaterial(fc)
end
function c100419006.fselect(c,mg,sg,tp,fc)
if sg:IsExists(Card.IsFusionAttribute,1,nil,c:GetFusionAttribute()) then return false end
sg:AddCard(c)
local res=false
if sg:GetCount()==3 then
res=Duel.GetLocationCountFromEx(tp,tp,sg,fc)>0
else
res=mg:IsExists(c100419006.fselect,1,sg,mg,sg,tp,fc)
end
sg:RemoveCard(c)
return res
end
function c100419006.fscon(e,g,gc,chkf)
if g==nil then return true end
local c=e:GetHandler()
local tp=c:GetControler()
local mg=g:Filter(c100419006.ffilter,nil,c)
local sg=Group.CreateGroup()
if gc then return c100419006.ffilter(gc,c) and c100419006.fselect(gc,mg,sg,tp,c) end
return mg:IsExists(c100419006.fselect,1,sg,mg,sg,tp,c)
end
function c100419006.fsop(e,tp,eg,ep,ev,re,r,rp,gc,chkf)
local c=e:GetHandler()
local mg=eg:Filter(c100419006.ffilter,nil,c)
local sg=Group.CreateGroup()
if gc then sg:AddCard(gc) end
repeat
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g=mg:FilterSelect(tp,c100419006.fselect,1,1,sg,mg,sg,tp,c)
sg:Merge(g)
until sg:GetCount()==3
Duel.SetFusionMaterial(sg)
end
function c100419006.sprcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.IsExistingMatchingCard(c100419006.sprfilter1,tp,LOCATION_MZONE,0,1,nil,tp,c)
end
function c100419006.sprfilter1(c,tp,fc)
return c:IsFusionSetCard(0x3d) and c:IsAbleToGraveAsCost() and c:IsCanBeFusionMaterial(fc)
and Duel.IsExistingMatchingCard(c100419006.sprfilter2,tp,LOCATION_MZONE,0,1,c,fc,c:GetFusionAttribute())
end
function c100419006.sprfilter2(c,tp,fc,mc)
return c:IsFusionSetCard(0x3d) and c:IsAbleToGraveAsCost() and c:IsCanBeFusionMaterial(fc) and not c:IsFusionAttribute(mc:GetFusionAttribute())
and Duel.IsExistingMatchingCard(c100419006.sprfilter3,tp,LOCATION_MZONE,0,1,c,fc,att,c:GetFusionAttribute())
end
function c100419006.sprfilter3(c,tp,fc,mc1,mc2)
local g=Group.FromCards(c,mc1,mc2)
return c:IsFusionSetCard(0x3d) and c:IsAbleToGraveAsCost() and c:IsCanBeFusionMaterial(fc) and not c:IsFusionAttribute(mc1:GetFusionAttribute()) and not c:IsFusionAttribute(mc2:GetFusionAttribute())
and Duel.GetLocationCountFromEx(tp,tp,g)>0
end
function c100419006.sprop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g1=Duel.SelectMatchingCard(tp,c100419006.sprfilter1,tp,LOCATION_ONFIELD,0,1,1,nil,tp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g2=Duel.SelectMatchingCard(tp,c100419006.sprfilter2,tp,LOCATION_ONFIELD,0,1,1,g1:GetFirst(),tp,c,g1:GetFirst())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g3=Duel.SelectMatchingCard(tp,c100419006.sprfilter3,tp,LOCATION_ONFIELD,0,1,1,g1:GetFirst(),tp,c,g1:GetFirst(),g2:GetFirst())
g1:Merge(g2)
g1:Merge(g3)
Duel.SendtoGrave(g1,REASON_COST)
end
function c100419006.costfilter(c,tp)
return c:IsSetCard(0x3d) and c:IsAbleToRemoveAsCost() and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup())
and Duel.IsExistingTarget(Card.IsAbleToRemove,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,c)
end
function c100419006.rmcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c100419006.costfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c100419006.costfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c100419006.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsLocation(LOCATION_ONFIELD) and chkc:IsAbleToRemove() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
end
function c100419006.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c100419006.repfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x3d)
and c:IsOnField() and c:IsControler(tp) and c:IsReason(REASON_EFFECT+REASON_BATTLE)
end
function c100419006.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemove() and eg:IsExists(c100419006.repfilter,1,nil,tp) end
return Duel.SelectYesNo(tp,aux.Stringid(100419006,1))
end
function c100419006.repval(e,c)
return c100419006.repfilter(c,e:GetHandlerPlayer())
end
function c100419006.repop(e,tp,eg,ep,ev,re,r,rp)
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT)
end
|
--[[
Syntax highlighting color scheme based on the
color scheme used on http://lua-users.org/wiki/.
Author: Peter Odding <peter@peterodding.com>
Last Change: July 17, 2011
URL: http://peterodding.com/code/lua/lxsh/
]]
return {
comment = { color = 0x00A000 },
constant = { color = 0x009090 },
default = { color = 0x000000, background = 0xffffff },
keyword = { color = 0x000080, bold = true },
library = { color = 0x900090 },
marker = { background = 0xffff00 },
prompt = { color = 0x00A000 },
url = { color = 0x0000FF, underline = true }
}
|
ITEM.name = "Hunting Knife"
ITEM.description = "A short, sharp blade typically used to skin game while hunting. It could also be used against humans proficiently."
ITEM.model = "models/weapons/w_knife_stalker.mdl"
ITEM.class = "stalker_knife"
ITEM.weaponCategory = "melee"
ITEM.width = 1
ITEM.height = 2
ITEM.chance = 43 |
local base = require( "acid.paxos.base" )
local paxos = require( "acid.paxos" )
local tableutil = require( "acid.tableutil" )
local errors = base.errors
function test_new(t)
local cases = {
{
mid=nil,
impl=nil,
rst=nil,
err=errors.InvalidArgument,
},
{
mid={ cluster_id=nil, ident=nil },
impl=nil,
rst=nil,
err=errors.InvalidArgument,
},
{
mid={ cluster_id="x", ident=nil },
impl=nil,
rst=nil,
err=errors.InvalidArgument,
},
{
mid={ cluster_id=nil, ident="x" },
impl=nil,
rst=nil,
err=errors.InvalidArgument,
},
{
mid={ cluster_id="x", ident="x" },
impl=nil,
rst=nil,
err=nil,
},
}
for i, case in ipairs( cases ) do
local mes = "" .. i .. (case.mes or "")
local p, err, errmes = paxos.new(case.mid, case.impl)
if case.err then
t:eq( nil, p )
t:eq( case.err, err )
else
t:eq( nil, err )
end
end
end
local function make_implementation( opt )
local resps = tableutil.dup( opt.resps, true ) or {}
local stores = tableutil.dup( opt.stores, true ) or {}
local def_sto = tableutil.dup( opt.def_sto, true ) or {}
function _sendmes( self, p, id, mes )
local r = resps[ id ] or {}
if mes.cmd == 'phase1' then
r = r.p1
if r == nil then r = { rnd=mes.rnd } end
elseif mes.cmd == 'phase2' then
r = r.p2
if r == nil then r = {} end
elseif mes.cmd == 'phase3' then
r = r.p3
if r == nil then r = {} end
else
error( "invalid cmd" .. tableutil.repr( mes ) )
end
if r == false then
return nil
end
return r
end
local impl = {
send_req = _sendmes,
load = function( p )
local id = p.ident
local c = stores[ id ] or def_sto
return tableutil.dup( c, true )
end,
store = function( self, p )
local id = p.ident
stores[ id ] = tableutil.dup( p.record, true )
end,
time= function( self ) return os.time() end,
}
return impl
end
function test_set(t)
local def_sto = {
committed = {
ver=1,
val = {
view = { { a=1, b=1, c=1 } },
}
}
}
cases = {
{
mes = 'set ok',
key="akey", val="aval", ver=nil,
rst = { ver=2, key="akey", val="aval" },
err = nil,
p_ver=2,
resps = {
a={},
b={},
c={},
},
def_sto = def_sto,
},
{
mes = 'set with specific ver',
key="akey", val="aval", ver=1,
rst = { ver=2, key="akey", val="aval" },
err = nil,
p_ver=2,
resps = {
a={},
b={},
c={},
},
def_sto = def_sto,
},
{
mes = 'set with unsatisfied ver',
key="akey", val="aval", ver=3,
rst = nil,
err = 'VerNotExist',
p_ver=3,
resps = {
a={},
b={},
c={},
},
def_sto = def_sto,
},
{
mes = 'set with quorum failure',
key="akey", val="aval", ver=1,
rst = nil,
err = 'QuorumFailure',
p_ver=1,
resps = {
a={p1=false},
b={p1=false},
c={},
},
def_sto = def_sto,
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local impl = make_implementation({
resps = case.resps,
stores = case.stores,
def_sto = case.def_sto
})
local mid = { cluster_id="x", ident="a" }
local p, err = paxos.new( mid, impl, case.ver )
t:eq( nil, err, mes )
local c, err, errmes = p:set( case.key, case.val )
t:eq( case.err, err, mes )
t:eqdict( case.rst, c, mes )
t:eq( case.p_ver, p.ver, mes )
end
end
function test_get(t)
local def_sto = {
committed = {
ver=1,
val = {
foo = "bar",
view = { { a=1, b=1, c=1 } },
}
}
}
cases = {
{
mes = 'get failure 3',
key="akey", ver=nil,
rst = nil,
err = errors.QuorumFailure,
resps = {
a={p3=false},
b={p3=false},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'get failure 2',
key="akey", ver=nil,
rst = nil,
err = errors.QuorumFailure,
resps = {
a={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
b={p3=false},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'get not found',
key="akey", ver=nil,
rst = {ver=1, key="akey", val=nil},
err = nil,
resps = {
a={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
b={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'get found',
key="foo", ver=nil,
rst = {ver=1, key="foo", val="bar"},
err = nil,
resps = {
a={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
b={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'get found latest',
key="foo", ver=nil,
rst = {ver=2, key="foo", val="bar2"},
err = nil,
resps = {
a={p3={err={Code=errors.AlreadyCommitted, Message=def_sto.committed}}},
b={p3={err={Code=errors.AlreadyCommitted, Message={
ver=2,
val = {
foo = "bar2",
view = { { a=1, b=1, c=1 } },
}
}}}},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'set with unsatisfied ver',
key="akey", ver=3,
rst = nil,
err = 'VerNotExist',
resps = {
a={},
b={},
c={},
},
def_sto = def_sto,
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local impl = make_implementation({
resps = case.resps,
stores = case.stores,
def_sto = case.def_sto
})
local mid = { cluster_id="x", ident="a" }
local p, err = paxos.new( mid, impl, case.ver )
t:eq( nil, err, mes )
local c, err, errmes = p:get( case.key )
t:eq( case.err, err, mes )
t:eqdict( case.rst, c, mes )
end
end
function test_sendmes(t)
local def_sto = {
committed = {
ver=1,
val = {
foo = "bar",
view = { { a=1, b=1, c=1 } },
}
}
}
cases = {
{
mes = 'send get nothing back',
key="akey", ver=nil,
req = {cmd="phase3"},
to_id = 'a',
rst = nil,
err = nil,
resps = {
a={p3=false},
b={p3=false},
c={p3=false},
},
def_sto = def_sto,
},
{
mes = 'send get something',
key="akey", ver=nil,
req = {cmd="phase3"},
to_id = 'a',
rst = {a=1},
err = nil,
resps = {
a={p3={a=1}},
b={p3={b=2}},
c={p3=false},
},
def_sto = def_sto,
},
}
for i, case in ipairs( cases ) do
mes = i .. ": " .. (case.mes or '')
resps = case.resps
local impl = make_implementation({
resps = case.resps,
stores = case.stores,
def_sto = case.def_sto
})
local mid = { cluster_id="x", ident="a" }
local p, err = paxos.new( mid, impl, case.ver )
t:eq( nil, err, mes )
local c, err, errmes = p:send_req( case.to_id, case.req )
t:eq( case.err, err, mes )
t:eqdict( case.rst, c, mes )
end
end
|
-- Example of your main gamestate, handling creation of the level and its entities, and setting up input callbacks.
local play = gamestate.new()
local gui, level, player, world, physics, input
function play:init()
-- Create GUI
gui = GUI()
-- Create level with physics world
level = Level(LevelData())
world = level:getPhysicsWorld()
world:setGravity(0, 300)
-- Set up example
player = level:createEntity("SpaceShip")
player:setPos( 0, 0 )
--Get input controller
input = getInput()
input:addMousePressCallback( "zoomin", MOUSE.WHEELUP, function()
local cam = level:getCamera()
local sx, sy = cam:getScale()
cam:setScale( sx + 0.1 )
end)
input:addMousePressCallback( "zoomout", MOUSE.WHEELDOWN, function()
local cam = level:getCamera()
local sx, sy = cam:getScale()
cam:setScale( sx - 0.1 )
end)
input:addMousePressCallback( "turn", MOUSE.RIGHT, function()
level:getCamera():rotate( math.pi / 10 )
end)
input:addGamepadPressCallback( "turnother", "x", function()
level:getCamera():rotate( -math.pi / 10 )
end)
-- Spawn objects part of the level data
level:spawnObjects()
-- Particle system test
level:createEntity("ParticleSystem", "Black Hole")
end
function play:enter()
end
function play:leave()
end
function play:update( dt )
if (input:keyIsPressed("t")) then
game.openMenu()
end
level:update( dt )
gui:update( dt )
end
function play:draw()
level:draw()
gui:draw()
level:getCamera():draw( function()
love.graphics.setColor( Color.getRGB("Red") )
love.graphics.line( 0, 0, 10, 0 )
love.graphics.line( 0, 0, 0, 10 )
love.graphics.setColor( Color.getRGB("White") )
end)
local mx, my = screen.getMousePosition()
local mwx, mwy = level:getCamera():getMouseWorldPos()
love.graphics.setColor( Color.getRGB("White") )
love.graphics.print( "["..math.round(mwx)..", "..math.round(mwy).."]", mx + 8, my )
end
return play |
obj.spec.paused = nil
return obj |
--[[DOC
A more complex example to be embedded with linject, e.g. into luancher.exe. It
is a lua script runner that handle some non-trivial cases.
luancher.exe will set the lua package.path and cpath so that lua will load all
the .lua and .dll files in the same directory (of luancher.exe). Then it will
try to execute two lua script.
The first script is config.lua in the same directory. Its purpose is to
configure global variables, so it is run in a sandbox environment just contain
- the variable 'this_directory' containing the obsolute path of the directory
containing config.lua file with the links expanded
- the following standard lua globals: assert, coroutine, error, os.getenv,
ipairs, math, next, pairs, pcall, string, table, tonumber, tostring, type,
unpack, xpcall.
- the 'chainload' global function that will load another lua script in the same
environment (it takes the path to the file as the argument)
If the config.lua file is not found luancher.exe will not raise any error.
The second script is the first match of the following list:
- the main.lua file in the same directory of the executable
- the .lua file with same name in the same directory of the executable (e.g.
luancher.lua)
- the first argument ONLY IF it has the .lua extension
- the file handle_e_YYY.XXX.lua in the same directory of luancher.exe, where
YYY is the laucher name (e.g. luancher) and .XXX is the extension of the
file passed as first argument (can be empty)
- the file handler_n_YYY.XXX.lua where YYY is the laucher name (e.g. luancher)
and XXX is the first argument ONLY IF the first argument has no path and no
extension
It is run in the full lua environment and if it is not found luancher will
print an error message containing all the script tryed.
Whatever script is run, it will receve the following arguments:
same arguments descibed in the
luaject section but with arg[0] replaced by
- arg[-1] - command line path to the executable (the C argv[0]) with links resolved ( ??? TODO : check this !!! )
- arg[0] - the script that was chosen (absolute path with links resolved)
- arg[N] - (N>0) are the rest of command line arguments
Note that the directory containing the launcher, that is used for package.path
and cpath also, is the one passed by luamain.o as arg[-1] i.e. has all the
filesystem link resolved. So, for example, if you have
```
...
/bin/luancher.exe
/bin/luancher.lua
/bin/module.lua
/module.lua
/luancher.lua
/luancher.exe -> my_project/bin/luancher.exe
...
```
and /bin/luancher.lua contains
```
local ex = require 'module'
```
while /luancher.lua is empty, launching /luancher.exe will
results in the loading of /bin/luancher.lua (not /luancher.lua) and then it will
require /bin/module.lua (not /module.lua)
Note that you can find tools similar to luancher around the web, e.g.
[l-bia](http://l-bia.sourceforge.net) (but I never tryed it).
Why all this words for such small tool? I changed a lot of times the way this
software work. So I just needed to FREEZE all, and print my thought somewhere
for the me of the future. :)
]]
if type(arg[-1]) ~= 'string' then return nil end
function path_split(str)
local p = str:match('(.*[/\\])[^/\\]*')
local n = str:match('([^/\\]*)$'):gsub('%.[^/\\%.]*$','')
local e = str:match('%.[^/\\%.]*$')
if not p then p = '' end
if not n then n = '' end
if not e then e = '' end
return p,n,e
end
local realpath, progname, extension = path_split(whereami)
package.path = realpath .. '?.lua;' .. realpath .. '?/init.lua'
package.cpath = realpath .. '?.dll;' .. realpath .. 'lib?.so'
local chainload = (function()
local sandbox = {
--print = print,
assert = assert, coroutine = coroutine, error = error,
os = {getenv = os.getenv}, ipairs = ipairs, math = math, next = next,
pairs = pairs, pcall = pcall, string = string, table = table,
tonumber = tonumber, tostring = tostring, type = type, unpack = unpack,
xpcall = xpall,
}
sandbox.chainload = function (file)
sandbox.this_directory = file:gsub('[/\\][^/\\]*$','')
local t = io.open(file)
if t then
t:close()
loadfile(file,'t',sandbox)()
end -- missing config is not an error !
return sandbox
end
return sandbox.chainload
end)()
local conf = chainload(realpath..'config.lua')
-- CONF keys are merged into global when there is no conflict.
-- Conflicting keys are avaiable in the CONFLICT global
for k,v in pairs(conf) do
if _G[k] == nil then
_G[k] = v
else
if not CONFLICT then CONFLICT = {} end
CONFLICT[k] = v
end
end
local script_list = {}
function script_list:append(s) script_list[1+#(script_list)]=s end
script_list:append(realpath .. 'main.lua')
script_list:append(realpath .. progname .. '.lua')
if arg[1] then
if ae == '.lua' then
script_list:append (arg[1])
end
local ap,an,ae = path_split(arg[1])
script_list:append (realpath .. 'handle_e_' .. progname .. ae .. '.lua')
if ap == '' and ae == '' and an ~= '' then
script_list:append (realpath .. 'handle_n_' .. progname .. '.' .. an .. '.lua')
end
end
for _,s in ipairs(script_list) do
local file = io.open(s,'rb')
if file then
file:close()
arg[0] = s
local chunk,err = loadfile(arg[0])
if not chunk then
error('error loading file '..arg[0]..':\n'..err)
end
return chunk()
end
end
local err = ''
if #(script_list) == 0 then
err = ' None'
else
for _,s in ipairs(script_list) do
err = err .. '\n ' .. s
end
end
error('Can not find the script to launch. Tryed: '..err)
|
/*
* Torrent - 2013 Illuminati Productions
*
* This product is 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.
*
*/
// All of the weapons that are given to players to build with.
// If you want to change what weapons are given, this is the place.
TR_WEAPONS_BUILD = {
"weapon_physgun",
"torrent_tool",
"weapon_crowbar"
}
|
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local core = require("apisix.core")
local ngx = ngx
local ngx_re = require("ngx.re")
local ipairs = ipairs
local consumer_mod = require("apisix.consumer")
local lualdap = require("lualdap")
local lrucache = core.lrucache.new({
ttl = 300, count = 512
})
local schema = {
type = "object",
title = "work with route or service object",
properties = {
base_dn = { type = "string" },
ldap_uri = { type = "string" },
use_tls = { type = "boolean" },
uid = { type = "string" }
},
required = {"base_dn","ldap_uri"},
}
local consumer_schema = {
type = "object",
title = "work with consumer object",
properties = {
user_dn = { type = "string" },
},
required = {"user_dn"},
}
local plugin_name = "ldap-auth"
local _M = {
version = 0.1,
priority = 2540,
type = 'auth',
name = plugin_name,
schema = schema,
consumer_schema = consumer_schema
}
function _M.check_schema(conf, schema_type)
local ok, err
if schema_type == core.schema.TYPE_CONSUMER then
ok, err = core.schema.check(consumer_schema, conf)
else
ok, err = core.schema.check(schema, conf)
end
return ok, err
end
local create_consumer_cache
do
local consumer_names = {}
function create_consumer_cache(consumers)
core.table.clear(consumer_names)
for _, consumer in ipairs(consumers.nodes) do
core.log.info("consumer node: ", core.json.delay_encode(consumer))
consumer_names[consumer.auth_conf.user_dn] = consumer
end
return consumer_names
end
end -- do
local function extract_auth_header(authorization)
local obj = { username = "", password = "" }
local m, err = ngx.re.match(authorization, "Basic\\s(.+)", "jo")
if err then
-- error authorization
return nil, err
end
if not m then
return nil, "Invalid authorization header format"
end
local decoded = ngx.decode_base64(m[1])
if not decoded then
return nil, "Failed to decode authentication header: " .. m[1]
end
local res
res, err = ngx_re.split(decoded, ":")
if err then
return nil, "Split authorization err:" .. err
end
if #res < 2 then
return nil, "Split authorization err: invalid decoded data: " .. decoded
end
obj.username = ngx.re.gsub(res[1], "\\s+", "", "jo")
obj.password = ngx.re.gsub(res[2], "\\s+", "", "jo")
return obj, nil
end
function _M.rewrite(conf, ctx)
core.log.info("plugin rewrite phase, conf: ", core.json.delay_encode(conf))
-- 1. extract authorization from header
local auth_header = core.request.header(ctx, "Authorization")
if not auth_header then
core.response.set_header("WWW-Authenticate", "Basic realm='.'")
return 401, { message = "Missing authorization in request" }
end
local user, err = extract_auth_header(auth_header)
if err then
return 401, { message = err }
end
-- 2. try authenticate the user against the ldap server
local uid = conf.uid or "cn"
local userdn = uid .. "=" .. user.username .. "," .. conf.base_dn
local ld = lualdap.open_simple (conf.ldap_uri, userdn, user.password, conf.use_tls)
if not ld then
return 401, { message = "Invalid user authorization" }
end
-- 3. Retrieve consumer for authorization plugin
local consumer_conf = consumer_mod.plugin(plugin_name)
if not consumer_conf then
return 401, {message = "Missing related consumer"}
end
local consumers = lrucache("consumers_key", consumer_conf.conf_version,
create_consumer_cache, consumer_conf)
local consumer = consumers[userdn]
if not consumer then
return 401, {message = "Invalid API key in request"}
end
consumer_mod.attach_consumer(ctx, consumer, consumer_conf)
core.log.info("hit basic-auth access")
end
return _M
|
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- BBCNet dataset loader
--
local image = require 'image'
local paths = require 'paths'
local t = require 'datasets/transforms'
local ffi = require 'ffi'
local M = {}
local BBCnetDataset = torch.class('resnet.BBCnetDataset', M)
function BBCnetDataset:__init(imageInfo, opt, split)
self.imageInfo = imageInfo[split]
self.opt = opt
self.split = split
self.dir = opt.data
print(self.imageInfo)
assert(paths.dirp(self.dir), 'directory does not exist: ' .. self.dir)
end
function BBCnetDataset:get(i)
-- At this stage, images should be 122x122. They will become 112x112 by random croppings. When testing this cropping is centered (non-random).
local path = ffi.string(self.imageInfo.imagePath[i]:data())
--local Bb = self.imageInfo.imageBb[i] -- Use this to start from the images (you can use a fixed Bounding Box, since the images are already certered and scaled).
--local images = self:_loadImage(paths.concat(self.dir, path),Bb) -- Use this to start from the images.
local class = self.imageInfo.imageClass[i]
local p1 = self.opt.imagecrop
local p2 = paths.basename(string.sub(path,1,string.len(path)-8))
local className = string.sub(p2,1,-7)
local p3 = p1 .. className .. "/" .. self.split .. "/" .. p2 .. ".t7"
--images = images*255 -- Use this to start from the images.
--torch.save(p3,images:type('torch.ByteTensor')) -- Use this to start from the images.
--Assuming you have saved the images in as torch.ByteTensor :
local images = torch.load(p3)
images = (images:float())/255
return {
input = images,
target = class,
}
end
function BBCnetDataset:_loadImage(p, Bb)
local Nfr = self.opt.Nfr
local Dmarg = self.opt.Dmarg
local Do = self.opt.Dimage + 2*Dmarg -- 112 + 2*5 = 122
local tocrop = torch.Tensor{80,116,176,212} -- or use Bb variable to define you our cropping coordinates
local collection = torch.Tensor(Nfr,1,Do,Do)
local i=0
for i=1,Nfr do
local path_i = string.sub(p,1,string.len(p)-7) .. string.format("%03d",i) .. ".png" -- GRAYSCALE ASSUMED
local ok, input = pcall(function()
return image.load(path_i, 1, 'float')
end)
input = image.crop(input,tocrop[1],tocrop[2],tocrop[3],tocrop[4])
input = image.scale(input,Do,Do,'bilinear')
collection[{{i},{},{},{}}] = input
end
return collection
end
function BBCnetDataset:size()
return self.imageInfo.imageClass:size(1)
end
-- Computed from random subset of BBCNet training images
local meanstd = {
mean = { 0.4161},
std = { 0.1688 },
} -- These stats were estimated using a very small subset. Alternatively, you can use your own or simply mean = 0.5, std = 1.0
function BBCnetDataset:preprocess()
if self.split == 'train' then
return t.Compose{
t.MyRandomCrop(self.opt.Dimage),
t.ColorNormalize(meanstd),
t.HorizontalFlip(0.5),
}
elseif self.split == 'val' or self.split == 'test' then
return t.Compose{
t.ColorNormalize(meanstd),
t.CenterCrop(self.opt.Dimage),
}
else
error('invalid split: ' .. self.split)
end
end
return M.BBCnetDataset
|
--[[---------------------------------------------------------
Name: gamemode:OnPhysgunFreeze( weapon, phys, ent, player )
Desc: The physgun wants to freeze a prop
-----------------------------------------------------------]]
function GM:OnPhysgunFreeze( weapon, phys, ent, ply )
-- Object is already frozen (!?)
if ( !phys:IsMoveable() ) then return false end
if ( ent:GetUnFreezable() ) then return false end
phys:EnableMotion( false )
-- With the jeep we need to pause all of its physics objects
-- to stop it spazzing out and killing the server.
if ( ent:GetClass() == "prop_vehicle_jeep" ) then
local objects = ent:GetPhysicsObjectCount()
for i = 0, objects - 1 do
local physobject = ent:GetPhysicsObjectNum( i )
physobject:EnableMotion( false )
end
end
-- Add it to the player's frozen props
ply:AddFrozenPhysicsObject( ent, phys )
return true
end
--[[---------------------------------------------------------
Name: gamemode:OnPhysgunReload( weapon, player )
Desc: The physgun wants to freeze a prop
-----------------------------------------------------------]]
function GM:OnPhysgunReload( weapon, ply )
ply:PhysgunUnfreeze()
end
--[[---------------------------------------------------------
Name: gamemode:PlayerAuthed()
Desc: Player's STEAMID has been authed
-----------------------------------------------------------]]
function GM:PlayerAuthed( ply, SteamID, UniqueID )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerCanPickupWeapon()
Desc: Called when a player tries to pickup a weapon.
return true to allow the pickup.
-----------------------------------------------------------]]
function GM:PlayerCanPickupWeapon( ply, entity )
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerCanPickupItem()
Desc: Called when a player tries to pickup an item.
return true to allow the pickup.
-----------------------------------------------------------]]
function GM:PlayerCanPickupItem( ply, entity )
return true
end
--[[---------------------------------------------------------
Name: gamemode:CanPlayerUnfreeze()
Desc: Can the player unfreeze this entity & physobject
-----------------------------------------------------------]]
function GM:CanPlayerUnfreeze( ply, entity, physobject )
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerDisconnected()
Desc: Player has disconnected from the server.
-----------------------------------------------------------]]
function GM:PlayerDisconnected( ply )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSay()
Desc: A player (or server) has used say. Return a string
for the player to say. Return an empty string if the
player should say nothing.
-----------------------------------------------------------]]
function GM:PlayerSay( ply, text, teamonly )
return text
end
--[[---------------------------------------------------------
Name: gamemode:PlayerDeathThink( player )
Desc: Called when the player is waiting to respawn
-----------------------------------------------------------]]
function GM:PlayerDeathThink( pl )
if ( pl.NextSpawnTime && pl.NextSpawnTime > CurTime() ) then return end
if ( pl:IsBot() || pl:KeyPressed( IN_ATTACK ) || pl:KeyPressed( IN_ATTACK2 ) || pl:KeyPressed( IN_JUMP ) ) then
pl:Spawn()
end
end
--[[---------------------------------------------------------
Name: gamemode:PlayerUse( player, entity )
Desc: A player has attempted to use a specific entity
Return true if the player can use it
------------------------------------------------------------]]
function GM:PlayerUse( ply, entity )
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSilentDeath()
Desc: Called when a player dies silently
-----------------------------------------------------------]]
function GM:PlayerSilentDeath( Victim )
Victim.NextSpawnTime = CurTime() + 2
Victim.DeathTime = CurTime()
end
-- Pool network strings used for PlayerDeaths.
util.AddNetworkString( "PlayerKilled" )
util.AddNetworkString( "PlayerKilledSelf" )
util.AddNetworkString( "PlayerKilledByPlayer" )
--[[---------------------------------------------------------
Name: gamemode:PlayerDeath()
Desc: Called when a player dies.
-----------------------------------------------------------]]
function GM:PlayerDeath( ply, inflictor, attacker )
-- Don't spawn for at least 2 seconds
ply.NextSpawnTime = CurTime() + 2
ply.DeathTime = CurTime()
if ( IsValid( attacker ) && attacker:GetClass() == "trigger_hurt" ) then attacker = ply end
if ( IsValid( attacker ) && attacker:IsVehicle() && IsValid( attacker:GetDriver() ) ) then
attacker = attacker:GetDriver()
end
if ( !IsValid( inflictor ) && IsValid( attacker ) ) then
inflictor = attacker
end
-- Convert the inflictor to the weapon that they're holding if we can.
-- This can be right or wrong with NPCs since combine can be holding a
-- pistol but kill you by hitting you with their arm.
if ( IsValid( inflictor ) && inflictor == attacker && ( inflictor:IsPlayer() || inflictor:IsNPC() ) ) then
inflictor = inflictor:GetActiveWeapon()
if ( !IsValid( inflictor ) ) then inflictor = attacker end
end
player_manager.RunClass( ply, "Death", inflictor, attacker )
if ( attacker == ply ) then
net.Start( "PlayerKilledSelf" )
net.WriteEntity( ply )
net.Broadcast()
MsgAll( attacker:Nick() .. " suicided!\n" )
return end
if ( attacker:IsPlayer() ) then
net.Start( "PlayerKilledByPlayer" )
net.WriteEntity( ply )
net.WriteString( inflictor:GetClass() )
net.WriteEntity( attacker )
net.Broadcast()
MsgAll( attacker:Nick() .. " killed " .. ply:Nick() .. " using " .. inflictor:GetClass() .. "\n" )
return end
net.Start( "PlayerKilled" )
net.WriteEntity( ply )
net.WriteString( inflictor:GetClass() )
net.WriteString( attacker:GetClass() )
net.Broadcast()
MsgAll( ply:Nick() .. " was killed by " .. attacker:GetClass() .. "\n" )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerInitialSpawn()
Desc: Called just before the player's first spawn
-----------------------------------------------------------]]
function GM:PlayerInitialSpawn( pl, transiton )
pl:SetTeam( TEAM_UNASSIGNED )
if ( GAMEMODE.TeamBased ) then
pl:ConCommand( "gm_showteam" )
end
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSpawnAsSpectator()
Desc: Player spawns as a spectator
-----------------------------------------------------------]]
function GM:PlayerSpawnAsSpectator( pl )
pl:StripWeapons()
if ( pl:Team() == TEAM_UNASSIGNED ) then
pl:Spectate( OBS_MODE_FIXED )
return
end
pl:SetTeam( TEAM_SPECTATOR )
pl:Spectate( OBS_MODE_ROAMING )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSpawn()
Desc: Called when a player spawns
-----------------------------------------------------------]]
function GM:PlayerSpawn( pl, transiton )
--
-- If the player doesn't have a team in a TeamBased game
-- then spawn him as a spectator
--
if ( self.TeamBased && ( pl:Team() == TEAM_SPECTATOR || pl:Team() == TEAM_UNASSIGNED ) ) then
self:PlayerSpawnAsSpectator( pl )
return
end
-- Stop observer mode
pl:UnSpectate()
pl:SetupHands()
player_manager.OnPlayerSpawn( pl, transiton )
player_manager.RunClass( pl, "Spawn" )
-- If we are in transition, do not touch player's weapons
if ( !transiton ) then
-- Call item loadout function
hook.Call( "PlayerLoadout", GAMEMODE, pl )
end
-- Set player model
hook.Call( "PlayerSetModel", GAMEMODE, pl )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSetModel()
Desc: Set the player's model
-----------------------------------------------------------]]
function GM:PlayerSetModel( pl )
player_manager.RunClass( pl, "SetModel" )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSetHandsModel()
Desc: Sets the player's view model hands model
-----------------------------------------------------------]]
function GM:PlayerSetHandsModel( pl, ent )
local info = player_manager.RunClass( pl, "GetHandsModel" )
if ( !info ) then
local playermodel = player_manager.TranslateToPlayerModelName( pl:GetModel() )
info = player_manager.TranslatePlayerHands( playermodel )
end
if ( info ) then
ent:SetModel( info.model )
ent:SetSkin( info.skin )
ent:SetBodyGroups( info.body )
end
end
--[[---------------------------------------------------------
Name: gamemode:PlayerLoadout()
Desc: Give the player the default spawning weapons/ammo
-----------------------------------------------------------]]
function GM:PlayerLoadout( pl )
player_manager.RunClass( pl, "Loadout" )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSelectTeamSpawn( player )
Desc: Find a spawn point entity for this player's team
-----------------------------------------------------------]]
function GM:PlayerSelectTeamSpawn( TeamID, pl )
local SpawnPoints = team.GetSpawnPoints( TeamID )
if ( !SpawnPoints || table.IsEmpty( SpawnPoints ) ) then return end
local ChosenSpawnPoint = nil
for i = 0, 6 do
local ChosenSpawnPoint = table.Random( SpawnPoints )
if ( hook.Call( "IsSpawnpointSuitable", GAMEMODE, pl, ChosenSpawnPoint, i == 6 ) ) then
return ChosenSpawnPoint
end
end
return ChosenSpawnPoint
end
--[[---------------------------------------------------------
Name: gamemode:IsSpawnpointSuitable( player )
Desc: Find out if the spawnpoint is suitable or not
-----------------------------------------------------------]]
function GM:IsSpawnpointSuitable( pl, spawnpointent, bMakeSuitable )
local Pos = spawnpointent:GetPos()
-- Note that we're searching the default hull size here for a player in the way of our spawning.
-- This seems pretty rough, seeing as our player's hull could be different.. but it should do the job
-- (HL2DM kills everything within a 128 unit radius)
local Ents = ents.FindInBox( Pos + Vector( -16, -16, 0 ), Pos + Vector( 16, 16, 64 ) )
if ( pl:Team() == TEAM_SPECTATOR ) then return true end
local Blockers = 0
for k, v in pairs( Ents ) do
if ( IsValid( v ) && v != pl && v:GetClass() == "player" && v:Alive() ) then
Blockers = Blockers + 1
if ( bMakeSuitable ) then
v:Kill()
end
end
end
if ( bMakeSuitable ) then return true end
if ( Blockers > 0 ) then return false end
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSelectSpawn( player )
Desc: Find a spawn point entity for this player
-----------------------------------------------------------]]
function GM:PlayerSelectSpawn( pl, transiton )
-- If we are in transition, do not reset player's position
if ( transiton ) then return end
if ( self.TeamBased ) then
local ent = self:PlayerSelectTeamSpawn( pl:Team(), pl )
if ( IsValid( ent ) ) then return ent end
end
-- Save information about all of the spawn points
-- in a team based game you'd split up the spawns
if ( !IsTableOfEntitiesValid( self.SpawnPoints ) ) then
self.LastSpawnPoint = 0
self.SpawnPoints = ents.FindByClass( "info_player_start" )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_deathmatch" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_combine" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_rebel" ) )
-- CS Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_counterterrorist" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_terrorist" ) )
-- DOD Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_axis" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_allies" ) )
-- (Old) GMod Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "gmod_player_start" ) )
-- TF Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_teamspawn" ) )
-- INS Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "ins_spawnpoint" ) )
-- AOC Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "aoc_spawnpoint" ) )
-- Dystopia Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "dys_spawn_point" ) )
-- PVKII Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_pirate" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_viking" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_knight" ) )
-- DIPRIP Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "diprip_start_team_blue" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "diprip_start_team_red" ) )
-- OB Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_red" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_blue" ) )
-- SYN Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_coop" ) )
-- ZPS Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_human" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_zombie" ) )
-- ZM Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_zombiemaster" ) )
-- FOF Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_fof" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_desperado" ) )
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_player_vigilante" ) )
-- L4D Maps
self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_survivor_rescue" ) )
-- Removing this one for the time being, c1m4_atrium has one of these in a box under the map
--self.SpawnPoints = table.Add( self.SpawnPoints, ents.FindByClass( "info_survivor_position" ) )
end
local Count = table.Count( self.SpawnPoints )
if ( Count == 0 ) then
Msg("[PlayerSelectSpawn] Error! No spawn points!\n")
return nil
end
-- If any of the spawnpoints have a MASTER flag then only use that one.
-- This is needed for single player maps.
for k, v in pairs( self.SpawnPoints ) do
if ( v:HasSpawnFlags( 1 ) && hook.Call( "IsSpawnpointSuitable", GAMEMODE, pl, v, true ) ) then
return v
end
end
local ChosenSpawnPoint = nil
-- Try to work out the best, random spawnpoint
for i = 1, Count do
ChosenSpawnPoint = table.Random( self.SpawnPoints )
if ( IsValid( ChosenSpawnPoint ) && ChosenSpawnPoint:IsInWorld() ) then
if ( ( ChosenSpawnPoint == pl:GetVar( "LastSpawnpoint" ) || ChosenSpawnPoint == self.LastSpawnPoint ) && Count > 1 ) then continue end
if ( hook.Call( "IsSpawnpointSuitable", GAMEMODE, pl, ChosenSpawnPoint, i == Count ) ) then
self.LastSpawnPoint = ChosenSpawnPoint
pl:SetVar( "LastSpawnpoint", ChosenSpawnPoint )
return ChosenSpawnPoint
end
end
end
return ChosenSpawnPoint
end
--[[---------------------------------------------------------
Name: gamemode:WeaponEquip( weapon )
Desc: Player just picked up (or was given) weapon
-----------------------------------------------------------]]
function GM:WeaponEquip( weapon )
end
--[[---------------------------------------------------------
Name: gamemode:ScalePlayerDamage( ply, hitgroup, dmginfo )
Desc: Scale the damage based on being shot in a hitbox
Return true to not take damage
-----------------------------------------------------------]]
function GM:ScalePlayerDamage( ply, hitgroup, dmginfo )
-- More damage if we're shot in the head
if ( hitgroup == HITGROUP_HEAD ) then
dmginfo:ScaleDamage( 2 )
end
-- Less damage if we're shot in the arms or legs
if ( hitgroup == HITGROUP_LEFTARM ||
hitgroup == HITGROUP_RIGHTARM ||
hitgroup == HITGROUP_LEFTLEG ||
hitgroup == HITGROUP_RIGHTLEG ||
hitgroup == HITGROUP_GEAR ) then
dmginfo:ScaleDamage( 0.25 )
end
end
--[[---------------------------------------------------------
Name: gamemode:PlayerDeathSound()
Desc: Return true to not play the default sounds
-----------------------------------------------------------]]
function GM:PlayerDeathSound()
return false
end
--[[---------------------------------------------------------
Name: gamemode:SetupPlayerVisibility()
Desc: Add extra positions to the player's PVS
-----------------------------------------------------------]]
function GM:SetupPlayerVisibility( pPlayer, pViewEntity )
--AddOriginToPVS( vector_position_here )
end
--[[---------------------------------------------------------
Name: gamemode:OnDamagedByExplosion( ply, dmginfo)
Desc: Player has been hurt by an explosion
-----------------------------------------------------------]]
function GM:OnDamagedByExplosion( ply, dmginfo )
ply:SetDSP( 35, false )
end
--[[---------------------------------------------------------
Name: gamemode:CanPlayerSuicide( ply )
Desc: Player typed KILL in the console. Can they kill themselves?
-----------------------------------------------------------]]
function GM:CanPlayerSuicide( ply )
return true
end
--[[---------------------------------------------------------
Name: gamemode:CanPlayerEnterVehicle( player, vehicle, role )
Desc: Return true if player can enter vehicle
-----------------------------------------------------------]]
function GM:CanPlayerEnterVehicle( ply, vehicle, role )
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerEnteredVehicle( player, vehicle, role )
Desc: Player entered the vehicle fine
-----------------------------------------------------------]]
function GM:PlayerEnteredVehicle( ply, vehicle, role )
end
--[[---------------------------------------------------------
Name: gamemode:CanExitVehicle()
Desc: If the player is allowed to leave the vehicle, return true
-----------------------------------------------------------]]
function GM:CanExitVehicle( vehicle, passenger )
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerLeaveVehicle()
Desc: Player left the vehicle
-----------------------------------------------------------]]
function GM:PlayerLeaveVehicle( ply, vehicle )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSwitchFlashlight()
Desc: Return true to allow action
-----------------------------------------------------------]]
function GM:PlayerSwitchFlashlight( ply, SwitchOn )
return ply:CanUseFlashlight()
end
--[[---------------------------------------------------------
Name: gamemode:PlayerCanJoinTeam( ply, teamid )
Desc: Allow mods/addons to easily determine whether a player
can join a team or not
-----------------------------------------------------------]]
function GM:PlayerCanJoinTeam( ply, teamid )
local TimeBetweenSwitches = GAMEMODE.SecondsBetweenTeamSwitches or 10
if ( ply.LastTeamSwitch && RealTime()-ply.LastTeamSwitch < TimeBetweenSwitches ) then
ply.LastTeamSwitch = ply.LastTeamSwitch + 1
ply:ChatPrint( Format( "Please wait %i more seconds before trying to change team again", ( TimeBetweenSwitches - ( RealTime() - ply.LastTeamSwitch ) ) + 1 ) )
return false
end
-- Already on this team!
if ( ply:Team() == teamid ) then
ply:ChatPrint( "You're already on that team" )
return false
end
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerRequestTeam()
Desc: Player wants to change team
-----------------------------------------------------------]]
function GM:PlayerRequestTeam( ply, teamid )
-- No changing teams if not teambased!
if ( !GAMEMODE.TeamBased ) then return end
-- This team isn't joinable
if ( !team.Joinable( teamid ) ) then
ply:ChatPrint( "You can't join that team" )
return end
-- This team isn't joinable
if ( !GAMEMODE:PlayerCanJoinTeam( ply, teamid ) ) then
-- Messages here should be outputted by this function
return end
GAMEMODE:PlayerJoinTeam( ply, teamid )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerJoinTeam()
Desc: Make player join this team
-----------------------------------------------------------]]
function GM:PlayerJoinTeam( ply, teamid )
local iOldTeam = ply:Team()
if ( ply:Alive() ) then
if ( iOldTeam == TEAM_SPECTATOR || iOldTeam == TEAM_UNASSIGNED ) then
ply:KillSilent()
else
ply:Kill()
end
end
ply:SetTeam( teamid )
ply.LastTeamSwitch = RealTime()
GAMEMODE:OnPlayerChangedTeam( ply, iOldTeam, teamid )
end
--[[---------------------------------------------------------
Name: gamemode:OnPlayerChangedTeam( ply, oldteam, newteam )
-----------------------------------------------------------]]
function GM:OnPlayerChangedTeam( ply, oldteam, newteam )
-- Here's an immediate respawn thing by default. If you want to
-- re-create something more like CS or some shit you could probably
-- change to a spectator or something while dead.
if ( newteam == TEAM_SPECTATOR ) then
-- If we changed to spectator mode, respawn where we are
local Pos = ply:EyePos()
ply:Spawn()
ply:SetPos( Pos )
elseif ( oldteam == TEAM_SPECTATOR ) then
-- If we're changing from spectator, join the game
ply:Spawn()
else
-- If we're straight up changing teams just hang
-- around until we're ready to respawn onto the
-- team that we chose
end
PrintMessage( HUD_PRINTTALK, Format( "%s joined '%s'", ply:Nick(), team.GetName( newteam ) ) )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerSpray()
Desc: Return true to prevent player spraying
-----------------------------------------------------------]]
function GM:PlayerSpray( ply )
return false
end
--[[---------------------------------------------------------
Name: gamemode:OnPlayerHitGround()
Desc: Return true to disable default action
-----------------------------------------------------------]]
function GM:OnPlayerHitGround( ply, bInWater, bOnFloater, flFallSpeed )
-- Apply damage and play collision sound here
-- then return true to disable the default action
--MsgN( ply, bInWater, bOnFloater, flFallSpeed )
--return true
end
--[[---------------------------------------------------------
Name: gamemode:GetFallDamage()
Desc: return amount of damage to do due to fall
-----------------------------------------------------------]]
local mp_falldamage = GetConVar( "mp_falldamage" )
function GM:GetFallDamage( ply, flFallSpeed )
if ( mp_falldamage:GetBool() ) then -- realistic fall damage is on
return ( flFallSpeed - 526.5 ) * ( 100 / 396 ) -- the Source SDK value
end
return 10
end
--[[---------------------------------------------------------
Name: gamemode:PlayerCanSeePlayersChat()
Desc: Can this player see the other player's chat?
-----------------------------------------------------------]]
function GM:PlayerCanSeePlayersChat( strText, bTeamOnly, pListener, pSpeaker )
if ( bTeamOnly ) then
if ( !IsValid( pSpeaker ) || !IsValid( pListener ) ) then return false end
if ( pListener:Team() != pSpeaker:Team() ) then return false end
end
return true
end
local sv_alltalk = GetConVar( "sv_alltalk" )
--[[---------------------------------------------------------
Name: gamemode:PlayerCanHearPlayersVoice()
Desc: Can this player see the other player's voice?
Returns 2 bools.
1. Can the player hear the other player
2. Can they hear them spacially
-----------------------------------------------------------]]
function GM:PlayerCanHearPlayersVoice( pListener, pTalker )
local alltalk = sv_alltalk:GetInt()
if ( alltalk >= 1 ) then return true, alltalk == 2 end
return pListener:Team() == pTalker:Team(), false
end
--[[---------------------------------------------------------
Name: gamemode:NetworkIDValidated()
Desc: Called when Steam has validated this as a valid player
-----------------------------------------------------------]]
function GM:NetworkIDValidated( name, steamid )
-- MsgN( "GM:NetworkIDValidated", name, steamid )
end
--[[---------------------------------------------------------
Name: gamemode:PlayerShouldTaunt( ply, actid )
-----------------------------------------------------------]]
function GM:PlayerShouldTaunt( ply, actid )
-- The default behaviour is to always let them act
-- Some gamemodes will obviously want to stop this for certain players by returning false
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerStartTaunt( ply, actid, length )
-----------------------------------------------------------]]
function GM:PlayerStartTaunt( ply, actid, length )
end
--[[---------------------------------------------------------
Name: gamemode:AllowPlayerPickup( ply, object )
-----------------------------------------------------------]]
function GM:AllowPlayerPickup( ply, object )
-- Should the player be allowed to pick this object up (using ENTER)?
-- If no then return false. Default is HELL YEAH
return true
end
--[[---------------------------------------------------------
Name: gamemode:PlayerDroppedWeapon()
Desc: Player has dropped a weapon
-----------------------------------------------------------]]
function GM:PlayerDroppedWeapon( ply, weapon )
end
--[[---------------------------------------------------------
These are buttons that the client is pressing. They're used
in Sandbox mode to control things like wheels, thrusters etc.
-----------------------------------------------------------]]
function GM:PlayerButtonDown( ply, btn ) end
function GM:PlayerButtonUp( ply, btn ) end
concommand.Add( "changeteam", function( pl, cmd, args ) hook.Call( "PlayerRequestTeam", GAMEMODE, pl, tonumber( args[ 1 ] ) ) end )
|
local RunService = game:GetService('RunService')
local isDev = RunService:IsStudio()
local GlobalConfig = {
WAIT_TIME = isDev and 4 or 20,
afterFinishWaitTime = 10,
refreshLeaderboards = 5 * 60,
DEFAULT_PLAYER_SLOTS = 3,
DEFAULT_PLAYER_COINS = 100,
DEFAULT_PLAYER_INVENTORY = {},
}
return GlobalConfig |
local cv = require 'cv._env'
local ffi = require 'ffi'
ffi.cdef[[
struct TensorWrapper inpaint(struct TensorWrapper src, struct TensorWrapper inpaintMask,
struct TensorWrapper dst, double inpaintRadius, int flags);
struct TensorWrapper fastNlMeansDenoising1(struct TensorWrapper src, struct TensorWrapper dst,
float h, int templateWindowSize,
int searchWindowSize);
struct TensorWrapper fastNlMeansDenoising2(struct TensorWrapper src, struct TensorWrapper dst,
struct TensorWrapper h, int templateWindowSize,
int searchWindowSize, int normType);
struct TensorWrapper fastNlMeansDenoisingColored(struct TensorWrapper src, struct TensorWrapper dst,
float h, float hColor, int templateWindowSize, int searchWindowSize);
struct TensorWrapper fastNlMeansDenoisingMulti1(struct TensorArray srcImgs, struct TensorWrapper dst,
int imgToDenoiseIndex, int temporalWindowSize, float h,
int templateWindowSize, int searchWindowSize);
struct TensorWrapper fastNlMeansDenoisingMulti2(struct TensorArray srcImgs, struct TensorWrapper dst,
int imgToDenoiseIndex, int temporalWindowSize, struct TensorWrapper h,
int templateWindowSize, int searchWindowSize, int normType);
struct TensorWrapper fastNlMeansDenoisingColoredMulti(struct TensorArray srcImgs, struct TensorWrapper dst,
int imgToDenoiseIndex, int temporalWindowSize, float h,
float hColor, int templateWindowSize, int searchWindowSize);
struct TensorWrapper denoise_TVL1(struct TensorArray observations, struct TensorWrapper result,
double lambda, int niters);
struct TensorWrapper decolor(struct TensorWrapper src, struct TensorWrapper grayscale,
struct TensorWrapper color_boost);
struct TensorWrapper seamlessClone(struct TensorWrapper src, struct TensorWrapper dst,
struct TensorWrapper mask, struct PointWrapper p,
struct TensorWrapper blend, int flags);
struct TensorWrapper colorChange(struct TensorWrapper src, struct TensorWrapper mask,
struct TensorWrapper dst, float red_mul,
float green_mul, float blue_mul);
struct TensorWrapper illuminationChange(struct TensorWrapper src, struct TensorWrapper mask,
struct TensorWrapper dst, float alpha, float beta);
struct TensorWrapper textureFlattening(struct TensorWrapper src, struct TensorWrapper mask,
struct TensorWrapper dst, float low_threshold, float high_threshold,
int kernel_size);
struct TensorWrapper edgePreservingFilter(struct TensorWrapper src, struct TensorWrapper dst,
int flags, float sigma_s, float sigma_r);
struct TensorWrapper detailEnhance(struct TensorWrapper src, struct TensorWrapper dst,
float sigma_s, float sigma_r);
struct TensorWrapper pencilSketch(struct TensorWrapper src, struct TensorWrapper dst1,
struct TensorWrapper dst2, float sigma_s, float sigma_r, float shade_factor);
struct TensorWrapper stylization(struct TensorWrapper src, struct TensorWrapper dst,
float sigma_s, float sigma_r);
]]
local C = ffi.load(cv.libPath('photo'))
function cv.inpaint(t)
local argRules = {
{"src", required = true},
{"inpaintMask", required = true},
{"dst", default = nil},
{"inpaintRadius", required = true},
{"flags", required = true}
}
local src, inpaintMask, dst, inpaintRadius, flags = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.inpaint(
cv.wrap_tensor(src), cv.wrap_tensor(inpaintMask), cv.wrap_tensor(dst), inpaintRadius, flags))
end
function cv.fastNlMeansDenoising(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"h", default = nil},
{"templateWindowSize", default = 7},
{"searchWindowSize", default = 21},
{"normType", default = cv.NORM_L2}
}
local src, dst, h, templateWindowSize, searchWindowSize, h, normType = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
assert(templateWindowSize % 2 == 1)
if type(h) == "number" or h == nil then
h = h or 3
return cv.unwrap_tensors(
C.fastNlMeansDenoising1(
cv.wrap_tensor(src), cv.wrap_tensor(dst), h, templateWindowSize, searchWindowSize))
end
if type(h) == "table" then
h = torch.FloatTensor(h)
end
return cv.unwrap_tensors(
C.fastNlMeansDenoising2(
cv.wrap_tensor(src), cv.wrap_tensor(dst), cv.wrap_tensor(h),
templateWindowSize, searchWindowSize, normType))
end
function cv.fastNlMeansDenoisingColored(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"h", default = 3},
{"hColor", default = 3},
{"templateWindowSize", default = 7},
{"searchWindowSize", default = 21}
}
local src, dst, h, hColor, templateWindowSize, searchWindowSize = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
assert(templateWindowSize % 2 == 1)
assert(searchWindowSize % 2 == 1)
return cv.unwrap_tensors(
C.fastNlMeansDenoisingColored(
cv.wrap_tensor(src), cv.wrap_tensor(dst), h, hColor, templateWindowSize, searchWindowSize))
end
function cv.fastNlMeansDenoisingMulti(t)
local argRules = {
{"srcImgs", required = true},
{"dst", default = nil},
{"imgToDenoiseIndex", required = true},
{"temporalWindowSize", required = true},
{"h", default = nil},
{"templateWindowSize", default = 7},
{"searchWindowSize", default = 21},
{"normType", default = cv.NORM_L2}
}
local srcImgs, dst, imgToDenoiseIndex, temporalWindowSize, h, templateWindowSize, searchWindowSize, h, normType = cv.argcheck(t, argRules)
if #srcImgs > 1 then
for i = 2, #srcImgs do
assert(srcImgs[i - 1]:type() == srcImgs[i]:type() and srcImgs[i - 1]:isSameSizeAs(srcImgs[i]))
end
end
if dst then
assert(dst:type() == srcImgs[1]:type() and srcImgs[1]:isSameSizeAs(dst))
end
assert(temporalWindowSize % 2 == 1)
assert(templateWindowSize % 2 == 1)
assert(searchWindowSize % 2 == 1)
-- h is a single number
if type(h) == "number" or h == nil then
h = h or 3
return cv.unwrap_tensors(
C.fastNlMeansDenoisingMulti1(
cv.wrap_tensors(srcImgs), cv.wrap_tensor(dst), imgToDenoiseIndex, temporalWindowSize,
h, templateWindowSize, searchWindowSize))
end
-- h is a vector
if type(h) == "table" then
h = torch.FloatTensor(h)
end
return cv.unwrap_tensors(
C.fastNlMeansDenoisingMulti2(
cv.wrap_tensors(srcImgs), cv.wrap_tensor(dst), imgToDenoiseIndex, temporalWindowSize,
cv.wrap_tensor(h), templateWindowSize, searchWindowSize, normType))
end
function cv.fastNlMeansDenoisingColoredMulti(t)
local argRules = {
{"srcImgs", required = true},
{"dst", default = nil},
{"imgToDenoiseIndex", required = true},
{"temporalWindowSize", required = true},
{"h", default = 3},
{"hColor", default = 3},
{"templateWindowSize", default = 7},
{"searchWindowSize", default = 21}
}
local srcImgs, dst, imgToDenoiseIndex, temporalWindowSize, h, hColor, templateWindowSize, searchWindowSize = cv.argcheck(t, argRules)
if #srcImgs > 1 then
for i = 2, #srcImgs do
assert(srcImgs[i - 1]:type() == srcImgs[i]:type() and srcImgs[i - 1]:isSameSizeAs(srcImgs[i]))
end
end
if dst then
assert(dst:type() == srcImgs[1]:type() and srcImgs[1]:isSameSizeAs(dst))
end
assert(temporalWindowSize % 2 == 1)
assert(templateWindowSize % 2 == 1)
assert(searchWindowSize % 2 == 1)
return cv.unwrap_tensors(
C.fastNlMeansDenoisingColoredMulti(
cv.wrap_tensors(srcImgs), cv.wrap_tensor(dst), imgToDenoiseIndex, temporalWindowSize,
h, hColor, templateWindowSize, searchWindowSize))
end
function cv.denoise_TVL1(t)
local argRules = {
{"observations", required = true},
{"result", default = nil},
{"lambda", default = 1.0},
{"niters", default = 30}
}
local observations, result, lambda, niters = cv.argcheck(t, argRules)
return cv.unwrap_tensors(
C.denoise_TVL1(
cv.wrap_tensors(observations), cv.wrap_tensor(result), lambda, niters))
end
function cv.decolor(t)
local argRules = {
{"src", required = true},
{"grayscale", default = nil},
{"color_boost", required = true}
}
local src, grayscale, color_boost = cv.argcheck(t, argRules)
return cv.unwrap_tensors(
C.decolor(
cv.wrap_tensor(src), cv.wrap_tensor(grayscale), cv.wrap_tensor(color_boost)))
end
function cv.seamlessClone(t)
local argRules = {
{"src", required = true},
{"dst", required = true},
{"mask", required = true},
{"p", required = true, operator = cv.Point},
{"blend", default = nil},
{"flags", required = true}
}
local src, dst, mask, p, blend, flags = cv.argcheck(t, argRules)
if blend then
assert(blend:type() == dst:type() and dst:isSameSizeAs(blend))
end
return cv.unwrap_tensors(
C.seamlessClone(
cv.wrap_tensor(src), cv.wrap_tensor(dst), cv.wrap_tensor(mask),
p, cv.wrap_tensor(blend), flags))
end
function cv.colorChange(t)
local argRules = {
{"src", required = true},
{"mask", required = true},
{"dst", default = nil},
{"red_mul", default = 1.0},
{"green_mul", default = 1.0},
{"blue_mul", default = 1.0}
}
local src, mask, dst, red_mul, green_mul, blue_mul = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.colorChange(
cv.wrap_tensor(src), cv.wrap_tensor(mask), cv.wrap_tensor(dst),
red_mul, green_mul, blue_mul))
end
function cv.illuminationChange(t)
local argRules = {
{"src", required = true},
{"mask", required = true},
{"dst", default = nil},
{"alpha", default = 0.2},
{"beta", default = 0.4}
}
local src, mask, dst, alpha, beta = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.illuminationChange(
cv.wrap_tensor(src), cv.wrap_tensor(mask), cv.wrap_tensor(dst),
alpha, beta))
end
function cv.textureFlattening(t)
local argRules = {
{"src", required = true},
{"mask", required = true},
{"dst", default = nil},
{"low_threshold", default = 30},
{"high_threshold", default = 45},
{"kernel_size", default = 3}
}
local src, mask, dst, low_threshold, high_threshold, kernel_size = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.textureFlattening(
cv.wrap_tensor(src), cv.wrap_tensor(mask), cv.wrap_tensor(dst),
low_threshold, high_threshold, kernel_size))
end
function cv.edgePreservingFilter(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"flags", default = 1},
{"sigma_s", default = 60},
{"sigma_r", default = 0.4}
}
local src, dst, flags, sigma_s, sigma_r = cv.argcheck(t, argRules)
return cv.unwrap_tensors(
C.edgePreservingFilter(
cv.wrap_tensor(src), cv.wrap_tensor(dst), flags, sigma_s, sigma_r))
end
function cv.detailEnhance(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"sigma_s", default = 10},
{"sigma_r", default = 0.15}
}
local src, dst, sigma_s, sigma_r = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.detailEnhance(
cv.wrap_tensor(src), cv.wrap_tensor(dst), sigma_s, sigma_r))
end
function cv.pencilSketch(t)
local argRules = {
{"src", required = true},
{"dst1", default = nil},
{"dst2", default = nil},
{"sigma_s", default = 60},
{"sigma_r", default = 0.07},
{"shade_factor", default = 0.02}
}
local src, dst1, dst2, sigma_s, sigma_r, shade_factor = cv.argcheck(t, argRules)
if dst2 then
assert(dst2:type() == src:type() and src:isSameSizeAs(dst2))
end
return cv.unwrap_tensors(
C.pencilSketch(
cv.wrap_tensor(src), cv.wrap_tensor(dst1), cv.wrap_tensor(dst2),
sigma_s, sigma_r, shade_factor))
end
function cv.stylization(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"sigma_s", default = 60},
{"sigma_r", default = 0.45}
}
local src, dst, sigma_s, sigma_r = cv.argcheck(t, argRules)
if dst then
assert(dst:type() == src:type() and src:isSameSizeAs(dst))
end
return cv.unwrap_tensors(
C.stylization(
cv.wrap_tensor(src), cv.wrap_tensor(dst), sigma_s, sigma_r))
end
--- ***************** Classes *****************
require 'cv.Classes'
local Classes = ffi.load(cv.libPath('Classes'))
ffi.cdef[[
struct PtrWrapper Tonemap_ctor(float gamma);
struct TensorWrapper Tonemap_process(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst);
float Tonemap_getGamma(struct PtrWrapper ptr);
void Tonemap_setGamma(struct PtrWrapper ptr, float gamma);
struct PtrWrapper TonemapDrago_ctor(float gamma, float saturation, float bias);
float TonemapDrago_getSaturation(struct PtrWrapper ptr);
void TonemapDrago_setSaturation(struct PtrWrapper ptr, float saturation);
float TonemapDrago_getBias(struct PtrWrapper ptr);
void TonemapDrago_setBias(struct PtrWrapper ptr, float bias);
struct PtrWrapper TonemapDurand_ctor(float gamma, float contrast, float saturation, float sigma_space, float sigma_color);
float TonemapDurand_getSaturation(struct PtrWrapper ptr);
void TonemapDurand_setSaturation(struct PtrWrapper ptr, float Saturation);
float TonemapDurand_getContrast(struct PtrWrapper ptr);
void TonemapDurand_setContrast(struct PtrWrapper ptr, float contrast);
float TonemapDurand_getSigmaSpace(struct PtrWrapper ptr);
void TonemapDurand_setSigmaSpace(struct PtrWrapper ptr, float sigma_space);
float TonemapDurand_getSigmaColor(struct PtrWrapper ptr);
void TonemapDurand_setSigmaColor(struct PtrWrapper ptr, float sigma_color);
struct PtrWrapper TonemapReinhard_ctor(float gamma, float intensity, float light_adapt, float color_adapt);
float TonemapReinhard_getIntensity(struct PtrWrapper ptr);
void TonemapReinhard_setIntensity(struct PtrWrapper ptr, float intensity);
float TonemapReinhard_getLightAdaptation(struct PtrWrapper ptr);
void TonemapReinhard_setLightAdaptation(struct PtrWrapper ptr, float light_adapt);
float TonemapReinhard_getColorAdaptation(struct PtrWrapper ptr);
void TonemapReinhard_setColorAdaptation(struct PtrWrapper ptr, float color_adapt);
struct PtrWrapper TonemapMantiuk_ctor(float gamma, float scale, float saturation);
float TonemapMantiuk_getScale(struct PtrWrapper ptr);
void TonemapMantiuk_setScale(struct PtrWrapper ptr, float scale);
float TonemapMantiuk_getSaturation(struct PtrWrapper ptr);
void TonemapMantiuk_setSaturation(struct PtrWrapper ptr, float saturation);
struct TensorArray AlignExposures_process(struct PtrWrapper ptr, struct TensorArray src, struct TensorArray dst,
struct TensorWrapper times, struct TensorWrapper response);
struct PtrWrapper AlignMTB_ctor(int max_bits, int exclude_range, bool cut);
struct TensorArray AlignMTB_process1(struct PtrWrapper ptr, struct TensorArray src, struct TensorArray dst,
struct TensorWrapper times, struct TensorWrapper response);
struct TensorArray AlignMTB_process2(struct PtrWrapper ptr, struct TensorArray src, struct TensorArray dst);
struct PointWrapper AlignMTB_calculateShift(struct PtrWrapper ptr, struct TensorWrapper img0, struct TensorWrapper img1);
struct TensorWrapper AlignMTB_shiftMat(struct PtrWrapper ptr, struct TensorWrapper src,
struct TensorWrapper dst, struct PointWrapper shift);
void AlignMTB_computeBitmaps(struct PtrWrapper ptr, struct TensorWrapper img, struct TensorWrapper tb, struct TensorWrapper eb);
int AlignMTB_getMaxBits(struct PtrWrapper ptr);
void AlignMTB_setMaxBits(struct PtrWrapper ptr, int max_bits);
int AlignMTB_getExcludeRange(struct PtrWrapper ptr);
void AlignMTB_setExcludeRange(struct PtrWrapper ptr, int exclude_range);
int AlignMTB_getCut(struct PtrWrapper ptr);
void AlignMTB_setCut(struct PtrWrapper ptr, bool cut);
struct TensorWrapper CalibrateCRF_process(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times);
struct PtrWrapper CalibrateDebevec_ctor(int samples, float lambda, bool random);
float CalibrateDebevec_getLambda(struct PtrWrapper ptr);
void CalibrateDebevec_setLambda(struct PtrWrapper ptr, float lambda);
int CalibrateDebevec_getSamples(struct PtrWrapper ptr);
void CalibrateDebevec_setSamples(struct PtrWrapper ptr, int samples);
bool CalibrateDebevec_getRandom(struct PtrWrapper ptr);
void CalibrateDebevec_setRandom(struct PtrWrapper ptr, bool random);
struct PtrWrapper CalibrateRobertson_ctor(int max_iter, float threshold);
int CalibrateRobertson_getMaxIter(struct PtrWrapper ptr);
void CalibrateRobertson_setMaxIter(struct PtrWrapper ptr, int max_iter);
float CalibrateRobertson_getThreshold(struct PtrWrapper ptr);
void CalibrateRobertson_setThreshold(struct PtrWrapper ptr, float threshold);
struct TensorWrapper CalibrateRobertson_getRadiance(struct PtrWrapper ptr);
struct TensorWrapper MergeExposures_process(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times, struct TensorWrapper response);
struct PtrWrapper MergeDebevec_ctor();
struct TensorWrapper MergeDebevec_process1(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times, struct TensorWrapper response);
struct TensorWrapper MergeDebevec_process2(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times);
struct PtrWrapper MergeMertens_ctor(float contrast_weight, float saturation_weight, float exposure_weight);
struct TensorWrapper MergeMertens_process1(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times, struct TensorWrapper response);
struct TensorWrapper MergeMertens_process2(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst);
float MergeMertens_getContrastWeight(struct PtrWrapper ptr);
void MergeMertens_setContrastWeight(struct PtrWrapper ptr, float contrast_weight);
float MergeMertens_getSaturationWeight(struct PtrWrapper ptr);
void MergeMertens_setSaturationWeight(struct PtrWrapper ptr, float saturation_weight);
float MergeMertens_getExposureWeight(struct PtrWrapper ptr);
void MergeMertens_setExposureWeight(struct PtrWrapper ptr, float exposure_weight);
struct PtrWrapper MergeRobertson_ctor();
struct TensorWrapper MergeRobertson_process1(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times, struct TensorWrapper response);
struct TensorWrapper MergeRobertson_process2(struct PtrWrapper ptr, struct TensorArray src, struct TensorWrapper dst,
struct TensorWrapper times);
]]
-- Tonemap
do
local Tonemap = torch.class('cv.Tonemap', 'cv.Algorithm', cv)
function Tonemap:__init(t)
local argRules = {
{"gamma", default = 1.0}
}
local gamma = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.Tonemap_ctor(gamma), Classes.Algorithm_dtor)
end
function Tonemap:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil}
}
local src, dst = cv.argcheck(t, argRules)
return C.Tonemap_process(self.ptr, cv.wrap_tensor(src), cv.wrap_tensor(dst));
end
function Tonemap:getGamma()
return C.Tonemap_getGamma(self.ptr);
end
function Tonemap:setGamma(t)
local argRules = {
{"gamma", required = true}
}
local gamma = cv.argcheck(t, argRules)
C.Tonemap_setGamma(self.ptr, gamma)
end
end
-- TonemapDrago
do
local TonemapDrago = torch.class('cv.TonemapDrago', 'cv.Tonemap', cv)
function TonemapDrago:__init(t)
local argRules = {
{"gamma", default = 1.0},
{"saturation", default = 1.0},
{"bias", default = 0.85}
}
local gamma, saturation, bias = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.TonemapDrago_ctor(gamma, saturation, bias), Classes.Algorithm_dtor)
end
function TonemapDrago:getSaturation()
return C.TonemapDrago_getSaturation(self.ptr);
end
function TonemapDrago:setSaturation(t)
local argRules = {
{"saturation", required = true}
}
local saturation = cv.argcheck(t, argRules)
C.TonemapDrago_setSaturation(self.ptr, saturation)
end
function TonemapDrago:getBias()
return C.TonemapDrago_getBias(self.ptr);
end
function TonemapDrago:setBias(t)
local argRules = {
{"bias", required = true}
}
local bias = cv.argcheck(t, argRules)
C.TonemapDrago_setBias(self.ptr, bias)
end
end
-- TonemapDurand
do
local TonemapDurand = torch.class('cv.TonemapDurand', 'cv.Tonemap', cv);
function TonemapDurand:__init(t)
local argRules = {
{"gamma", default = 1.0},
{"contrast", default = 4.0},
{"saturation", default = 1.0},
{"sigma_space", default = 2.0},
{"sigma_color", default = 2.0}
}
local gamma, contrast, saturation, sigma_space, sigma_color = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.TonemapDurand_ctor(gamma, contrast, saturation, sigma_space, sigma_color), Classes.Algorithm_dtor)
end
function TonemapDurand:getSaturation()
return C.TonemapDurand_getSaturation(self.ptr)
end
function TonemapDurand:setSaturation(t)
local argRules = {
{"saturation", required = true}
}
local saturation = cv.argcheck(t, argRules)
C.TonemapDurand_setSaturation(self.ptr, saturation)
end
function TonemapDurand:getConstant()
return C.TonemapDurand_getConstant(self.ptr)
end
function TonemapDurand:setConstant(t)
local argRules = {
{"Constant", required = true}
}
local Constant = cv.argcheck(t, argRules)
C.TonemapDurand_setConstant(self.ptr, Constant)
end
function TonemapDurand:getSigmaSpace()
return C.TonemapDurand_getSigmaSpace(self.ptr)
end
function TonemapDurand:setSigmaSpace(t)
local argRules = {
{"sigma_space", required = true}
}
local sigma_space = cv.argcheck(t, argRules)
C.TonemapDurand_setSigmaSpace(self.ptr, sigma_space)
end
function TonemapDurand:getSigmaColor()
return C.TonemapDurand_getSigmaColor(self.ptr)
end
function TonemapDurand:setSigmaColor(t)
local argRules = {
{"sigma_color", required = true}
}
local sigma_color = cv.argcheck(t, argRules)
C.TonemapDurand_setSigmaColor(self.ptr, sigma_color)
end
end
-- TonemapReinhard
do
local TonemapReinhard = torch.class('cv.TonemapReinhard', 'cv.Tonemap', cv);
function TonemapReinhard:__init(t)
local argRules = {
{"gamma", default = 1.0},
{"intensity", default = 0.0},
{"light_adapt", default = 1.0},
{"sigma_space", default = 2.0},
{"sigma_color", default = 2.0}
}
local gamma, intensity, light_adapt, color_adapt = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.TonemapReinhard_ctor(gamma, intensity, light_adapt, color_adapt), Classes.Algorithm_dtor)
end
function TonemapReinhard:getIntensity()
return C.TonemapReinhard_getIntensity(self.ptr)
end
function TonemapReinhard:setIntensity(t)
local argRules = {
{"intensity", required = true}
}
local intensity = cv.argcheck(t, argRules)
C.TonemapReinhard_setIntensity(self.ptr, intensity)
end
function TonemapReinhard:getLightAdaptation()
return C.TonemapReinhard_getLightAdaptation(self.ptr)
end
function TonemapReinhard:setLightAdaptation(t)
local argRules = {
{"light_adapt", required = true}
}
local light_adapt = cv.argcheck(t, argRules)
C.TonemapReinhard_setLightAdaptation(self.ptr, light_adapt)
end
function TonemapReinhard:getColorAdaptation()
return C.TonemapReinhard_getColorAdaptation(self.ptr)
end
function TonemapReinhard:setColorAdaptation(t)
local argRules = {
{"color_adapt", required = true}
}
local color_adapt = cv.argcheck(t, argRules)
C.TonemapReinhard_setColorAdaptation(self.ptr, color_adapt)
end
end
-- TonemapMantiuk
do
local TonemapMantiuk = torch.class('cv.TonemapMantiuk', 'cv.Tonemap', cv);
function TonemapMantiuk:__init(t)
local argRules = {
{"gamma", default = 1.0},
{"scale", default = 0.7},
{"saturation", default = 1.0}
}
local gamma, scale, saturation = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.TonemapMantiuk_ctor(gamma, scale, saturation), Classes.Algorithm_dtor)
end
function TonemapMantiuk:getScale()
return C.TonemapMantiuk_getScale(self.ptr)
end
function TonemapMantiuk:setScale(t)
local argRules = {
{"scale", required = true}
}
local scale = cv.argcheck(t, argRules)
C.TonemapMantiuk_setScale(self.ptr, scale)
end
function TonemapMantiuk:getSaturation()
return C.TonemapMantiuk_getSaturation(self.ptr)
end
function TonemapMantiuk:setSaturation(t)
local argRules = {
{"saturation", required = true}
}
local saturation = cv.argcheck(t, argRules)
C.TonemapMantiuk_setSaturation(self.ptr, saturation)
end
end
-- AlignExposures
do
local AlignExposures = torch.class('cv.AlignExposures', 'cv.Algorithm', cv)
function AlignExposures:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", required = true},
{"response", required = true}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if type(times) == "table" then
times = torch.FloatTensor(times)
end
return cv.unwrap_tensors(
C.AlignExposures_process(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensors(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
end
-- AlignMTB
do
local AlignMTB = torch.class('cv.AlignMTB', 'cv.AlignExposures', cv)
function AlignMTB:__init(t)
local argRules = {
{"max_bits", default = 6},
{"exclude_range", default = 4},
{"cut", default = true}
}
local max_bits, exclude_range, cut = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.AlignMTB_ctor(max_bits, exclude_range, cut), Classes.Algorithm_dtor)
end
function AlignMTB:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", default = nil},
{"response", default = nil}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if times == nil then
return cv.unwrap_tensors(
C.AlignMTB_process2(self.ptr, cv.wrap_tensors(src), cv.wrap_tensors(dst)))
end
if type(times) == "table" then
times = torch.FloatTensor(times)
end
return cv.unwrap_tensors(
C.AlignMTB_process1(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensors(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
function AlignMTB:calculateShift(t)
local argRules = {
{"img0", required = true},
{"img1", required = true}
}
local img0, img1 = cv.argcheck(t, argRules)
resPoint = C.AlignMTB_calculateShift(self.ptr, cv.wrap_tensor(img0), cv.wrap_tensor(img1))
return {resPoint.x, resPoint.y}
end
function AlignMTB:shiftMat(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"shift", required = true, operator = cv.Point}
}
local src, dst, shift = cv.argcheck(t, argRules)
return cv.unwrap_tensors(
C.AlignMTB_shiftMat(self.ptr, cv.wrap_tensor(src), cv.wrap_tensor(dst), shift))
end
function AlignMTB:computeBitmaps(t)
local argRules = {
{"img", required = true},
{"tb", required = true},
{"eb", required = true}
}
local img, tb, eb = cv.argcheck(t, argRules)
return cv.unwrap_tensors(
C.AlignMTB_computeBitmaps(self.ptr, cv.wrap_tensor(img), cv.wrap_tensor(tb), cv.wrap_tensor(eb)))
end
function AlignMTB:getMaxBits()
return C.AlignMTB_getMaxBits(self.ptr)
end
function AlignMTB:setMaxBits(t)
local argRules = {
{"max_bits", required = true}
}
local max_bits = cv.argcheck(t, argRules)
C.AlignMTB_setMaxBits(self.ptr, max_bits)
end
function AlignMTB:getExcludeRange()
return C.AlignMTB_getExcludeRange(self.ptr)
end
function AlignMTB:setExcludeRange(t)
local argRules = {
{"exclude_range", required = true}
}
local exclude_range = cv.argcheck(t, argRules)
C.AlignMTB_setExcludeRange(self.ptr, exclude_range)
end
function AlignMTB:getCut()
return C.AlignMTB_getCut(self.ptr)
end
function AlignMTB:setCut(t)
local argRules = {
{"cut", required = true}
}
local cut = cv.argcheck(t, argRules)
C.AlignMTB_setCut(self.ptr, cut)
end
end
-- CalibrateCRF
do
local CalibrateCRF = torch.class('cv.CalibrateCRF', 'cv.Algorithm', cv)
function CalibrateCRF:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", required = true}
}
local src, dst, times = cv.argcheck(t, argRules)
if type(times) == "table" then
times = torch.FloatTensor(times)
end
return cv.unwrap_tensors(
C.CalibrateCRF_process(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst), cv.wrap_tensor(times)))
end
end
-- CalibrateDebevec
do
local CalibrateDebevec = torch.class('cv.CalibrateDebevec', 'cv.CalibrateCRF', cv)
function CalibrateDebevec:__init(t)
local argRules = {
{"samples", default = 70},
{"lambda", default = 10.0},
{"random", default = false}
}
local samples, lambda, random = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.CalibrateDebevec_ctor(samples, lambda, random), Classes.Algorithm_dtor)
end
function CalibrateDebevec:getLambda()
return C.CalibrateDebevec_getLambda(self.ptr)
end
function CalibrateDebevec:setLambda(t)
local argRules = {
{"lambda", required = true}
}
local lambda = cv.argcheck(t, argRules)
C.CalibrateDebevec_setLambda(self.ptr, lambda)
end
function CalibrateDebevec:getSamples()
return C.CalibrateDebevec_getSamples(self.ptr)
end
function CalibrateDebevec:setSamples(t)
local argRules = {
{"samples", required = true}
}
local samples = cv.argcheck(t, argRules)
C.CalibrateDebevec_setSamples(self.ptr, samples)
end
function CalibrateDebevec:getRandom()
return C.CalibrateDebevec_getRandom(self.ptr)
end
function CalibrateDebevec:setRandom(t)
local argRules = {
{"random", required = true}
}
local random = cv.argcheck(t, argRules)
C.CalibrateDebevec_setRandom(self.ptr, random)
end
end
-- CalibrateRobertson
do
local CalibrateRobertson = torch.class('cv.CalibrateRobertson', 'cv.CalibrateCRF', cv)
function CalibrateRobertson:__init(t)
local argRules = {
{"max_iter", default = 30},
{"threshold", default = 0.01}
}
local max_iter, threshold = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.CalibrateRobertson_ctor(max_iter, threshold), Classes.Algorithm_dtor)
end
function CalibrateRobertson:getMaxIter()
return C.CalibrateRobertson_getMaxIter(self.ptr)
end
function CalibrateRobertson:setMaxIter(t)
local argRules = {
{"max_iter", required = true}
}
local max_iter = cv.argcheck(t, argRules)
C.CalibrateRobertson_setMaxIter(self.ptr, max_iter)
end
function CalibrateRobertson:getThreshold()
return C.CalibrateRobertson_getThreshold(self.ptr)
end
function CalibrateRobertson:setThreshold(t)
local argRules = {
{"threshold", required = true}
}
local threshold = cv.argcheck(t, argRules)
C.CalibrateRobertson_setThreshold(self.ptr, threshold)
end
function CalibrateRobertson:getRadiance()
return cv.unwrap_tensors(C.CalibrateRobertson_getRadiance(self.ptr))
end
end
-- MergeExposures
do
local MergeExposures = torch.class('cv.MergeExposures', 'cv.Algorithm', cv)
function MergeExposures:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", required = true},
{"response", required = true}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if type(times) == "table" then
times = torch.FloatTensor(times)
end
return cv.unwrap_tensors(
C.MergeExposures_process(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
end
-- MergeDebevec
do
local MergeDebevec = torch.class('cv.MergeDebevec', 'cv.MergeExposures', cv)
function MergeDebevec:__init(t)
self.ptr = ffi.gc(C.MergeDebevec_ctor(), Classes.Algorithm_dtor)
end
function MergeDebevec:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", required = true},
{"response", default = nil}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if type(times) == "table" then
times = torch.FloatTensor(times)
end
if response == nil then
return cv.unwrap_tensors(
C.MergeDebevec_process2(self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst), cv.wrap_tensor(times)))
end
return cv.unwrap_tensors(
C.MergeDebevec_process1(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
end
-- MergeMertens
do
local MergeMertens = torch.class('cv.MergeMertens', 'cv.MergeExposures', cv)
function MergeMertens:__init(t)
local argRules = {
{"contrast_weight", default = 1.0},
{"saturation_weight", default = 1.0},
{"exposure_weight", default = 0.0}
}
local contrast_weight, saturation_weight, exposure_weight = cv.argcheck(t, argRules)
self.ptr = ffi.gc(C.MergeMertens_ctor(contrast_weight, saturation_weight, exposure_weight), Classes.Algorithm_dtor)
end
function MergeMertens:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", default = nil},
{"response", default = nil}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if times == nil then
return cv.unwrap_tensors(
C.MergeMertens_process2(self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst)))
end
if type(times) == "table" then
times = torch.FloatTensor(times)
end
return cv.unwrap_tensors(
C.MergeMertens_process1(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
function MergeMertens:getContrastWeight()
return C.MergeMertens_getContrastWeight(self.ptr)
end
function MergeMertens:setContrastWeight(t)
local argRules = {
{"contrast_weight", required = true}
}
local contrast_weight = cv.argcheck(t, argRules)
C.MergeMertens_setContrastWeight(self.ptr, contrast_weight)
end
function MergeMertens:getSaturationWeight()
return C.MergeMertens_getSaturationWeight(self.ptr)
end
function MergeMertens:setSaturationWeight(t)
local argRules = {
{"saturation_weight", required = true}
}
local saturation_weight = cv.argcheck(t, argRules)
C.MergeMertens_setSaturationWeight(self.ptr, saturation_weight)
end
function MergeMertens:getExposureWeight()
return C.MergeMertens_getExposureWeight(self.ptr)
end
function MergeMertens:setExposureWeight(t)
local argRules = {
{"exposure_weight", required = true}
}
local exposure_weight = cv.argcheck(t, argRules)
C.MergeMertens_setExposureWeight(self.ptr, exposure_weight)
end
end
-- MergeRobertson
do
local MergeRobertson = torch.class('cv.MergeRobertson', 'cv.MergeExposures', cv)
function MergeRobertson:__init(t)
self.ptr = ffi.gc(C.MergeRobertson_ctor(), Classes.Algorithm_dtor)
end
function MergeRobertson:process(t)
local argRules = {
{"src", required = true},
{"dst", default = nil},
{"times", required = true},
{"response", default = nil}
}
local src, dst, times, response = cv.argcheck(t, argRules)
if type(times) == "table" then
times = torch.FloatTensor(times)
end
if response == nil then
return cv.unwrap_tensors(
C.MergeRobertson_process2(self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst), cv.wrap_tensor(times)))
end
return cv.unwrap_tensors(
C.MergeRobertson_process1(
self.ptr, cv.wrap_tensors(src), cv.wrap_tensor(dst),
cv.wrap_tensor(times), cv.wrap_tensor(response)))
end
end
return cv
|
local function AutoFile(msg)
local text = msg.content_.text_
if Sudo(msg) then
if text == 'تفعيل النسخه التلقائيه' or text == 'تفعيل جلب نسخه الكروبات' or text == 'تفعيل عمل نسخه للمجموعات' then
Dev_Aek(msg.chat_id_,msg.id_, 1, "♕︙تم تفعيل جلب نسخة الكروبات التلقائيه\n♕︙سيتم ارسال نسخه تلقائيه للكروبات كل يوم الى خاص المطور الاساسي", 1, 'md')
DevAek:del(AEK.."Aek:Lock:AutoFile")
end
if text == 'تعطيل النسخه التلقائيه' or text == 'تعطيل جلب نسخه الكروبات' or text == 'تعطيل عمل نسخه للمجموعات' then
Dev_Aek(msg.chat_id_,msg.id_, 1, "♕︙تم تعطيل جلب نسخة الكروبات التلقائيه", 1, 'md')
DevAek:set(AEK.."Aek:Lock:AutoFile",true)
end
end
if (text and not DevAek:get(AEK.."Aek:Lock:AutoFile")) then
Time = DevAek:get(AEK.."Aek:AutoFile:Time")
if Time then
if Time ~= os.date("%x") then
local list = DevAek:smembers(AEK..'Aek:Groups')
local BotName = (DevAek:get(AEK.."Aek:NameBot") or 'بروكس')
local GetJson = '{"BotId": '..AEK..',"BotName": "'..BotName..'","GroupsList":{'
for k,v in pairs(list) do
LinkGroups = DevAek:get(AEK.."Aek:Groups:Links"..v)
Welcomes = DevAek:get(AEK..'Aek:Groups:Welcomes'..v) or ''
AekConstructors = DevAek:smembers(AEK..'Aek:AekConstructor:'..v)
BasicConstructors = DevAek:smembers(AEK..'Aek:BasicConstructor:'..v)
Constructors = DevAek:smembers(AEK..'Aek:Constructor:'..v)
Managers = DevAek:smembers(AEK..'Aek:Managers:'..v)
Admis = DevAek:smembers(AEK..'Aek:Admins:'..v)
Vips = DevAek:smembers(AEK..'Aek:VipMem:'..v)
if k == 1 then
GetJson = GetJson..'"'..v..'":{'
else
GetJson = GetJson..',"'..v..'":{'
end
if #Vips ~= 0 then
GetJson = GetJson..'"Vips":['
for k,v in pairs(Vips) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if #Admis ~= 0 then
GetJson = GetJson..'"Admis":['
for k,v in pairs(Admis) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if #Managers ~= 0 then
GetJson = GetJson..'"Managers":['
for k,v in pairs(Managers) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if #Constructors ~= 0 then
GetJson = GetJson..'"Constructors":['
for k,v in pairs(Constructors) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if #BasicConstructors ~= 0 then
GetJson = GetJson..'"BasicConstructors":['
for k,v in pairs(BasicConstructors) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if #AekConstructors ~= 0 then
GetJson = GetJson..'"AekConstructors":['
for k,v in pairs(AekConstructors) do
if k == 1 then
GetJson = GetJson..'"'..v..'"'
else
GetJson = GetJson..',"'..v..'"'
end
end
GetJson = GetJson..'],'
end
if LinkGroups then
GetJson = GetJson..'"LinkGroups":"'..LinkGroups..'",'
end
GetJson = GetJson..'"Welcomes":"'..Welcomes..'"}'
end
GetJson = GetJson..'}}'
local File = io.open('./'..AEK..'.json', "w")
File:write(GetJson)
File:close()
local Aekan = 'https://api.telegram.org/bot' .. TokenBot .. '/sendDocument'
local curl = 'curl "' .. Aekan .. '" -F "chat_id='..DevId..'" -F "document=@'..AEK..'.json' .. '" -F "caption=♕︙نسخه تلقائيه تحتوي على ↫ '..#list..' مجموعه"'
io.popen(curl)
io.popen('fm -fr '..AEK..'.json')
DevAek:set(AEK.."Aek:AutoFile:Time",os.date("%x"))
end
else
DevAek:set(AEK.."Aek:AutoFile:Time",os.date("%x"))
end
end
end
return {
AEK = AutoFile
} |
local player = ...
local pn = ToEnumShortString(player)
local p = PlayerNumber:Reverse()[player]
local rv
local zoom_factor = WideScale(0.8,0.9)
local labelX_col1 = WideScale(-70,-90)
local dataX_col1 = WideScale(-75,-96)
local labelX_col2 = WideScale(10,20)
local dataX_col2 = WideScale(5,15)
local highscoreX = WideScale(56, 80)
local highscorenameX = WideScale(61, 97)
local PaneItems = {}
PaneItems[THEME:GetString("RadarCategory","Taps")] = {
-- "rc" is RadarCategory
rc = 'RadarCategory_TapsAndHolds',
label = {
x = labelX_col1,
y = 150,
},
data = {
x = dataX_col1,
y = 150
}
}
PaneItems[THEME:GetString("RadarCategory","Mines")] = {
rc = 'RadarCategory_Mines',
label = {
x = labelX_col2,
y = 150,
},
data = {
x = dataX_col2,
y = 150
}
}
PaneItems[THEME:GetString("RadarCategory","Jumps")] = {
rc = 'RadarCategory_Jumps',
label = {
x = labelX_col1,
y = 168,
},
data = {
x = dataX_col1,
y = 168
}
}
PaneItems[THEME:GetString("RadarCategory","Hands")] = {
rc = 'RadarCategory_Hands',
label = {
x = labelX_col2,
y = 168,
},
data = {
x = dataX_col2,
y = 168
}
}
PaneItems[THEME:GetString("RadarCategory","Holds")] = {
rc = 'RadarCategory_Holds',
label = {
x = labelX_col1,
y = 186,
},
data = {
x = dataX_col1,
y = 186
}
}
PaneItems[THEME:GetString("RadarCategory","Rolls")] = {
rc = 'RadarCategory_Rolls',
label = {
x = labelX_col2,
y = 186,
},
data = {
x = dataX_col2,
y = 186
}
}
local GetNameAndScore = function(profile)
local song = (GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentCourse()) or GAMESTATE:GetCurrentSong()
local steps = (GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentTrail(player)) or GAMESTATE:GetCurrentSteps(player)
local score = ""
local name = ""
if profile and song and steps then
local scorelist = profile:GetHighScoreList(song,steps)
local scores = scorelist:GetHighScores()
local topscore = scores[1]
if topscore then
score = string.format("%.2f%%", topscore:GetPercentDP()*100.0)
name = topscore:GetName()
else
score = string.format("%.2f%%", 0)
name = "????"
end
end
return score, name
end
local pd = Def.ActorFrame{
Name="PaneDisplay"..ToEnumShortString(player),
InitCommand=function(self)
self:visible(false)
if GAMESTATE:IsHumanPlayer(player) then
self:visible(true)
end
if player == PLAYER_1 then
self:x(_screen.w * 0.25 - 5)
elseif player == PLAYER_2 then
self:x( _screen.w * 0.75 + 5)
end
self:y(_screen.h/2 + 5)
end,
PlayerJoinedMessageCommand=function(self, params)
if player==params.Player then
self:visible(true)
:zoom(0):croptop(0):bounceend(0.3):zoom(1)
:playcommand("Set")
end
end,
PlayerUnjoinedMessageCommand=function(self, params)
if player==params.Player then
self:accelerate(0.3):croptop(1):sleep(0.01):zoom(0)
end
end,
-- These playcommand("Set") need to apply to the ENTIRE panedisplay
-- (all its children) so declare each here
OnCommand=cmd(queuecommand,"Set"),
CurrentSongChangedMessageCommand=cmd(queuecommand,"Set"),
CurrentCourseChangedMessageCommand=cmd(queuecommand,"Set"),
StepsHaveChangedCommand=cmd(queuecommand,"Set"),
SetCommand=function(self)
local machine_score, machine_name = GetNameAndScore( PROFILEMAN:GetMachineProfile() )
self:GetChild("MachineHighScore"):settext(machine_score)
self:GetChild("MachineHighScoreName"):settext(machine_name):diffuse({0,0,0,1})
DiffuseEmojis(self, machine_name)
if PROFILEMAN:IsPersistentProfile(player) then
local player_score, player_name = GetNameAndScore( PROFILEMAN:GetProfile(player) )
self:GetChild("PlayerHighScore"):settext(player_score)
self:GetChild("PlayerHighScoreName"):settext(player_name):diffuse({0,0,0,1})
DiffuseEmojis(self, player_name)
end
end
}
-- colored background for chart statistics
pd[#pd+1] = Def.Quad{
Name="BackgroundQuad",
InitCommand=cmd(zoomto, _screen.w/2-10, _screen.h/8; y, _screen.h/2 - 67 ),
SetCommand=function(self, params)
if GAMESTATE:IsHumanPlayer(player) then
local StepsOrTrail = GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentTrail(player) or GAMESTATE:GetCurrentSteps(player)
if StepsOrTrail then
local difficulty = StepsOrTrail:GetDifficulty()
self:diffuse( DifficultyColor(difficulty) )
else
self:diffuse( PlayerColor(player) )
end
end
end
}
for key, item in pairs(PaneItems) do
pd[#pd+1] = Def.ActorFrame{
Name=key,
OnCommand=cmd(x, -_screen.w/20; y,6 ),
-- label
LoadFont("_miso")..{
Text=key,
InitCommand=cmd(zoom, zoom_factor; xy, item.label.x, item.label.y; diffuse, Color.Black; shadowlength, 0.2; halign, 0)
},
-- numerical value
LoadFont("_miso")..{
InitCommand=cmd(zoom, zoom_factor; xy, item.data.x, item.data.y; diffuse, Color.Black; shadowlength, 0.2; halign, 1),
OnCommand=cmd(playcommand, "Set"),
SetCommand=function(self)
local song = (GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentCourse()) or GAMESTATE:GetCurrentSong()
if not song then
self:settext("?")
return
end
local steps = (GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentTrail(player)) or GAMESTATE:GetCurrentSteps(player)
if steps then
rv = steps:GetRadarValues(player)
local val = rv:GetValue( item.rc )
-- negative ones show up for autogenerated content
-- show a question mark instead
if val == -1 then
self:settext("?")
else
self:settext( val )
end
else
self:settext( "" )
end
end
}
}
end
-- chart difficulty meter
pd[#pd+1] = Def.BitmapText{
Font="_wendy small",
Name="DifficultyMeter",
InitCommand=cmd(horizalign, right; diffuse, Color.Black; xy, _screen.w/4 - 10, _screen.h/2 - 65; queuecommand, "Set"),
SetCommand=function(self)
local SongOrCourse = (GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentCourse()) or GAMESTATE:GetCurrentSong()
if not SongOrCourse then
self:settext("")
else
local StepsOrTrail = GAMESTATE:IsCourseMode() and GAMESTATE:GetCurrentTrail(player) or GAMESTATE:GetCurrentSteps(player)
local meter = StepsOrTrail and StepsOrTrail:GetMeter()
self:settext( meter and meter or "?" )
end
end
}
--MACHINE high score
pd[#pd+1] = Def.BitmapText{
Font="_miso",
Name="MachineHighScore",
InitCommand=cmd(x, highscoreX; y, 156; zoom, zoom_factor; diffuse, Color.Black; halign, 1 )
}
--MACHINE highscore name
pd[#pd+1] = Def.BitmapText{
Font="_miso",
Name="MachineHighScoreName",
InitCommand=cmd(x, highscorenameX; y, 156; zoom, zoom_factor; diffuse, Color.Black; halign, 0; maxwidth, 80)
}
--PLAYER PROFILE high score
pd[#pd+1] = Def.BitmapText{
Font="_miso",
Name="PlayerHighScore",
InitCommand=cmd(x, highscoreX; y, 176; zoom, zoom_factor; diffuse, Color.Black; halign, 1 )
}
--PLAYER PROFILE highscore name
pd[#pd+1] = Def.BitmapText{
Font="_miso",
Name="PlayerHighScoreName",
InitCommand=cmd(x, highscorenameX; y, 176; zoom, zoom_factor; diffuse, Color.Black; halign, 0; maxwidth, 80)
}
return pd |
require 'math'
--[[
A simple module with "math related" utility functions
]]--
local math_utils = {}
function math_utils.random_range(min, max)
if type(min) ~= 'number' then
min = 0
end
if type(max) ~= 'number' then
max = 1
end
if (max < min) then
local temp = max
max = min
min = temp
end
local res = math.random(max - min) + min
if res == 0 then
res = math_utils.random_range(min, max)
end
return res
end
function math_utils.radians(v)
if type(v) == 'number' then
return v / 180 * math.pi
end
end
function math_utils.degrees(v)
if type(v) == 'number' then
return v / math.pi * 180
end
end
return math_utils
|
-- x64 specific definitions
return {
epoll = [[
struct epoll_event {
uint32_t events;
epoll_data_t data;
} __attribute__ ((packed));
]],
ucontext = [[
typedef long long greg_t, gregset_t[23];
typedef struct _fpstate {
unsigned short cwd, swd, ftw, fop;
unsigned long long rip, rdp;
unsigned mxcsr, mxcr_mask;
struct {
unsigned short significand[4], exponent, padding[3];
} _st[8];
struct {
unsigned element[4];
} _xmm[16];
unsigned padding[24];
} *fpregset_t;
typedef struct {
gregset_t gregs;
fpregset_t fpregs;
unsigned long long __reserved1[8];
} mcontext_t;
typedef struct __ucontext {
unsigned long uc_flags;
struct __ucontext *uc_link;
stack_t uc_stack;
mcontext_t uc_mcontext;
sigset_t uc_sigmask;
unsigned long __fpregs_mem[64];
} ucontext_t;
]],
stat = [[
struct stat {
unsigned long st_dev;
unsigned long st_ino;
unsigned long st_nlink;
unsigned int st_mode;
unsigned int st_uid;
unsigned int st_gid;
unsigned int __pad0;
unsigned long st_rdev;
long st_size;
long st_blksize;
long st_blocks;
unsigned long st_atime;
unsigned long st_atime_nsec;
unsigned long st_mtime;
unsigned long st_mtime_nsec;
unsigned long st_ctime;
unsigned long st_ctime_nsec;
long __unused[3];
};
]],
}
|
function SpawnPoints()
return {
constructionworker = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
fireofficer = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
parkranger = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
carpenter = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
burglar = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
chef = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
repairman = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
farmer = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
fisherman = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
doctor = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
veteran = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
nurse = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
lumberjack = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
fitnessinstructor = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
burgerflipper = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
electrician = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
engineer = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
policeofficer = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
securityguard = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
},
unemployed = {
{ worldX = 37, worldY = 35, posX = 168, posY = 188, posZ = 0 }
}
}
end
|
ParticleSystem = {}
ParticleSystem.__index = ParticleSystem
function ParticleSystem:new(universe)
local particle_system = {}
setmetatable(particle_system, self)
particle_system.particles = {}
particle_system.emitters = {}
particle_system.universe = universe
return particle_system
end
function ParticleSystem:create_particle(x, y, vx, vy, size, time)
self.particles[#self.particles + 1] = {
size = size,
color = {1, 1, 1, 1},
x = x,
y = y,
vx = vx,
vy = vy,
timeleft = time
}
end
function ParticleSystem:create_emitter(x, y, v, amountpertick, ticks)
self.emitters[#self.emitters + 1] = {
size = size,
x = x,
y = y,
v = v,
amountpertick = amountpertick,
ticksleft = ticks
}
end
function ParticleSystem:tick(dt)
-- Spawn particles from emitters
for i, emitter in ipairs(self.emitters) do
local randomdir = math.random() * math.pi * 2
for _ = 0, emitter.amountpertick do
self:create_particle(emitter.x, emitter.y, math.sin(randomdir) * emitter.v, math.cos(randomdir) * emitter.v, 5, 0.5)
end
emitter.ticksleft = emitter.ticksleft - 1
end
-- Remove old emitters
for i, emitter in ipairs(self.emitters) do
if emitter.ticksleft <= 0 then
table.remove(self.emitters, i)
end
end
-- Tick the particles
for i, particle in ipairs(self.particles) do
particle.x = particle.x + particle.vx * dt
particle.y = particle.y + particle.vy * dt
particle.timeleft = particle.timeleft - dt
end
-- Remove particles that are old
for i, particle in ipairs(self.particles) do
if particle.timeleft <= 0 then
table.remove(self.particles, i)
end
end
end
function ParticleSystem:draw()
for i, particle in ipairs(self.particles) do
love.graphics.push()
love.graphics.setColor(particle.color)
love.graphics.rectangle("fill", particle.x, particle.y, particle.size, particle.size)
love.graphics.pop()
end
end
|
local ffi = require "ffi"
local ffi_cdef = ffi.cdef
ffi_cdef[[
void *opaque;
void (*blockcode)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *lang, const hoedown_renderer_data *data);
void (*blockquote)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*header)(hoedown_buffer *ob, const hoedown_buffer *content, int level, const hoedown_renderer_data *data);
void (*hrule)(hoedown_buffer *ob, const hoedown_renderer_data *data);
void (*list)(hoedown_buffer *ob, const hoedown_buffer *content, hoedown_list_flags flags, const hoedown_renderer_data *data);
void (*listitem)(hoedown_buffer *ob, const hoedown_buffer *content, hoedown_list_flags flags, const hoedown_renderer_data *data);
void (*paragraph)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*table)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*table_header)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*table_body)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*table_row)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*table_cell)(hoedown_buffer *ob, const hoedown_buffer *content, hoedown_table_flags flags, const hoedown_renderer_data *data);
void (*footnotes)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
void (*footnote_def)(hoedown_buffer *ob, const hoedown_buffer *content, unsigned int num, const hoedown_renderer_data *data);
void (*blockhtml)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data);
int (*autolink)(hoedown_buffer *ob, const hoedown_buffer *link, hoedown_autolink_type type, const hoedown_renderer_data *data);
int (*codespan)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data);
int (*double_emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*underline)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*highlight)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*quote)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*image)(hoedown_buffer *ob, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *alt, const hoedown_renderer_data *data);
int (*linebreak)(hoedown_buffer *ob, const hoedown_renderer_data *data);
int (*link)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_renderer_data *data);
int (*triple_emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*strikethrough)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*superscript)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data);
int (*footnote_ref)(hoedown_buffer *ob, unsigned int num, const hoedown_renderer_data *data);
int (*math)(hoedown_buffer *ob, const hoedown_buffer *text, int displaymode, const hoedown_renderer_data *data);
int (*raw_html)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data);
void (*entity)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data);
void (*normal_text)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data);
void (*doc_header)(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data);
void (*doc_footer)(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data);
]]
-- TODO: NYI. |
client_scripts {
'data-ora.lua'
} |
#!/usr/bin/env lua
require("socket")
stack = {}
mem = {}
handles = {}
address = {"0.0.0.0", 0}
contexts = {}
contextpos = {}
curcontext = 0
pos = 0
function clear()
while #stack ~= 0 do
table.remove(stack)
end
end
do
local mt = {}
function mt.__index() return 0 end
setmetatable(stack, mt)
setmetatable(mem, mt)
end
function readfd(fd, arg)
if io.type(fd) then
return fd:read(arg)
else
return fd:receive(arg)
end
end
function writefd(fd, text)
if io.type(fd) then
return fd:write(text)
else
return fd:send(text)
end
end
funcs = {
[0x0001] = function() --output
for i, v in ipairs(stack) do
if v == 0 then break end
io.write(string.char(v))
end
clear()
end,
[0x0002] = function() --input
local pos, size = stack[1], stack[2]
clear()
local text = io.read():sub(1, size)
for i = 0, size-1 do
mem[pos+i] = text:sub(i+1, i+1) and string.byte(text:sub(i+1, i+1)) or 0
end
table.insert(stack, #text+1)
end,
[0x0003] = function() --fileopen
local fname = ""
local mode
for i, v in ipairs(stack) do
if v == 0 then break end
fname = fname .. string.char(v)
end
mode = stack[#fname+2]
clear()
if mode == 1 then
mode = "r"
elseif mode == 2 then
mode = "w"
elseif mode == 3 then
mode = "a"
end
local f = assert(io.open(fname, mode))
local id = #handles+1
table.insert(handles, id, f)
table.insert(stack, id-1)
end,
[0x0004] = function() --fileclose
local id = stack[1]+1
clear()
handles[id]:close()
handles[id] = nil
end,
[0x0005] = function() --read
local id, pos, size = stack[1]+1, stack[2], stack[3]
clear()
local text = readfd(handles[id], size-1)
for i = 0, size-1 do
mem[pos+i] = text:sub(i+1, i+1) and string.byte(text:sub(i+1, i+1)) or 0
end
table.insert(stack, #text+1)
end,
[0x0006] = function() --write
local id = stack[1]+1
table.remove(stack, 1)
local text = ""
for i, v in ipairs(stack) do
if v == 0 then break end
text = text .. string.char(v)
end
writefd(handles[id], text)
clear()
end,
[0x0007] = function() --tcp
local ip = ""
for i, v in ipairs(stack) do
if v == 0 then break end
ip = ip .. string.char(v)
end
local port = stack[#ip+2]
clear()
local sock = socket.tcp()
local id = #handles+1
table.insert(handles, id, sock)
assert(sock:connect(ip, port))
table.insert(stack, id-1)
end,
[0x0008] = function() --udp
clear()
local sock = socket.udp()
local id = #handles+1
table.insert(handles, id, sock)
table.insert(stack, id-1)
end,
[0x0009] = function() --createip
local addr, a, b, c, d = stack[1], stack[2], stack[3], stack[4], stack[5]
clear()
local s = string.format("%d.%d.%d.%d", a, b, c, d)
for i = 0, #s-1 do
mem[addr+i] = s:sub(i+1, i+1)
end
table.insert(stack, #s)
end,
[0x000a] = function() --sendto
local id = stack[1]+1
table.remove(stack, 1)
local text = ""
while stack[1] ~= 0 do
text = text .. string.char(table.remove(stack, 1))
end
table.remove(stack, 1)
local ip = ""
while stack[1] ~= 0 do
ip = ip .. string.char(table.remove(stack, 1))
end
table.remove(stack, 1)
local port = stack[1]
clear()
handles[id]:sendto(text, ip, port)
end,
[0x000b] = function() --storeaddress
local ip = ""
while stack[1] ~= 0 do
ip = ip .. string.char(table.remove(stack, 1))
end
table.remove(stack, 1)
local port = stack[1]
clear()
address = {ip, port}
end,
[0x000c] = function() --getaddress
clear()
local ip = address[1]
local iplen = #ip
local port = address[2]
for i = 1, iplen do
table.insert(stack, string.byte(ip:sub(1, 1)))
end
table.insert(stack, 0)
table.insert(stack, port)
end,
[0x000d] = function() --createcontext
local s, e = (stack[#stack-1]-1)*3, (stack[#stack])*3
clear()
local data = contexts[1]:sub(s+1, e)
local id = #contexts+1
table.insert(contexts, id, data)
table.insert(stack, id-1)
end,
[0xFFFF] = function() --debug
print(stack[#stack])
end,
}
commands = {
[0x01] = function(address) --get
table.insert(stack, mem[address] or 0)
end,
[0x02] = function(address) --set
mem[address] = stack[#stack]
end,
[0x03] = function(value) --put
table.insert(stack, value)
end,
[0x04] = function() --pop
table.remove(stack)
end,
[0x05] = function(func) --call
funcs[func]()
end,
[0x06] = function() --clear
clear()
end,
[0x07] = function() --getp
stack[#stack] = mem[stack[#stack]]
end,
[0x08] = function(p) --goto
local b = stack[#stack] > 0
clear()
if b then
pos = (p-1)*3
end
end,
[0x09] = function() --gotos
local b, p = stack[#stack-1] > 0, stack[#stack]
clear()
if b then
pos = (p-1)*3
end
end,
[0x0a] = function() --add
local r = stack[#stack-1] + stack[#stack]
stack[#stack] = nil
stack[#stack] = r
end,
[0x0b] = function() --sub
local r = stack[#stack-1] - stack[#stack]
stack[#stack] = nil
stack[#stack] = r
end,
[0x0c] = function() --mult
local r = stack[#stack-1] * stack[#stack]
stack[#stack] = nil
stack[#stack] = r
end,
[0x0d] = function() --div
local r = math.floor(stack[#stack-1] / stack[#stack])
stack[#stack] = nil
stack[#stack] = r
end,
[0x0e] = function() --pow
local r = stack[#stack-1] ^ stack[#stack]
stack[#stack] = nil
stack[#stack] = r
end,
[0x0f] = function() --root
local r = math.floor(stack[#stack-1] ^ (1/stack[#stack]))
stack[#stack] = nil
stack[#stack] = r
end,
[0x10] = function() --mod
local r = stack[#stack-1] % stack[#stack]
stack[#stack] = nil
stack[#stack] = r
end,
[0x11] = function() --eq
local r = stack[#stack-1] == stack[#stack]
stack[#stack] = nil
stack[#stack] = r and 1 or 0
end,
[0x12] = function() --lt
local r = stack[#stack-1] < stack[#stack]
stack[#stack] = nil
stack[#stack] = r and 1 or 0
end,
[0x13] = function() --gt
local r = stack[#stack-1] > stack[#stack]
stack[#stack] = nil
stack[#stack] = r and 1 or 0
end,
[0x14] = function() --not
local r = stack[#stack] == 0
stack[#stack] = r and 1 or 0
end,
[0x15] = function() --pos
clear()
table.insert(stack, pos/3)
end,
[0x16] = function(address) --ascii
local s = string.format("%d", stack[#stack])
for i = 0, #s-1 do
mem[address+i] = s:sub(i+1, i+1) and string.byte(s:sub(i+1, i+1)) or 0
end
table.insert(stack, #s)
end,
[0x17] = function(address) --num
local c = 0
local s = ""
while true do
if not mem[address+c] or mem[address+c] == 0 then break end
s = s .. string.char(mem[address+c])
c = c + 1
end
table.insert(stack, tonumber(s))
end,
[0x18] = function() --setp
mem[stack[#stack-1]] = stack[#stack]
end,
[0x19] = function(c) --ctxt
local oldc = curcontext
contextpos[curcontext] = pos
curcontext = c+1
pos = contextpos[curcontext] or 0
clear()
table.insert(stack, oldc-1)
end,
[0x1a] = function() --ctxts
local oldc = curcontext
contextpos[curcontext] = pos
curcontext = stack[#stack]+1
pos = contextpos[curcontext] or 0
clear()
table.insert(stack, oldc-1)
end,
}
if not arg then
print("Must be called from the command line")
return 1
end
if #arg < 1 then
print("Usage: " .. arg[0] .. " <infile>")
return 1
end
i = arg[1] == "-" and io.stdin or io.open(arg[1], "rb")
if not i then
print("Could not open file " .. arg[1])
return 1
end
if #arg > 1 then
for i = 2, #arg do
table.insert(stack, tonumber(arg[i]))
end
end
local contents = i:read("*a")
i:close()
table.insert(contexts, contents)
local command, args
curcontext = 1
pos = 0
local line = contexts[curcontext]:sub(pos+1, pos+3)
while line ~= "" do
command = string.byte(line:sub(1, 1))
args = string.byte(line:sub(2, 2))
args = args * 256 + string.byte(line:sub(3, 3))
commands[command](args)
pos = pos + 3
line = contexts[curcontext]:sub(pos+1, pos+3)
end
print()
|
object_tangible_quest_corellia_disappearances_2_object_2 = object_tangible_quest_shared_corellia_disappearances_2_object_2:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_corellia_disappearances_2_object_2, "object/tangible/quest/corellia_disappearances_2_object_2.iff")
|
local color = require('__stdlib__/stdlib/utils/defines/color')
local allowed_values = {'default'}
for name in pairs(color) do
allowed_values[#allowed_values + 1] = name
end
data:extend{
{
type = 'string-setting',
name = 'picker-chat-color',
setting_type = 'runtime-per-user',
default_value = 'default',
allowed_values = allowed_values,
order = 'player-options-chat-color'
},
{
type = 'string-setting',
name = 'picker-character-color',
setting_type = 'runtime-per-user',
default_value = 'default',
allowed_values = allowed_values,
order = 'player-options-character-color'
}
} |
vim.bo.tabstop = 4
vim.bo.shiftwidth = 4
vim.bo.expandtab = true
vim.wo.listchars = {
tab = ".."
}
|
local K = require("game.constants")
local hsl = require("utils.hsl")
local easing = require('tweener.easing')
local dynArray = require("utils.dynArray")
local timing = require("utils.timing")
local buffer = require('utils.buffer')
local r = math.random
local eh, es, el = easing.outQuad, easing.outExpo, easing.inQuad
local function chunkyCheckers(chunky)
local self = {}
local W, H, MAX_STRIPES = chunky.w, chunky.h, chunky.h * 4
local matrix = buffer(W, H)
local min, max = W / 4, W
local function newStripe()
local l = math.floor(min + (max - min) * math.random())
return { x = 2 * W - math.random(W) + l, y = math.random(H), l = l, speed=math.random(W/5) }
end
local stripes = {} do
for i = 1, MAX_STRIPES do stripes[#stripes + 1] = newStripe() end
end
local function putStripe(x, y, length)
for i = x, x + length do matrix.put(easing.linear(i - x, 0.5, -0.5, length), i, y) end
end
local hue = 0
local function updateStripes()
matrix.clear(0)
for i, s in ipairs(stripes) do
if s.x + s.l > 1 then
s.x = s.x - s.speed
else
stripes[i] = newStripe()
end
putStripe(s.x, s.y, s.l)
end
for i, j in chunky.coords() do
chunky.put(i, j, hue, 1, matrix.get(i, j))
end
end
local t = timing.interval(1/60, updateStripes)
local function update(dt)
hue = hue + dt / 10
t(dt)
end
return update
end
return chunkyCheckers
|
data:extend({
{
type = "assembling-machine",
name = "arboretum",
icon = "__zenith-bio__/graphics/icons/arboretum.png",
icon_size = 32,
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "arboretum"},
max_health = 350,
corpse = "big-remnants",
dying_explosion = "medium-explosion",
alert_icon_shift = util.by_pixel(-3, -12),
resistances =
{
{
type = "fire",
percent = 70
}
},
fluid_boxes = {
{
production_type = "input",
pipe_picture = assembler3pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {0, -2} }}
},
{
production_type = "input",
pipe_picture = assembler3pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {0, 2} }}
},
{
production_type = "output",
pipe_picture = assembler3pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {2, 0} }}
},
off_when_no_fluid_recipe = true
},
collision_box = {{-1.2, -1.2}, {1.2, 1.2}},
selection_box = {{-1.5, -1.5}, {1.5, 1.5}},
fast_replaceable_group = "arboretum",
animation =
{
layers =
{
{
filename = "__zenith-bio__/graphics/entity/arboretum/arboretum.png",
width = 98,
height = 87,
frame_count = 33,
line_length = 11,
animation_speed = 1 / 3,
shift = util.by_pixel(0, 1.5),
hr_version =
{
filename = "__zenith-bio__/graphics/entity/arboretum/hr-arboretum.png",
width = 194,
height = 174,
frame_count = 33,
line_length = 11,
animation_speed = 1 / 3,
shift = util.by_pixel(0, 1.5),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/lab/lab-integration.png",
width = 122,
height = 81,
frame_count = 1,
line_length = 1,
repeat_count = 33,
animation_speed = 1 / 3,
shift = util.by_pixel(0, 15.5),
hr_version =
{
filename = "__base__/graphics/entity/lab/hr-lab-integration.png",
width = 242,
height = 162,
frame_count = 1,
line_length = 1,
repeat_count = 33,
animation_speed = 1 / 3,
shift = util.by_pixel(0, 15.5),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/lab/lab-shadow.png",
width = 122,
height = 68,
frame_count = 1,
line_length = 1,
repeat_count = 33,
animation_speed = 1 / 3,
shift = util.by_pixel(13, 11),
draw_as_shadow = true,
hr_version =
{
filename = "__base__/graphics/entity/lab/hr-lab-shadow.png",
width = 242,
height = 136,
frame_count = 1,
line_length = 1,
repeat_count = 33,
animation_speed = 1 / 3,
shift = util.by_pixel(13, 11),
scale = 0.5,
draw_as_shadow = true
}
}
}
},
working_sound =
{
sound =
{
filename = "__zenith-bio__/sound/scream.ogg",
volume = 0.4
},
max_sounds_per_type = 3
},
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
crafting_categories = { "arboretuming" },
crafting_speed = 1,
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
emissions = 0.04 / 2.5
},
energy_usage = "150kW",
ingredient_count = 4,
module_specification =
{
module_slots = 2
},
allowed_effects = {"consumption", "speed", "productivity", "pollution"}
},
{
type = "item",
name = "arboretum",
icon = "__zenith-bio__/graphics/icons/arboretum.png",
icon_size = 32,
flags = {"goes-to-quickbar"},
subgroup = "production-machine",
order = "h",
place_result = "arboretum",
stack_size = 10
},
{
type = "recipe",
name = "arboretum",
energy_required = 2,
enabled = false,
ingredients =
{
{ "iron-plate", 5 },
{ "electronic-circuit", 5 },
{ "stone", 5 },
},
result = "arboretum"
},
{
type = "recipe-category",
name = "arboretuming"
},
})
|
local weapon_class = 'weapon_quest_system_tool_trigger_selector'
sgui.RouteRegister('qsystem/editor/quest/triggers', function(quest)
net.Start('sv_qsystem_open_trigger_editor')
net.SendToServer()
local is_back = true
local frame = vgui.Create('DFrame')
frame:SetPos(20, 20)
frame:SetSize(550, 350)
frame:SetTitle('Select trigger')
frame:MakePopup()
frame:Center()
frame.OnClose = function(self)
if not is_back then return end
net.Start('sv_qsystem_close_trigger_editor')
net.SendToServer()
sgui.route('qsystem/editor/quest', quest)
end
local QuestList = vgui.Create('DListView', frame)
QuestList:Dock(FILL)
QuestList:SetMultiSelect(false)
QuestList:AddColumn('Id')
QuestList:AddColumn('Type')
local exists_names = {}
for _, step in pairs(quest.steps) do
if step.triggers ~= nil then
for name, _ in pairs(step.triggers) do
if not table.HasValue(exists_names, name) then
local line = QuestList:AddLine(name)
QuestSystem:GetStorage('trigger'):Read(quest.id, name, function(ply, data)
line:SetColumnText(2, data.type)
end)
table.insert(exists_names, name)
end
end
end
end
QuestList.OnRowSelected = function(lst, index, pnl)
if not LocalPlayer():HasWeapon(weapon_class) then return end
timer.Simple(0.1, function()
sgui.route('qsystem/editor/quest/triggers/select', quest, pnl:GetColumnText(1))
is_back = false
frame:Close()
end)
end
end, { isAdmin = true})
sgui.RouteRegister('qsystem/editor/quest/triggers/select', function(quest, trigger_name)
local weapon = LocalPlayer():GetWeapon(weapon_class)
QuestSystem:GetStorage('trigger'):Read(quest.id, trigger_name, function(ply, data)
if IsValid(weapon) then
weapon.CurrentTrigger = data
end
end)
local trigger = nil
local PanelManager = DFCL:New('qsystem_trigger_editor')
PanelManager:AddMouseClickListener()
PanelManager:AddContextMenuListener()
PanelManager:AddFocusName('DTextEntry')
local InfoPanel = vgui.Create('DFrame')
InfoPanel:MakePopup()
InfoPanel:SetSize(230, 180)
InfoPanel:SetPos(100, ScrH() / 2 - 10)
InfoPanel:SetTitle('Trigger editor')
InfoPanel:SetSizable(false)
InfoPanel:SetDraggable(true)
InfoPanel:ShowCloseButton(false)
InfoPanel:SetKeyboardInputEnabled(false)
InfoPanel:SetMouseInputEnabled(false)
InfoPanel:SetVisible(true)
InfoPanel.Paint = function(self, width, height)
draw.RoundedBox(0, 0, 0, width, height, Color(33, 29, 46, 255))
if trigger ~= nil then
surface.SetFont('Trebuchet18')
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(15, 25)
surface.DrawText('Trigger:')
surface.SetTextPos(15, 40)
surface.DrawText(trigger.type)
surface.SetTextColor(94, 220, 255, 255)
surface.SetFont('Default')
if trigger.type == 'box' then
if trigger.vec1 ~= nil then
surface.SetTextPos(15, 55)
surface.DrawText(tostring(trigger.vec1))
end
if trigger.vec2 ~= nil then
surface.SetTextPos(15, 65)
surface.DrawText(tostring(trigger.vec2))
end
end
if trigger.type == 'sphere' then
if trigger.center ~= nil then
surface.SetTextPos(15, 55)
surface.DrawText(tostring(trigger.center))
end
if trigger.radius ~= nil then
surface.SetTextPos(15, 65)
surface.DrawText(trigger.radius)
end
end
end
if IsValid(weapon) then
trigger = weapon.CurrentTrigger
else
self:Close()
end
end
InfoPanel.OnClose = function()
weapon:ClearTriggerPosition()
sgui.route('qsystem/editor/quest/triggers', quest)
PanelManager:Destruct()
end
PanelManager:AddPanel(InfoPanel, true)
local InfoButtonYes = vgui.Create('DButton')
InfoButtonYes:SetParent(InfoPanel)
InfoButtonYes:SetText('Save')
InfoButtonYes:SetPos(15, 100)
InfoButtonYes:SetSize(200, 30)
InfoButtonYes.DoClick = function()
if trigger_name ~= nil and trigger ~= nil then
QuestSystem:GetStorage('trigger'):Save(quest.id, trigger_name, trigger)
surface.PlaySound('buttons/blip1.wav')
else
surface.PlaySound('Resource/warning.wav')
end
end
PanelManager:AddPanel(InfoButtonYes)
local InfoButtonNo = vgui.Create('DButton')
InfoButtonNo:SetParent(InfoPanel)
InfoButtonNo:SetText('Exit')
InfoButtonNo:SetPos(15, 140)
InfoButtonNo:SetSize(200, 30)
InfoButtonNo.DoClick = function()
InfoPanel:Close()
end
PanelManager:AddPanel(InfoButtonNo)
end, { isAdmin = true}) |
SCRIPT_TITLE = "Super Mario Bros. 3 Rainbow Riding"
SCRIPT_VERSION = "0.1"
require "m_utils"
m_require("m_utils",0)
--[[
Super Mario Bros. 3 Rainbow Riding
version 0.1 by miau
Visit http://morphcat.de/lua/ for the most recent version and other scripts.
This script turns smb3 into a new game very similar to Kirby's Canvas Curse.
It's still incomplete, messy and full of bugs, so don't expect too much. Next version
will fix most of that... hopefully.
Probably slow on old computers, you may want to turn down emulator speed anyway to
decrease difficulty.
Controls
Left-click on mario - jump
Middle-click anywhere - run
Draw vertical lines to make mario change his walking direction
Draw horizontal lines to help mario move over obstacles
Supported roms
Super Mario Bros 3 (J), Super Mario Bros 3 (U) (PRG 0), Super Mario Bros 3 (U) (PRG 1),
Super Mario Bros 3 (E)
Known Bugs/TODO list
Too many to list em all, actually...
- game objects are occasionally catapulted out of screen - bad divisions!?
- mario falling through lines (clean up collision detection)
- long vertically scrolling levels won't work
- boss battles are glitchy
- disable auto move in mini games?
- option to disable auto move?
- make collision detection work with fire balls (fire mario or fire piranha plants)
- improve map screen check
- add easy mode: decrease mario's speed
- improve enemy hit boxes
- (add suicide button in case mario gets stuck)
-]]
--configurable vars
local show_cursor = false
--------------------------------------------------------------------------------------------
local Z_LSPAN = 400 --240
local Z_MAX = 128 --256 --maximum amount of lines on screen
local NUM_SPRITES = 20
local zbuf = {}
local zindex = 1
local timer = 0
local zprev = 0
local last_inp={}
local spr = {} --game's original sprites
local mario = {}
local clickbox={x1=-4,y1=4,x2=18,y2=32}
local collx = 0
local colly = 0
--local coll = {} --debug
local paintmeter = 0
local lastpaint = -100
local jp = {}
--accepts two tables containing these elements [1]=x1, [2]=y1, [3]=x2, [4]=y2
function get_line_intersection(a,b)
local Asx,Asy,Bsx,Bsy,s,t
local Ax1,Ay1,Ax2,Ay2
local Bx1,By1,Bx2,By2
Ax1 = a[1]
Ay1 = a[2]
Ax2 = a[3]
Ay2 = a[4]
Bx1 = b[1]
By1 = b[2]
Bx2 = b[3]
By2 = b[4]
Asx = Ax2 - Ax1
Asy = Ay2 - Ay1
Bsx = Bx2 - Bx1
Bsy = By2 - By1
s = (-Asy * (Ax1 - Bx1) + Asx * (Ay1 - By1)) / (-Bsx*Asy + Asx*Bsy)
t = (Bsx * (Ay1 - By1) - Bsy * (Ax1 - Bx1)) / (-Bsx*Asy + Asx*Bsy)
if(s>=0 and s<=1 and t>=0 and t<=1) then
local Ix,Iy
Ix = Ax1 + t * Asx
Iy = Ay1 + t * Asy
return Ix,Iy
else
return nil
end
end
function close_to_line(Px,Py,a,range) --a[4] line segment
local Ax=a[1]
local Ay=a[2]
local Bx=a[3]
local By=a[4]
local APx = Px - Ax
local APy = Py - Ay
local ABx = Bx - Ax
local ABy = By - Ay
local absq = ABx*ABx + ABy*ABy
local apab = APx*ABx + APy*ABy
local t = apab / absq
if (t < 0.0) then
t = 0.0
elseif (t > 1.0) then
t = 1.0
end
local Cx,Cy
Cx = Ax + ABx * t
Cy = Ay + ABy * t
if(getdistance(Px,Py,Cx,Cy)<=range) then
return true
else
return false
end
end
function ride_line(s,xoffs,yoffs)
local function move(zx1,zy1,zx2,zy2)
local avx,avy,cvx,cvy
cvx,cvy = getvdir(zx1,zy1,zx2,zy2)
if(math.abs(spr[s].vx)<math.abs(spr[s].vy)) then
avx = spr[s].vx
avy = spr[s].vx
else
avx = spr[s].vy
avy = spr[s].vy
end
if(spr[s].movetimer) then
avx = cvx*5
avy = cvy*5
else
avx = cvx*2.5
avy = cvy*3
end
set_sprite_velocity(s,avx,avy)
--coll.a = {spr[s].x+xoffs,spr[s].y+yoffs-1,spr[s].x+xoffs+avx*64,spr[s].y+yoffs+avy*64-1}
end
local function getcoords(i)
local j
j = i - 1
if(j < 1) then
j = Z_MAX
end
if(zbuf[i] and zbuf[j]) then
return zbuf[j].x,zbuf[j].y,zbuf[i].x,zbuf[i].y
else
return nil
end
end
local function domovemagic(x,y,firstline)
local zx1,zy1,zx2,zy2 = getcoords(spr[s].riding)
if(zx1 and close_to_line(x,y,{zx1,zy1,zx2,zy2},5)) then
move(zx1,zy1,zx2,zy2)
else
--get next line.. check for collision
spr[s].riding = spr[s].riding + 1
if(spr[s].riding > Z_MAX) then
spr[s].riding = 1
end
if(spr[s].riding==firstline) then
spr[s].riding=nil
return
end
domovemagic(x,y,firstline)
end
end
if(spr[s].riding==nil) then
return
end
local x = spr[s].x+xoffs
local y = spr[s].y+yoffs
domovemagic(x,y,spr[s].riding)
end
function collisioncheck(s)
local c=false
local cvx,cvy
local avx,avy
local function checkpixel(xoffs,yoffs,i,j)
local x = spr[s].x+xoffs
local y = spr[s].y+yoffs
local px2 = x+spr[s].vx
local py2 = y+spr[s].vy
local px1 = x
local py1 = y
local zx = zbuf[i].x
local zy = zbuf[i].y
local zx2 = zbuf[j].x
local zy2 = zbuf[j].y
if(spr[s].vx~=0 or spr[s].vy~=0) then
if(spr[s].vx>0) then --we need at least one pixel!!?
px2 = px2 + 2
elseif(spr[s].vx<0) then
px2 = px2 - 2
end
if(spr[s].vy>0) then
py2 = py2 + 2
elseif(spr[s].vy<0) then
py2 = py2 - 2
end
local cx,cy = get_line_intersection({px1,py1,px2,py2},{zx,zy,zx2,zy2})
if(cx~=nil) then
cx = math.floor(cx)
cy = math.floor(cy)
local avx,avy,cvx,cvy
--coll = {--[[a={px1,py1,px2+spr[s].vx*64,py2+spr[s].vy*64},-]]b={zbuf[i].x,zbuf[i].y,zbuf[j].x,zbuf[j].y}} --debug
collx = cx
colly = cy
avx,avy = getvdir(px1,py1,px2,py2)
cvx,cvy = getvdir(zbuf[j].x,zbuf[j].y,zbuf[i].x,zbuf[i].y)
local x,y
x = cx-xoffs
y = cy-yoffs
if(spr[s].x==x and spr[s].y==y) then
--FCEU.message("boo"..timer)
else
set_sprite_pos(s,x,y)
end
if(s==0) then --mario/luigi
if(math.abs(cvy)==1 and math.abs(cvx) < 0.5) then
change_sprite_dir(s)
set_sprite_velocity(s,-avx,nil)
else
spr[s].riding = i
set_sprite_velocity(s,0,0)
end
else --enemies, moving platforms
end
return true
end
else
if(close_to_line(x,y,{zx,zy,zx2,zy2},4)) then
if(s==0) then
spr[s].riding = i
set_sprite_velocity(s,0,0)
end
return true
else
spr[s].riding = nil
end
end
return false
end
if(spr[s].riding) then
ride_line(s,8,30)
return
end
for i=1,Z_MAX do
if(zbuf[i] and zbuf[i].connected) then
--if(zbuf[i].x >= spr[s].x+hitbox.x1 and zbuf[i].y >= spr[s].y+hitbox.y1
-- and zbuf[i].x <= spr[s].x+hitbox.x2 and zbuf[i].y <= spr[s].y+hitbox.y2) then
--local px = spr[s].x-spr[s].vx
--local py = spr[s].y-spr[s].vy
local j
j = i - 1
if(j < 1) then
j = Z_MAX
end
if(zbuf[j]) then --check if line is still valid (if nil, node disappeared)
if(s==0) then --mario
if(checkpixel(8,30,i,j)) then
return
end
else
if(checkpixel(0,0,i,j) or checkpixel(8,8,i,j)
--[[or checkpixel(0,8,i,j) or checkpixel(8,0,i,j)-]]) then
destroy_sprite(s)
return
end
end
end
--end
end
end
end
function screen_to_game_pos(x,y)
return x+scroll_x,y+scroll_y
end
function game_to_screen_pos(x,y)
return x-scroll_x,y-scroll_y
end
function destroy_sprite(s)
if(s<10) then
memory.writebyte(0x660+s,0x06)
--memory.writebyte(0x660+s,0x00)
--set_sprite_velocity(s,10,10)
else
memory.writebyte(0x6C7+s-10,0x01)
--set_sprite_pos(s,0,0)
end
end
function set_sprite_velocity(s,vx,vy)
if(s<10) then
if(s==0) then
memory.writebyte(0xD8,1) --air flag?
end
if(vx) then
memory.writebyte(0xBD+s,vx*16)
spr[s].vx = vx
end
if(vy) then
memory.writebyte(0xCF+s,vy*16)
spr[s].vy = vy
end
end
end
function set_sprite_pos(i,x,y)
memory.writebyte(0x90+i,AND(x,255))
memory.writebyte(0x75+i,math.floor(x/256))
memory.writebyte(0xA2+i,AND(y,255))
memory.writebyte(0x87+i,math.floor(y/256))
spr[i].x = x
spr[i].y = y
spr[i].sx,spr[i].sy = game_to_screen_pos(spr[i].x,spr[i].y)
end
function change_sprite_dir(s)
if(spr[s].dir == 1) then
spr[s].dir = -1
elseif(spr[s].dir == -1) then
spr[s].dir = 1
end
end
function add_rainbow_coord(cx,cy,connected)
zbuf[zindex] = {t=timer,x=cx,y=cy,connected=connected}
zprev = zbuf[zindex]
zindex = zindex + 1
if(zindex>Z_MAX) then
zindex = 1
end
end
function drawrainbow(x1,y1,x2,y2,coloffs)
local cx,cy
local vx,vy
local color = coloffs
vx,vy = getvdir(x1,y1,x2,y2)
cx = x1
cy = y1
for i=1,200 do
if(cx>=0 and cy>=0 and cx<=253 and cy<=253) then
local rcolor = color/1.8+161 --165
gui.drawpixel(cx,cy,rcolor)
gui.drawpixel(cx,cy+1,rcolor)
gui.drawpixel(cx+1,cy,rcolor)
gui.drawpixel(cx+1,cy+1,rcolor)
gui.drawpixel(cx+2,cy,rcolor)
gui.drawpixel(cx,cy+2,rcolor)
gui.drawpixel(cx+2,cy+1,rcolor)
gui.drawpixel(cx+1,cy+2,rcolor)
gui.drawpixel(cx+2,cy+2,rcolor)
end
if((x2>x1 and cx>x2) or (x2<x1 and cx<x2) or (y2>y1 and cy>y2) or (y2<y1 and cy<y2)) then
break
end
cx = cx + vx
cy = cy + vy
color = color + 17
color = AND(color,15)
end
return color
end
function initialize()
for i=0,NUM_SPRITES-1 do
spr[i] = {
a=0,
id=0,
id2=0,
x=0,
y=0,
hp=0,
}
end
spr[0].dir = 1
spr[0].lastposchange = -999
end
function update_sprites()
mario = spr[0]
--also change dir when colliding with game objects
local x = memory.readbyte(0x90)+memory.readbyte(0x75)*256
local y = memory.readbyte(0xA2)+memory.readbyte(0x87)*256
if(x~=mario.x or y~=mario.y) then
mario.lastposchange = timer
end
if(mario.dir~=0 and mario.riding==nil and timer-mario.lastposchange>60) then
mario.lastposchange = timer
change_sprite_dir(0)
end
--load game sprites from ram
for i=0,NUM_SPRITES-1 do
if(i<10) then
spr[i].x = memory.readbyte(0x90+i)+memory.readbyte(0x75+i)*256
spr[i].y = memory.readbyte(0xA2+i)+memory.readbyte(0x87+i)*256
spr[i].vx = memory.readbytesigned(0xBD+i)/16
spr[i].vy = memory.readbytesigned(0xCF+i)/16
spr[i].a = (memory.readbytesigned(0x660+i)~=0)
spr[i].id = memory.readbytesigned(0x670+i)
spr[i].sx,spr[i].sy = game_to_screen_pos(spr[i].x,spr[i].y)
else
--TODO: 0x5D3?
local xcomp = memory.readbyte(0xFD)
local ycomp = memory.readbyte(0xFC)
spr[i].x = memory.readbyte(0x5C9+i-10)
spr[i].y = memory.readbyte(0x5BF+i-10)
spr[i].a = true
spr[i].vx = 0
spr[i].vy = 0
spr[i].sx = AND(spr[i].x-xcomp+256,255)
spr[i].sy = AND(spr[i].y-ycomp+256,255)
spr[i].x = spr[i].sx + scroll_x
spr[i].y = spr[i].sy + scroll_y
end
if(spr[i].a) then
collisioncheck(i)
end
end
end
function update_vars()
--disabling input not possible anymore in FCEUX 2.1?
jp = {}
if(mario.riding==nil) then
if(mario.movetimer) then
jp.B = 1
mario.movetimer = mario.movetimer - 1
if(mario.movetimer == 0) then
mario.movetimer = nil
end
end
if(mario.dir==1) then
jp.right=1
elseif(mario.dir==-1) then
jp.left=1
end
--if(AND(timer,1)==0) then --automatically enter doors and pipes... not a very good idea actually :P
--jp.up=1
--if(memory.readbyte(0xD8)==1) then --air flag set? try to stay in air as long as possible... makes it easier to rescue mario if collision detection screws up.. sucks in water levels
-- jp.A=1
--end
--else
-- jp.down=1 --automatically enter pipes
--end
end
inp = input.get()
scroll_x = memory.readbyte(0xFD)+memory.readbyte(0x12)*256
scroll_y = memory.readbyte(0xFC)--+memory.readbyte(0x13)*256 --not quite right, long vertical scrolling levels won't work
--0xD8 = 0 -> touch ground, 1 -> air
update_sprites()
if(inp.middleclick) then
mario.movetimer = 30
end
if(inp.leftclick==nil) then
mario.jumping=false
end
if(inp.leftclick and last_inp.leftclick==nil and
inp.xmouse>=mario.sx+clickbox.x1 and inp.xmouse<=mario.sx+clickbox.x2 and
inp.ymouse>=mario.sy+clickbox.y1 and inp.ymouse<=mario.sy+clickbox.y2)
then
jp.A = 1
mario.jumping = true
elseif(inp.leftclick and mario.jumping) then
jp.A = 1
elseif(inp.leftclick) then
if(paintmeter>0) then
local x,y=screen_to_game_pos(inp.xmouse,inp.ymouse)
if(last_inp.leftclick==nil) then
add_rainbow_coord(x,y,false)
outofpaint = nil
elseif(outofpaint==nil) then
if(zprev and getdistance(x,y,zprev.x,zprev.y)>8) then
add_rainbow_coord(x,y,true)
paintmeter = paintmeter - 2
lastpaint = timer
end
end
else
outofpaint = true
end
end
joypad.set(1,jp)
last_mario = mario
last_inp = inp
end
function render()
--bctext(0,20,string.format("Memory usage: %.2f KB",collectgarbage("count")))
local j = 0
for i=1,Z_MAX do
if(zbuf[i]) then
j = j + 1
end
end
--bctext(0,20,"Lines: "..j)
--bctext(0,20,mario.x..","..mario.y)
--bctext(0,30,mario.sx..","..mario.sy)
--bctext(0,40,mario.vx..","..mario.vy)
--bctext(0,50,"D "..mario.dir)
--bctext(0,70,"scroll_x: "..scroll_x)
--bctext(0,80,"scroll_y: "..scroll_y)
--bctext(0,90,AND(mario.x,255))
--if(mario.riding) then
-- bctext(0,100,"R")
--end
bcbox(mario.sx+clickbox.x1,mario.sy+clickbox.y1,mario.sx+clickbox.x2,mario.sy+clickbox.y2,"white")
local prev_x, prev_y, prev_connected
local i=zindex
local color = AND(timer/2,15)
for j=1,Z_MAX do
if(zbuf[i]) then
local ltime = timer-zbuf[i].t
if(ltime<Z_LSPAN) then
local x,y=game_to_screen_pos(zbuf[i].x,zbuf[i].y)
if(prev_x and prev_connected) then
color = drawrainbow(prev_x,prev_y,x,y,color)
end
prev_x = x
prev_y = y
prev_connected = zbuf[i].connected
else
zbuf[i] = nil
end
end
i = i - 1
if(i<1) then
i = Z_MAX
end
end
local cx,cy = game_to_screen_pos(mario.x+8,mario.y+30)
bcpixel(cx,cy,string.format("#%02X%02X%02X",math.random(0,255),math.random(0,255),math.random(0,255)))
local pmx=78
local pmy=226
if(paintmeter>0) then
drawrainbow(pmx+paintmeter,pmy,pmx,pmy,timer/6)
end
bcbox(pmx-2,pmy-1,pmx+102,pmy+3,"white")
if(timer-lastpaint>60) then
paintmeter = paintmeter + 1
if(paintmeter>100) then
paintmeter=100
end
end
if(show_cursor) then
local col2
if(inp.leftclick) then
col2 = "#FFAA00"
elseif(inp.rightclick) then
col2 = "#0099EE"
elseif(inp.middleclick) then
col2 = "#AACC00"
else
col2 = "white"
end
drawcursor(inp.xmouse,inp.ymouse,"black",col2)
end
end
function domagic()
if(memory.readbyte(0x73)==0x20) then --map screen(?)
update_vars()
render()
else
bcpixel(1,10,"clear")
end
end
initialize()
gui.register(domagic)
while(true) do
FCEU.frameadvance()
timer = timer + 1
end
|
dofile "test.lua"
--^ kwb
--[[a comment]] var=11
-- ^ num
-- ^ opt
-- ^^ num
" " var=11
-- ^^ num
-- ^ opt
-- ^^ num
var=111111111111111111111
-- ^^^^^^^^^^^^^^^^^^^^^ num
Strings={
Delimiter=[["|']],
-- ^^^^^^^ str
-- ^ opt
DelimiterPairs= {
{ Open=[[ \[=*\[ ]], Close=[[ \]=*\] ]], Raw=true }
-- ^ ^ str ^ opt
-- ^ opt ^ ^ str ^ kwa
},
AssertEqualLength=true
}
|
--[[
Probabilistic Criterion for Triplet Siamese Model for learning embedding.
Ref: https://arxiv.org/pdf/1610.00243.pdf
loss = -log( exp(-X) / ( exp(-X) + exp(-Y) ) )
where
X : Distance between similar samples
Y : Distance between dissimilar samples
The loss could be break down to following log expansion
loss = -log( exp(-X) ) - (-log( exp(-X) + exp(-Y) ))
= -log( exp(-X) ) + log( exp(-X) + exp(-Y) )
= -(-X) + log( exp(-X) + exp(-Y) )
= X + log( exp(-X) + exp(-Y) )
Gradients:
dLoss/dX = 1 + 1 / (exp(-X) + exp(-Y)) * -1 * exp(-X)
= 1 - exp(-X) / (exp(-X) + exp(-Y))
dLoss/dY = 0 + 1 / (exp(-X) + exp(-Y)) * -1 * exp(-Y)
= -exp(-Y) / (exp(-X) + exp(-Y))
--]]
local DistanceRatioCriterion, parent = torch.class('nn.DistanceRatioCriterion',
'nn.Criterion')
function DistanceRatioCriterion:__init(sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
end
-- Forward
--[[
-- X : Distance between similar samples
-- Y : Distance between dissimilar samples
loss = -log( exp(-X) ) - (-log( exp(-X) + exp(-Y) ))
= -log( exp(-X) ) + log( exp(-X) + exp(-Y) )
= -(-X) + log( exp(-X) + exp(-Y) )
= X + log( exp(-X) + exp(-Y) )
--]]
function DistanceRatioCriterion:updateOutput(input)
assert(#input == 2, "Invalid number of inputs")
local X = input[1]
local Y = input[2]
assert(X:nElement() == Y:nElement(), "Number of distances don't match.")
assert(X:size(1) == Y:size(1), "Invalid distances' size.")
-- Compute exp(-X) and exp(-Y)
self._expMinusX = self._expMinusX or X.new()
self._expMinusY = self._expMinusY or Y.new()
-- Compute ( exp(-X) + exp(-Y) )
self._expMinusX:resizeAs(X):copy(X):mul(-1):exp()
self._expMinusY:resizeAs(Y):copy(Y):mul(-1):exp()
self._sumExpMinusXY = self.sumExpMinusExp or X.new()
self._sumExpMinusXY:resizeAs(self._expMinusX):copy(self._expMinusX)
:add(self._expMinusY)
-- Compute log( exp(-X) + exp(-Y) )
self._logSumExpMinusXY = self._logSumExpMinusXY or self._sumExpMinusXY.new()
self._logSumExpMinusXY:resizeAs(self._sumExpMinusXY)
:copy(self._sumExpMinusXY):log()
-- Compute log( exp(-X) + exp(-Y) )
self.loss = self.loss or self._logSumExpMinusXY.new()
self.loss:resizeAs(X):copy(X):add(self._logSumExpMinusXY)
if self.sizeAverage then
return self.loss:sum()/X:size(1)
else
return self.loss:sum()
end
end
-- Backward
--[[
-- X : Distance between similar samples
-- Y : Distance between dissimilar samples
Gradients:
dLoss/dX = 1 + 1 / (exp(-X) + exp(-Y)) * -1 * exp(-X)
= 1 - exp(-X) / (exp(-X) + exp(-Y))
dLoss/dY = 0 + 1 / (exp(-X) + exp(-Y)) * -1 * exp(-Y)
= -exp(-Y) / (exp(-X) + exp(-Y))
--]]
function DistanceRatioCriterion:updateGradInput(input)
assert(#input == 2, "Invalid number of inputs")
local X = input[1]
local Y = input[2]
assert(X:nElement() == Y:nElement(), "Number of distances don't match.")
assert(X:size(1) == Y:size(1), "Invalid distances' size.")
-- dLoss/dX
-- -exp(-X)
self.dX = self.dX or X.new()
self.dX:resizeAs(self._expMinusX):copy(self._expMinusX):mul(-1)
-- -exp(-X) / (exp(-X) + exp(-Y))
self.dX:cdiv(self._sumExpMinusXY)
-- 1 - exp(-X) / (exp(-X) + exp(-Y))
self.dX:add(1)
-- dLoss/dY
-- -exp(-Y)
self.dY = self.dY or Y.new()
self.dY:resizeAs(self._expMinusY):copy(self._expMinusY):mul(-1)
-- -exp(-Y) / (exp(-X) + exp(-Y))
self.dY:cdiv(self._sumExpMinusXY)
if self.sizeAverage then
self.dX:div(X:size(1))
self.dY:div(X:size(1))
end
return {self.dX, self.dY}
end
function DistanceRatioCriterion:type(type, tensorCache)
if type then
self._expMinusX = nil
self._expMinusY = nil
self._sumExpMinusXY = nil
self._logSumExpMinusXY = nil
self.loss = nil
self.dX = nil
self.dY = nil
end
return parent.type(self, type, tensorCache)
end
|
Hooks:PostHook(UpgradesTweakData, "init", "VPPP_UpgradesTweakData_init", function(self)
self:common_add_throwables("yakuza_injector", 1, 8)
self:common_add_throwables("burglar_luck", 1, 8)
self:common_add_throwables("med_x", 1, 8)
self:common_add_throwables("adrenaline_shot", 2, 10)
self:common_add_throwables("spare_armor_plate", 1, 0.5)
self:common_add_throwables("liquid_armor", 2, 10)
self:common_add_throwables("blood_transfusion", 1, 0.5)
self:common_add_throwables("wick_mode", 1, 6)
self:common_add_throwables("emergency_requisition", 1, 2)
self:common_add_throwables("auto_inject_super_stimpak", 1, 0.1)
self:common_add_throwables("the_mixtape", 1, 4)
self:common_add_throwables("throwable_trip_mine", 1, 0.1)
self:common_add_throwables("jet", 1, 8)
self:common_add_throwables("whiff", 2, 8)
self:common_add_throwables("lonestar_rage", 0, 5)
self:common_add_throwables("crooks_con", 1, 4)
self:common_add_throwables("crew_synchrony", 1, 12)
self:common_add_throwables("buff_banner", 1, 12)
-- self.values.player.body_armor.dodge[1] = 1 -- Debug always dodgde
-- mx_print_table(self.specialization_descs)
end)
-- Todo make new override for [pd2-lua\lib\managers\menu\skilltreegui.lua]SpecializationTierItem:init the self._desc_string and use new macros
--[[
cooldown_reduction on kill, does not includes the custom cooldown reductions, like on melee or explosive kill
]]
function UpgradesTweakData:common_add_throwables(name_id, cooldown_reduction, duration)
self.values.temporary[name_id] = {
{
cooldown_reduction,
duration,
}
}
self.definitions[name_id] = {
category = "grenade",
}
self.definitions["temporary_"..name_id.."_1"] = {
name_id = "menu_temporary_"..name_id.."_1",
category = "temporary",
upgrade = {
value = 1,
upgrade = name_id,
category = "temporary"
}
}
end
|
return function(ent, args)
if ent.position.x < 0 then
DOSWITCH = true
scripts.systems.money.money.end_raid(true)
local ent = scripts.systems.money.money.get_money_ent()
ent.money.total, ent.money.pocket_treasure = ent.money.total + ent.money.pocket_treasure, 0
end
end |
ngx.header['response'] = ngx.req.get_method() .. '.' .. ngx.var.uri
local config = require "./conf/lua/config_coreadmin"
--local functions
local function isempty(s)
return s == nil or s == ''
end
local redis = require "resty.redis"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local ok, err = red:connect(config.redis.host, config.redis.port)
if not ok then
ngx.say("failed to connect: ", err)
ngx.status = ngx.HTTP_NOT_FOUND
return ngx.exit(ngx.HTTP_NOT_FOUND)
end
if not isempty(config.redis.auth) then
local res, err = red:auth(config.redis.auth)
if not res then
ngx.say("failed to authenticate: ", err)
return
end
end
local cookie_value = ngx.var.cookie_ssid
--CHUA LOGIN
if isempty(cookie_value) then
ngx.status = ngx.HTTP_UNAUTHORIZED --401
return ngx.exit(ngx.HTTP_UNAUTHORIZED )
end
local res, err = red:hmget(cookie_value, 'id', 'username', 'logId', 'isSuperAdmin', 'ipAddress', ngx.req.get_method() .. '.' .. ngx.var.uri)
--Chưa có trong redis:
--Kiem tra SESSION_ID co ton tai khong. res[1]=id
if tostring(res[1])=='userdata: NULL' then
ngx.status = ngx.HTTP_UNAUTHORIZED --401
ngx.header['reLogin']='/pages/v3/login.html'
return ngx.exit(ngx.HTTP_UNAUTHORIZED)
else
ngx.req.set_header("currentUserId", res[1])
ngx.req.set_header("username", res[2])
ngx.req.set_header("logid", res[3])
ngx.req.set_header("isSuperAdmin", res[4])
ngx.req.set_header("ip", res[5])
ngx.req.set_header("apiUrl", res[6])
ngx.req.set_header("apiMethod", ngx.req.get_method())
ngx.var.target = res[6]
end
|
pg = pg or {}
pg.world_goods_data = {
[10101] = {
id = 10101,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2002,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[10102] = {
id = 10102,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2002,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[10201] = {
id = 10201,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2003,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[10301] = {
id = 10301,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2004,
item_type = 12,
frequency = 1,
price_num = 9000,
price_type = 12
},
[10103] = {
id = 10103,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2002,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[10202] = {
id = 10202,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2003,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[10203] = {
id = 10203,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2003,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[10302] = {
id = 10302,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2004,
item_type = 12,
frequency = 1,
price_num = 9000,
price_type = 12
},
[10303] = {
id = 10303,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2004,
item_type = 12,
frequency = 1,
price_num = 9000,
price_type = 12
},
[10401] = {
id = 10401,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2005,
item_type = 12,
frequency = 1,
price_num = 15000,
price_type = 12
},
[10402] = {
id = 10402,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2005,
item_type = 12,
frequency = 1,
price_num = 15000,
price_type = 12
},
[10501] = {
id = 10501,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2006,
item_type = 12,
frequency = 1,
price_num = 30000,
price_type = 12
},
[10304] = {
id = 10304,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2004,
item_type = 12,
frequency = 1,
price_num = 9000,
price_type = 12
},
[10403] = {
id = 10403,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2005,
item_type = 12,
frequency = 1,
price_num = 15000,
price_type = 12
},
[10502] = {
id = 10502,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2006,
item_type = 12,
frequency = 1,
price_num = 30000,
price_type = 12
},
[10503] = {
id = 10503,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2006,
item_type = 12,
frequency = 1,
price_num = 30000,
price_type = 12
},
[11101] = {
id = 11101,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2014,
item_type = 12,
frequency = 1,
price_num = 36000,
price_type = 12
},
[11201] = {
id = 11201,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2015,
item_type = 12,
frequency = 1,
price_num = 60000,
price_type = 12
},
[11301] = {
id = 11301,
priority = 2,
price_id = 100,
item_num = 1,
is_auto_use = 1,
item_id = 2016,
item_type = 12,
frequency = 1,
price_num = 100000,
price_type = 12
},
[20101] = {
id = 20101,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 2,
price_type = 12
},
[20102] = {
id = 20102,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 2,
price_type = 12
},
[20201] = {
id = 20201,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[20202] = {
id = 20202,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[20103] = {
id = 20103,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 2,
price_type = 12
},
[20104] = {
id = 20104,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 5,
price_type = 12
},
[20203] = {
id = 20203,
priority = 4,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[20204] = {
id = 20204,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 25,
price_type = 12
},
[20301] = {
id = 20301,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[20302] = {
id = 20302,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[20501] = {
id = 20501,
priority = 4,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 30915,
item_type = 2,
frequency = 1,
price_num = 300,
price_type = 12
},
[20105] = {
id = 20105,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 5,
price_type = 12
},
[20106] = {
id = 20106,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 5,
price_type = 12
},
[20205] = {
id = 20205,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 25,
price_type = 12
},
[20206] = {
id = 20206,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 25,
price_type = 12
},
[20303] = {
id = 20303,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[20304] = {
id = 20304,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[20401] = {
id = 20401,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 0,
item_id = 30914,
item_type = 2,
frequency = 1,
price_num = 250,
price_type = 12
},
[20502] = {
id = 20502,
priority = 4,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 30915,
item_type = 2,
frequency = 1,
price_num = 300,
price_type = 12
},
[20107] = {
id = 20107,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[20108] = {
id = 20108,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2101,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[20207] = {
id = 20207,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 50,
price_type = 12
},
[20208] = {
id = 20208,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2102,
item_type = 12,
frequency = 1,
price_num = 50,
price_type = 12
},
[20305] = {
id = 20305,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[20306] = {
id = 20306,
priority = 4,
price_id = 101,
item_num = 10,
is_auto_use = 1,
item_id = 2103,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[20402] = {
id = 20402,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 0,
item_id = 30914,
item_type = 2,
frequency = 1,
price_num = 250,
price_type = 12
},
[20403] = {
id = 20403,
priority = 4,
price_id = 101,
item_num = 5,
is_auto_use = 0,
item_id = 30914,
item_type = 2,
frequency = 1,
price_num = 250,
price_type = 12
},
[20503] = {
id = 20503,
priority = 4,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 30915,
item_type = 2,
frequency = 1,
price_num = 300,
price_type = 12
},
[30101] = {
id = 30101,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 251,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[30102] = {
id = 30102,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 251,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[30201] = {
id = 30201,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 2500,
price_type = 12
},
[30103] = {
id = 30103,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 251,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[30202] = {
id = 30202,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 2500,
price_type = 12
},
[30203] = {
id = 30203,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[30204] = {
id = 30204,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 2500,
price_type = 12
},
[30205] = {
id = 30205,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[30301] = {
id = 30301,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 253,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[30206] = {
id = 30206,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 2500,
price_type = 12
},
[30302] = {
id = 30302,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 253,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[30303] = {
id = 30303,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 253,
item_type = 12,
frequency = 1,
price_num = 10000,
price_type = 12
},
[40101] = {
id = 40101,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 201,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[40102] = {
id = 40102,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 201,
item_type = 12,
frequency = 1,
price_num = 450,
price_type = 12
},
[40201] = {
id = 40201,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[40202] = {
id = 40202,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[40301] = {
id = 40301,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 250,
price_type = 12
},
[40203] = {
id = 40203,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[40204] = {
id = 40204,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[40302] = {
id = 40302,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[40303] = {
id = 40303,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[40401] = {
id = 40401,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 750,
price_type = 12
},
[40304] = {
id = 40304,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[40305] = {
id = 40305,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 750,
price_type = 12
},
[40402] = {
id = 40402,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 750,
price_type = 12
},
[40403] = {
id = 40403,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 1500,
price_type = 12
},
[40501] = {
id = 40501,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 205,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[40404] = {
id = 40404,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 2250,
price_type = 12
},
[40405] = {
id = 40405,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 2250,
price_type = 12
},
[40502] = {
id = 40502,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 205,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[40503] = {
id = 40503,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 205,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[40601] = {
id = 40601,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 206,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[50101] = {
id = 50101,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[50102] = {
id = 50102,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[50103] = {
id = 50103,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[50104] = {
id = 50104,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[50105] = {
id = 50105,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[50106] = {
id = 50106,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[50107] = {
id = 50107,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 500,
price_type = 12
},
[50108] = {
id = 50108,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 110,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[60101] = {
id = 60101,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60102] = {
id = 60102,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60201] = {
id = 60201,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60202] = {
id = 60202,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60301] = {
id = 60301,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60302] = {
id = 60302,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60103] = {
id = 60103,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60104] = {
id = 60104,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60203] = {
id = 60203,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60204] = {
id = 60204,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60303] = {
id = 60303,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60304] = {
id = 60304,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60105] = {
id = 60105,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60401] = {
id = 60401,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 304,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[60205] = {
id = 60205,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60501] = {
id = 60501,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 305,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[60305] = {
id = 60305,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60601] = {
id = 60601,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 306,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[60106] = {
id = 60106,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60402] = {
id = 60402,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 304,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[60206] = {
id = 60206,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60502] = {
id = 60502,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 305,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[60306] = {
id = 60306,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 10,
price_type = 12
},
[60602] = {
id = 60602,
priority = 1,
price_id = 101,
item_num = 1,
is_auto_use = 0,
item_id = 306,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[70101] = {
id = 70101,
priority = 2,
price_id = 100,
item_num = 20,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[70102] = {
id = 70102,
priority = 2,
price_id = 100,
item_num = 20,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[70103] = {
id = 70103,
priority = 2,
price_id = 100,
item_num = 50,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[70104] = {
id = 70104,
priority = 2,
price_id = 100,
item_num = 20,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[70105] = {
id = 70105,
priority = 2,
price_id = 100,
item_num = 50,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[70106] = {
id = 70106,
priority = 2,
price_id = 100,
item_num = 100,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 10000,
price_type = 12
},
[70107] = {
id = 70107,
priority = 2,
price_id = 100,
item_num = 50,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 5000,
price_type = 12
},
[70108] = {
id = 70108,
priority = 2,
price_id = 100,
item_num = 100,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 10000,
price_type = 12
},
[70109] = {
id = 70109,
priority = 2,
price_id = 100,
item_num = 200,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 20000,
price_type = 12
},
[70110] = {
id = 70110,
priority = 2,
price_id = 100,
item_num = 100,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 10000,
price_type = 12
},
[70111] = {
id = 70111,
priority = 2,
price_id = 100,
item_num = 200,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 20000,
price_type = 12
},
[70112] = {
id = 70112,
priority = 2,
price_id = 100,
item_num = 500,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 50000,
price_type = 12
},
[80101] = {
id = 80101,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2111,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[80102] = {
id = 80102,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2111,
item_type = 12,
frequency = 1,
price_num = 20,
price_type = 12
},
[80201] = {
id = 80201,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2112,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[80103] = {
id = 80103,
priority = 5,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2111,
item_type = 12,
frequency = 1,
price_num = 40,
price_type = 12
},
[80202] = {
id = 80202,
priority = 5,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2112,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[80104] = {
id = 80104,
priority = 5,
price_id = 101,
item_num = 3,
is_auto_use = 1,
item_id = 2111,
item_type = 12,
frequency = 1,
price_num = 60,
price_type = 12
},
[80203] = {
id = 80203,
priority = 5,
price_id = 101,
item_num = 3,
is_auto_use = 1,
item_id = 2112,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[90101] = {
id = 90101,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90201] = {
id = 90201,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90102] = {
id = 90102,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90202] = {
id = 90202,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90301] = {
id = 90301,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2115,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[90103] = {
id = 90103,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90104] = {
id = 90104,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90203] = {
id = 90203,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90204] = {
id = 90204,
priority = 5,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[90302] = {
id = 90302,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2115,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[90105] = {
id = 90105,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90106] = {
id = 90106,
priority = 5,
price_id = 101,
item_num = 5,
is_auto_use = 1,
item_id = 2113,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[90205] = {
id = 90205,
priority = 5,
price_id = 101,
item_num = 2,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[90206] = {
id = 90206,
priority = 5,
price_id = 101,
item_num = 3,
is_auto_use = 1,
item_id = 2114,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[90303] = {
id = 90303,
priority = 5,
price_id = 101,
item_num = 1,
is_auto_use = 1,
item_id = 2115,
item_type = 12,
frequency = 1,
price_num = 300,
price_type = 12
},
[100101] = {
id = 100101,
priority = 3,
price_id = 101,
item_num = 20,
is_auto_use = 1,
item_id = 2116,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[100102] = {
id = 100102,
priority = 3,
price_id = 101,
item_num = 40,
is_auto_use = 1,
item_id = 2116,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[100201] = {
id = 100201,
priority = 3,
price_id = 101,
item_num = 20,
is_auto_use = 1,
item_id = 2117,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[100202] = {
id = 100202,
priority = 3,
price_id = 101,
item_num = 40,
is_auto_use = 1,
item_id = 2117,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[100301] = {
id = 100301,
priority = 3,
price_id = 101,
item_num = 20,
is_auto_use = 1,
item_id = 2118,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[100302] = {
id = 100302,
priority = 3,
price_id = 101,
item_num = 40,
is_auto_use = 1,
item_id = 2118,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[100401] = {
id = 100401,
priority = 3,
price_id = 101,
item_num = 20,
is_auto_use = 1,
item_id = 2119,
item_type = 12,
frequency = 1,
price_num = 100,
price_type = 12
},
[100402] = {
id = 100402,
priority = 3,
price_id = 101,
item_num = 40,
is_auto_use = 1,
item_id = 2119,
item_type = 12,
frequency = 1,
price_num = 200,
price_type = 12
},
[200101] = {
id = 200101,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 251,
item_type = 12,
frequency = 1,
price_num = 800,
price_type = 12
},
[200102] = {
id = 200102,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 251,
item_type = 12,
frequency = 1,
price_num = 1600,
price_type = 12
},
[200201] = {
id = 200201,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[200202] = {
id = 200202,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 252,
item_type = 12,
frequency = 1,
price_num = 4000,
price_type = 12
},
[200301] = {
id = 200301,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 253,
item_type = 12,
frequency = 1,
price_num = 4000,
price_type = 12
},
[200302] = {
id = 200302,
priority = 1,
price_id = 100,
item_num = 2,
is_auto_use = 0,
item_id = 253,
item_type = 12,
frequency = 1,
price_num = 8000,
price_type = 12
},
[210101] = {
id = 210101,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 201,
item_type = 12,
frequency = 1,
price_num = 600,
price_type = 12
},
[210102] = {
id = 210102,
priority = 1,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 201,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[210201] = {
id = 210201,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 2000,
price_type = 12
},
[210202] = {
id = 210202,
priority = 1,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 202,
item_type = 12,
frequency = 1,
price_num = 10000,
price_type = 12
},
[210301] = {
id = 210301,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 1000,
price_type = 12
},
[210302] = {
id = 210302,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 203,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[210401] = {
id = 210401,
priority = 1,
price_id = 100,
item_num = 1,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 3000,
price_type = 12
},
[210402] = {
id = 210402,
priority = 1,
price_id = 100,
item_num = 3,
is_auto_use = 0,
item_id = 204,
item_type = 12,
frequency = 1,
price_num = 9000,
price_type = 12
},
[220101] = {
id = 220101,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[220102] = {
id = 220102,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 301,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[220201] = {
id = 220201,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[220202] = {
id = 220202,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 302,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[220301] = {
id = 220301,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[220302] = {
id = 220302,
priority = 1,
price_id = 110,
item_num = 1,
is_auto_use = 0,
item_id = 303,
item_type = 12,
frequency = 1,
price_num = 1,
price_type = 12
},
[230101] = {
id = 230101,
priority = 2,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 400,
price_type = 12
},
[230102] = {
id = 230102,
priority = 2,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 400,
price_type = 12
},
[230103] = {
id = 230103,
priority = 2,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 400,
price_type = 12
},
[230104] = {
id = 230104,
priority = 2,
price_id = 100,
item_num = 5,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 400,
price_type = 12
},
[230105] = {
id = 230105,
priority = 2,
price_id = 100,
item_num = 10,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 800,
price_type = 12
},
[230106] = {
id = 230106,
priority = 2,
price_id = 100,
item_num = 10,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 800,
price_type = 12
},
[230107] = {
id = 230107,
priority = 2,
price_id = 100,
item_num = 10,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 800,
price_type = 12
},
[230108] = {
id = 230108,
priority = 2,
price_id = 100,
item_num = 10,
is_auto_use = 0,
item_id = 101,
item_type = 12,
frequency = 1,
price_num = 800,
price_type = 12
},
all = {
10101,
10102,
10201,
10301,
10103,
10202,
10203,
10302,
10303,
10401,
10402,
10501,
10304,
10403,
10502,
10503,
11101,
11201,
11301,
20101,
20102,
20201,
20202,
20103,
20104,
20203,
20204,
20301,
20302,
20501,
20105,
20106,
20205,
20206,
20303,
20304,
20401,
20502,
20107,
20108,
20207,
20208,
20305,
20306,
20402,
20403,
20503,
30101,
30102,
30201,
30103,
30202,
30203,
30204,
30205,
30301,
30206,
30302,
30303,
40101,
40102,
40201,
40202,
40301,
40203,
40204,
40302,
40303,
40401,
40304,
40305,
40402,
40403,
40501,
40404,
40405,
40502,
40503,
40601,
50101,
50102,
50103,
50104,
50105,
50106,
50107,
50108,
60101,
60102,
60201,
60202,
60301,
60302,
60103,
60104,
60203,
60204,
60303,
60304,
60105,
60401,
60205,
60501,
60305,
60601,
60106,
60402,
60206,
60502,
60306,
60602,
70101,
70102,
70103,
70104,
70105,
70106,
70107,
70108,
70109,
70110,
70111,
70112,
80101,
80102,
80201,
80103,
80202,
80104,
80203,
90101,
90201,
90102,
90202,
90301,
90103,
90104,
90203,
90204,
90302,
90105,
90106,
90205,
90206,
90303,
100101,
100102,
100201,
100202,
100301,
100302,
100401,
100402,
200101,
200102,
200201,
200202,
200301,
200302,
210101,
210102,
210201,
210202,
210301,
210302,
210401,
210402,
220101,
220102,
220201,
220202,
220301,
220302,
230101,
230102,
230103,
230104,
230105,
230106,
230107,
230108
}
}
return
|
local lpeg = require'lpeg'
--local pp = require'pretty'
local number = lpeg.R'09' ^ 1 / tonumber
local space = lpeg.P(" ") ^ 0
local pattern = space * number * space * number * space * number
local total = 0
local i = 0
local triangles = {}
for line in io.lines("3.txt") do
i = i + 1
local a, b, c = lpeg.match(pattern, line)
triangles[i] = { a, b, c }
end
for i = 1, #triangles, 3 do
for j = 1, 3 do
local a, b, c = triangles[i][j], triangles[i+1][j], triangles[i+2][j]
if a + b > c and a + c > b and b + c > a then
total = total + 1
end
end
end
print(total)
|
class "BackgroundComponent" {
extends "DisplayComponent",
-- Override
new = function (self, left,right,top,bottom)
self:super(left,right,top,bottom)
self.image = love.graphics.newImage("Assets/background.png")
self.fits = {true, true}
self.scales = {1, 1}
self.offsets = {0, 0}
self.isAligncenter = false
self.colorHSVA = {1,0,1,1}
-- self:setImage("D:/MIDIFall_Project/MIDIFall/Assets/transparent.png")
end,
-- Implement
update = function (self, dt)
end,
-- Implement
draw = function (self, screenWidth,screenHeight)
if not self.enabled then
return
end
-- Find out the display scales of the background image
local scales = {self.scales[1], self.scales[2]}
if self.fits[1] then
scales[1] = screenWidth / self.image:getWidth()
end
if self.fits[2] then
scales[2] = screenHeight / self.image:getHeight()
end
-- Find out the display offsets of the background image
local offsets = {screenWidth*self.offsets[1], screenHeight*self.offsets[2]}
if self.isAligncenter then
offsets[1] = offsets[1] + (screenWidth - scales[1]*self.image:getWidth()) / 2
offsets[2] = offsets[2] + (screenHeight - scales[2]*self.image:getHeight()) / 2
end
-- Draw the background image
love.graphics.setColor(vivid.HSVtoRGB(self.colorHSVA))
love.graphics.draw(self.image, screenWidth*self.x+offsets[1], screenHeight*self.y+offsets[2], 0, scales[1], scales[2])
end,
setImage = function (self, path)
local file = io.open(path, "rb")
local fileData
if file then
fileData = love.filesystem.newFileData(file:read("*a"), "backgroundImageFile")
file:close()
local imageData = love.image.newImageData(fileData)
self.image = love.graphics.newImage(imageData)
end
end,
} |
-- See LICENSE for terms
-- edited from orig func to remove deposits
local function SetSignsVisible(visible)
if visible and not g_SignsVisible then
MapSetEnumFlags(const.efVisible, "map", "BuildingSign", "UnitSign", "ArrowTutorialBase", "SelectionArrow")
g_SignsVisible = true
end
if not visible and g_SignsVisible then
MapClearEnumFlags(const.efVisible, "map", "BuildingSign", "UnitSign", "ArrowTutorialBase", "SelectionArrow")
g_SignsVisible = false
end
end
local mod_EnableMod
local function SetBuildingSigns1()
SetSignsVisible(not mod_EnableMod)
end
local function SetBuildingSigns2()
SetSignsVisible(not g_SignsVisible)
end
-- fired when settings are changed/init
local function ModOptions()
mod_EnableMod = CurrentModOptions:GetProperty("EnableMod")
-- make sure we're ingame
if UICity then
SetBuildingSigns1()
end
end
-- load default/saved settings
OnMsg.ModsReloaded = ModOptions
-- fired when option is changed
function OnMsg.ApplyModOptions(id)
if id == CurrentModId then
ModOptions()
end
end
OnMsg.CityStart = SetBuildingSigns1
OnMsg.LoadGame = SetBuildingSigns1
-- add keybind for toggle
local Actions = ChoGGi.Temp.Actions
Actions[#Actions+1] = {ActionName = T(302535920011687, "Hide Building Signs"),
ActionId = "ChoGGi.HideBuildingSigns.ToggleSigns",
OnAction = function()
SetBuildingSigns2()
end,
ActionShortcut = "Numpad 8",
replace_matching_id = true,
ActionBindable = true,
}
|
map_proto = {
[1] = { name = 4901, map = 1, },
[2] = { name = 4902, map = 3, },
[3] = { name = 4903, map = 3, },
[4] = { name = 4904, map = 3, },
[5] = { name = 4905, map = 3, },
[6] = { name = 4906, map = 3, },
[7] = { name = 4907, map = 3, },
[8] = { name = 4908, map = 3, },
[9] = { name = 4909, map = 3, },
[10] = { name = 4910, map = 3, },
[11] = { name = 4911, map = 3, },
[12] = { name = 4912, map = 3, },
[13] = { name = 4913, map = 3, },
[14] = { name = 4914, map = 3, },
[15] = { name = 4915, map = 3, },
[16] = { name = 4916, map = 3, },
[17] = { name = 4917, map = 3, },
[18] = { name = 4918, map = 3, },
[19] = { name = 4919, map = 3, },
[20] = { name = 4920, map = 3, },
[21] = { name = 4921, map = 3, },
[22] = { name = 4922, map = 3, },
[23] = { name = 4923, map = 3, },
[24] = { name = 4924, map = 3, },
[10001] = { name = 4901, map = 10001, },
[10002] = { name = 4902, map = 10003, },
[10003] = { name = 4903, map = 10003, },
[10004] = { name = 4904, map = 10003, },
[10005] = { name = 4905, map = 10003, },
[10006] = { name = 4906, map = 10003, },
[10007] = { name = 4907, map = 10003, },
[10008] = { name = 4908, map = 10003, },
[10009] = { name = 4909, map = 10003, },
[10010] = { name = 4910, map = 10003, },
[10011] = { name = 4911, map = 10003, },
[10012] = { name = 4912, map = 10003, },
[10013] = { name = 4913, map = 10003, },
[10014] = { name = 4914, map = 10003, },
[10015] = { name = 4915, map = 10003, },
[10016] = { name = 4916, map = 10003, },
[10017] = { name = 4917, map = 10003, },
[10018] = { name = 4918, map = 10003, },
[10019] = { name = 4919, map = 10003, },
[10020] = { name = 4920, map = 10003, },
[10021] = { name = 4921, map = 10003, },
[10022] = { name = 4922, map = 10003, },
[10023] = { name = 4923, map = 10003, },
[10024] = { name = 4924, map = 10003, },
}
return map_proto
|
local queries = require "nvim-treesitter.query"
local M = {}
function M.init()
require("nvim-treesitter").define_modules {
refactor = {
highlight_definitions = {
module_path = "nvim-treesitter-refactor.highlight_definitions",
enable = false,
disable = {},
is_supported = queries.has_locals,
clear_on_cursor_move = true,
},
highlight_current_scope = {
module_path = "nvim-treesitter-refactor.highlight_current_scope",
enable = false,
disable = {},
is_supported = queries.has_locals,
},
smart_rename = {
module_path = "nvim-treesitter-refactor.smart_rename",
enable = false,
disable = {},
is_supported = queries.has_locals,
keymaps = {
smart_rename = "grr",
},
},
navigation = {
module_path = "nvim-treesitter-refactor.navigation",
enable = false,
disable = {},
is_supported = queries.has_locals,
keymaps = {
goto_definition = "gnd",
list_definitions = "gnD",
list_definitions_toc = "gO",
goto_next_usage = "<a-*>",
goto_previous_usage = "<a-#>",
},
},
},
}
end
return M
|
return {'lto','lto'} |
-- Functions:
-------------------------------------------------------
function model.completeDataPartSpecific(data)
if not data.partSpecific then
data.partSpecific={}
end
-- if not data.partSpecific['width'] then
-- data.partSpecific['width']=0.3
-- end
end
-- Additional handles:
-------------------------------------------------------
model.specHandles={}
|
require('nvim-treesitter.configs').setup {
highlight = {
enable = true,
disable = {
'fennel',
},
},
incremental_selection = {
enable = false, -- too much for me!
},
indent = {
enable = true,
},
textobjects = {
select = {
enable = true,
keymaps = {
-- NOTE: 'ib' and 'ab' are reserved for selecting braces.
-- Use 'v' since 'v' is next to 'b' in keyboard and easy to type.
['iv'] = '@block.inner',
['av'] = '@block.outer',
['iC'] = '@call.inner',
['aC'] = '@call.outer',
['ik'] = '@class.inner',
['ak'] = '@class.outer',
['ac'] = '@comment.outer',
-- NOTE: 'i' is mnemonic for 'If'.
['ii'] = '@conditional.inner',
['ai'] = '@conditional.outer',
-- NOTE: Below are supported for very few languages.
-- ['if'] = '@frame.inner',
-- ['af'] = '@frame.outer',
-- NOTE: Use 'm' from 'Method' since 'f' reminds me of 'File'.
['im'] = '@function.inner',
['am'] = '@function.outer',
['il'] = '@loop.inner',
['al'] = '@loop.outer',
['ia'] = '@parameter.inner',
['aa'] = '@parameter.outer',
-- ['in'] = '@scopename.inner', -- NOTE: supported for vary few languages.
['aS'] = '@statement.outer', -- NOTE: 'as' is reserved for sentence.
},
},
swap = {
-- FIXME: It does not work for me.
-- See https://github.com/nvim-treesitter/nvim-treesitter-textobjects/issues/96
enable = false,
},
move = {
enable = true,
set_jumps = true,
goto_next_start = {
[']m'] = '@function.outer',
[']k'] = '@class.outer',
},
goto_next_end = {
[']M'] = '@function.outer',
[']K'] = '@class.outer',
},
goto_previous_start = {
['[m'] = '@function.outer',
['[k'] = '@class.outer',
},
goto_previous_end = {
['[M'] = '@function.outer',
['[K'] = '@class.outer',
},
},
lsp_interop = {
enable = true,
peek_definition_code = {
['<LocalLeader>sm'] = '@function.outer',
['<LocalLeader>sk'] = '@class.outer',
},
},
},
}
|
include("shared.lua")
local lib = include("psychedelics/libs/cl/ents_cl.lua")
local function drawPanel(ent)
-- local pos = ent:LocalToWorld(Vector(18.5,0,28))
-- local pos = ent:LocalToWorld(Vector(18.5,0,24))
local base = ent:GetNWEntity("psychedelicsDoorBase", ent)
local temp = base:GetNWInt("psychedelicsTemp", 22) -- 22C is default room temperature
local tempString = tostring(temp) .. "°"
local tempW, tempH -- width and height for the temperature string
local pos = ent:LocalToWorld(Vector(3, 0, 0))
local ang = ent:LocalToWorldAngles(Angle(0, 90, 90))
cam.Start3D2D(pos, ang, 0.2)
draw.NoTexture() -- fixes material bugs
surface.SetFont("DermaLarge")
surface.SetDrawColor(30, 30, 30)
tempW, tempH = surface.GetTextSize(tempString)
surface.SetTextColor(HSVToColor(180 - (temp * 2), 1, 1))
surface.SetTextPos(-tempW / 2, -tempH / 2)
surface.DrawRect(-20, -15, 40, 30)
surface.DrawText(tempString)
cam.End3D2D()
end
function ENT:Draw() self:DrawModel() end
function ENT:DrawTranslucent(flags)
if (self:GetModel() == "models/props_interiors/refrigeratordoor02a.mdl") and lib.checkDist(self) then
drawPanel(self)
end -- only draws a panel for the upper door
end
|
fx_version 'cerulean'
game 'gta5'
author 'An awesome dude'
description 'An awesome, but short, description'
version '1.0.0'
resource_type 'gametype' { name = 'My awesome game type!' }
client_script 'mymode_client.lua'
|
local K, C = unpack(select(2, ...))
local Module = K:GetModule("Skins")
local _G = _G
local pairs = pairs
local table_insert = table.insert
local hooksecurefunc = _G.hooksecurefunc
local function LoadSpellBookSkin()
local professionTexture = K.GetTexture(C["UITextures"].SkinTextures)
for i = 1, _G.SPELLS_PER_PAGE do
local button = _G["SpellButton" .. i]
local icon = _G["SpellButton" .. i .. "IconTexture"]
local slot = _G["SpellButton" .. i .. "SlotFrame"]
local highlight =_G["SpellButton" .. i .. "Highlight"]
highlight:SetColorTexture(1, 1, 1, 0.3)
highlight:SetAllPoints(icon)
button.EmptySlot:SetTexture("")
button.UnlearnedFrame:SetTexture("")
slot:SetTexture("")
icon:SetTexCoord(K.TexCoords[1], K.TexCoords[2], K.TexCoords[3], K.TexCoords[4])
icon:SetAllPoints()
button:CreateBorder()
if button.SpellHighlightTexture then
K.Flash(button.SpellHighlightTexture, 1, true)
end
if button.shine then
button.shine:ClearAllPoints()
button.shine:SetPoint("TOPLEFT", button, "TOPLEFT", -3, 3)
button.shine:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", 3, -3)
end
end
hooksecurefunc("SpellButton_UpdateButton", function()
for i = 1, _G.SPELLS_PER_PAGE do
local button = _G["SpellButton" .. i]
if button.SpellHighlightTexture then
K.Flash(button.SpellHighlightTexture, 1, true)
end
end
end)
-- Profession Tab
local professionbuttons = {
"PrimaryProfession1SpellButtonTop",
"PrimaryProfession1SpellButtonBottom",
"PrimaryProfession2SpellButtonTop",
"PrimaryProfession2SpellButtonBottom",
"SecondaryProfession1SpellButtonLeft",
"SecondaryProfession1SpellButtonRight",
"SecondaryProfession2SpellButtonLeft",
"SecondaryProfession2SpellButtonRight",
"SecondaryProfession3SpellButtonLeft",
"SecondaryProfession3SpellButtonRight",
}
local professionheaders = {
"PrimaryProfession1",
"PrimaryProfession2",
"SecondaryProfession1",
"SecondaryProfession2",
"SecondaryProfession3",
}
for _, header in pairs(professionheaders) do
_G[header.."Missing"]:SetTextColor(1, 0.8, 0)
_G[header.."Missing"]:SetShadowColor(0, 0, 0)
_G[header.."Missing"]:SetShadowOffset(1, -1)
_G[header].missingText:SetTextColor(.04, .04, .04)
end
for _, button in pairs(professionbuttons) do
local icon = _G[button.."IconTexture"]
local rank = _G[button.."SubSpellName"]
local button = _G[button]
button:StripTextures()
if rank then
rank:SetTextColor(1, 1, 1)
end
button:GetCheckedTexture():SetColorTexture(0, 1, 0, 0.3)
button:GetCheckedTexture():SetPoint("TOPLEFT", button, 4, -4)
button:GetCheckedTexture():SetPoint("BOTTOMRIGHT", button, -4, 4)
button.cooldown:SetPoint("TOPLEFT", button, 5, -5)
button.cooldown:SetPoint("BOTTOMRIGHT", button, -5, 5)
if icon then
icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
icon:ClearAllPoints()
icon:SetPoint("TOPLEFT", 3, -3)
icon:SetPoint("BOTTOMRIGHT", -3, 3)
if not button.Backdrop then
button:CreateBackdrop()
button.Backdrop:SetFrameLevel(button:GetFrameLevel())
button.Backdrop:SetAllPoints(icon)
end
end
end
hooksecurefunc("UpdateProfessionButton", function()
for _, button in pairs(professionbuttons) do
local button = _G[button]
button:GetHighlightTexture():SetPoint("TOPLEFT", button, 3, -3)
button:GetHighlightTexture():SetPoint("BOTTOMRIGHT", button, -3, 3)
end
end)
local professionstatusbars = {
"PrimaryProfession1StatusBar",
"PrimaryProfession2StatusBar",
"SecondaryProfession1StatusBar",
"SecondaryProfession2StatusBar",
"SecondaryProfession3StatusBar",
}
for _, statusbar in pairs(professionstatusbars) do
local statusbar = _G[statusbar]
statusbar:StripTextures()
statusbar:SetStatusBarTexture(professionTexture)
statusbar:SetStatusBarColor(0, 0.8, 0)
statusbar:CreateBorder()
statusbar.rankText:ClearAllPoints()
statusbar.rankText:SetPoint("CENTER")
end
end
table_insert(Module.SkinFuncs["KkthnxUI"], LoadSpellBookSkin) |
--[[
定义大厅用到的协议命令字
]]
local CMD = {};
---客户端发送命令到服务器
CMD.C2S = {
HALL_REQUEST = 0xEEEF, -- RPC请求
HEART_REQUEST = 0x2008, -- 心跳
IM_REQUEST = 0xEEF0, -- IM消息
MATCH_REQUEST = 0xEEEC, -- 比赛消息
};
---服务器发送命令到客户端,协议都是双数
CMD.S2C = {
HALL_RESPONSE = 0xEEEF, -- 大厅和后端交互的rpc消息
HEART_RESPONSE = 0x600D, -- 心跳响应消息
IM_RESPONSE = 0xEEF0, -- IM消息
MATCH_RESPONSE = 0xEEEC, -- 比赛消息
};
-- ingonre:ture,收到socket消息不入队列,收到即广播;false:收到消息后先压入消息队列中
CMD.op = {
[CMD.S2C.HEART_RESPONSE] = {ingnore = true};
};
return CMD; |
eHelicopter_announcers = eHelicopter_announcers or {}
--[[
eHelicopter_announcers["name of announcer"] = {
["Lines"] = {
["lineID1"] = {0, "variation1"},
-- For the sake of organization It is recommended you write out some of the spoken audio for "LineID"
-- The first entry within each line is the delay added as it is spoken, the second is the sound file
-- File names have to match scripted sounds found in sounds_EHE.txt for those scripts to be loaded
} }
]]
eHelicopter_announcers["Raven Male"] = {
["Lines"] = {
["PleaseReturnToYourHomes"] = {6500, "eHeli_lineM_1"},
["TheSituationIsUnderControl"] = {6500, "eHeli_lineM_2"},
["ThisAreaIsNowInQuarantine"] = {7000, "eHeli_lineM_3"},
["DoNotTryToLeaveTheArea"] = {6500, "eHeli_lineM_5"},
["LockAllEntrances"] = {7000, "eHeli_lineM_7"},
["AvoidContact"] = {6500, "eHeli_lineM_8"},
["DoNotTryToReachOut"] = {7000, "eHeli_lineM_9"},
["AnyCriminalActivity"] = {8500, "eHeli_lineM_10"},
["AnyPersonsTryingToLeave"] = {8500, "eHeli_lineM_6"},
} }
eHelicopter_announcers["Gabby Female"] = {
["Lines"] = {
["PleaseReturnToYourHomes"] = {5750, "eHeli_lineF_1"},
["TheSituationIsUnderControl"] = {6200, "eHeli_lineF_2"},
["ThisAreaIsNowInQuarantine"] = {6500, "eHeli_lineF_3"},
["DoNotTryToLeaveTheArea"] = {6500, "eHeli_lineF_5"},
["LockAllEntrances"] = {6500, "eHeli_lineF_7"},
["AvoidContact"] = {5750, "eHeli_lineF_8"},
["DoNotTryToReachOut"] = {6750, "eHeli_lineF_9"},
["AnyCriminalActivity"] = {8750, "eHeli_lineF_10"},
["AnyPersonsTryingToLeave"] = {7500, "eHeli_lineF_6"},
} }
eHelicopter_announcers["Jade Male A"] = {
["LineCount"] = 0,
["Lines"] = {
["ThisAreaIsUnderQuarantine"] = {7500, "eHeli_Jade_1a"},
["ForTheSafetyOfYourSelf"] = {8500, "eHeli_Jade_2a"},
["RepeatedAttemptsAtBreaching"] = {7250, "eHeli_Jade_3a"},
} }
eHelicopter_announcers["Jade Male B"] = {
["Lines"] = {
["ThisAreaIsUnderQuarantine"] = {8500, "eHeli_Jade_1b"},
["ForTheSafetyOfYourSelf"] = {9500, "eHeli_Jade_2b"},
["RepeatedAttemptsAtBreaching"] = {7250, "eHeli_Jade_3b"},
} }
eHelicopter_announcers["Jade Male C"] = {
["Lines"] = {
["ThisAreaIsUnderQuarantine"] = {8500, "eHeli_Jade_1c"},
["ForTheSafetyOfYourSelf"] = {9500, "eHeli_Jade_2c"},
["RepeatedAttemptsAtBreaching"] = {7250, "eHeli_Jade_3c"},
} }
eHelicopter_announcers["Police"] = {
["LeaveOutOfRandomSelection"] = true,
["Lines"] = {
["PoliceLines"] = {8500, "eHeli_police_lines"},
} }
|
--[[
Name: gui/pages/settingsPage.lua
Description: Program the players page
Author: misrepresenting
]]
local smoothScroll, colorPicker, onClick, singleSearch, blink do
local helpers = import('gui/helpers')
smoothScroll, colorPicker, onClick, singleSearch, blink = helpers.smoothScroll, helpers.colorPicker, helpers.onClick, helpers.singleSearch, helpers.blink
end
local settings = import('settings')
local tween = import('utils').tween
local gui = import('storage').gui
local newColor = Color3.new
local fromRGB = Color3.fromRGB
local barColor, textColor = newColor(1, 1, 1), newColor(1, 1, 1)
local gsub, format = string.gsub, string.format
local floor = math.floor
local commandBar = gui.CommandBar
local main = gui.MainDragFrame.Main
local settingsPage = main.Pages.Settings.ScrollingFrame
local settingsBarColor = settingsPage.CommandBarColor
local settingsTextColor = settingsPage.TextColor
local settingsEvents = settingsPage.Events
local plugins = settingsPage.Plugins
local loadedPlugins = settingsPage.LoadedPlugins
local greenColor = fromRGB(53, 211, 56)
smoothScroll(settingsPage, 0.14)
onClick(settingsBarColor.ApplyColor, 'BackgroundColor3')
onClick(settingsTextColor.ApplyColor, 'BackgroundColor3')
colorPicker(settingsBarColor.ColorPicker, function(color)
settingsBarColor.Color.Display.BackgroundColor3 = color
barColor = color
end)
colorPicker(settingsTextColor.ColorPicker, function(color)
settingsTextColor.Color.Display.BackgroundColor3 = color
textColor = color
end)
connect(settingsBarColor.ApplyColor.MouseButton1Click, function()
local colorTable = settings.barColor
colorTable[1] = floor(barColor.R * 255)
colorTable[2] = floor(barColor.G * 255)
colorTable[3] = floor(barColor.B * 255)
commandBar.BackgroundColor3 = barColor
end)
connect(settingsTextColor.ApplyColor.MouseButton1Click, function()
local colorTable = settings.textColor
local oldColor = fromRGB(unpack(settings.textColor))
colorTable[1] = floor(textColor.R * 255)
colorTable[2] = floor(textColor.G * 255)
colorTable[3] = floor(textColor.B * 255)
local color = fromRGB(unpack(colorTable))
local colorize = format('rgb(%s,%s,%s)', unpack(colorTable))
for _, v in ipairs(main:GetDescendants()) do
if v.ClassName == 'TextLabel' then
if v.RichText then
v.Text = gsub(v.Text, 'rgb%(%d+,%d+,%d+%)', colorize)
elseif v.TextColor3 == oldColor then
v.TextColor3 = color
end
end
end
main.Title.TitleButton.Text = colorize('Tohru')..' Admin'
end)
connect(plugins.SearchBar.SearchFrame.Search:GetPropertyChangedSignal('Text'), function()
local query = plugins.SearchBar.SearchFrame.Search.Text
for _, v in ipairs(plugins.ScrollingFrame:GetChildren()) do
if v.ClassName ~= 'UIListLayout' then
singleSearch(v, v.Title, query)
end
end
end)
connect(loadedPlugins.SearchBar.SearchFrame.Search:GetPropertyChangedSignal('Text'), function()
local query = loadedPlugins.SearchBar.SearchFrame.Search.Text
for _,v in ipairs(loadedPlugins.ScrollingFrame:GetChildren()) do
if v.ClassName ~= 'UIListLayout' then
singleSearch(v, v.Title, query)
end
end
end)
local eventMenu = settingsEvents.MainFrame.Selection
local eventPages = settingsEvents.MainFrame.CommandsScrollingFrame
local pageLayout = eventPages.UIPageLayout
local textGoal = {}
local tweenPage = function(page, transparency)
textGoal.TextTransparency = transparency
tween(eventMenu[page.Name], 'Sine', 'Out', 0.25, textGoal)
end
for _, v in ipairs(eventMenu:GetChildren()) do
if v.ClassName ~= 'UIListLayout' then
local clone = settingsEvents.CommandsFrame:Clone()
onClick(clone.ButtonFrame.AddCommand, 'BackgroundColor3')
connect(clone.ButtonFrame.AddCommand.MouseButton1Click, function()
local commandClone = settingsEvents.Command:Clone()
onClick(commandClone.Delete, 'TextColor3')
connect(commandClone.CommandName.FocusLost, function()
print(commandClone.CommandName.Text)
blink(commandClone.CommandName, 'TextColor3', greenColor)
end)
connect(commandClone.Delete.MouseButton1Click, function()
commandClone:Destroy()
end)
commandClone.Visible = true
commandClone.Parent = clone
end)
clone.Name = v.Name
clone.Visible = true
clone.Parent = eventPages
connect(v.MouseButton1Click, function()
local currentPage = pageLayout.CurrentPage
local page = eventPages[v.Name]
pageLayout:JumpTo(page)
if eventMenu:FindFirstChild(currentPage.Name) then
tweenPage(currentPage, 0.5)
end
tweenPage(page, 0)
end)
connect(v.MouseEnter, function()
local page = eventPages[v.Name]
if pageLayout.CurrentPage ~= page then
tweenPage(page, 0.3)
end
end)
connect(v.MouseLeave, function()
local page = eventPages[v.Name]
if pageLayout.CurrentPage ~= page then
tweenPage(page, 0.5)
end
end)
end
end
return settingsPage |
#!/usr/bin/env tarantool
box.cfg({
listen = os.getenv("LISTEN"),
memtx_allocator = os.getenv("MEMTX_ALLOCATOR")
})
require('console').listen(os.getenv('ADMIN'))
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
PANEL_TYPE_SETTINGS = 1
PANEL_TYPE_CONTROLS = 2
ZO_KeyboardOptions = ZO_SharedOptions:Subclass()
function ZO_KeyboardOptions:Initialize(control)
ZO_SharedOptions.Initialize(self)
self.currentPanelId = 100 -- must be higher than total EsoGameDataEnums::SettingSystemPanel
internalassert(self.currentPanelId > SETTING_PANEL_MAX_VALUE)
self.control = control
self.colorOptionHighlight = control:GetNamedChild("Options_Color_SharedHighlight")
self.emptyPanelLabel = control:GetNamedChild("EmptyPanelLabel")
self.loadingControl = control:GetNamedChild("Loading")
OPTIONS_WINDOW_FRAGMENT = ZO_FadeSceneFragment:New(control)
OPTIONS_WINDOW_FRAGMENT:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
RefreshSettings()
self:UpdateAllPanelOptions(SAVE_CURRENT_VALUES)
control:GetNamedChild("ApplyButton"):SetHidden(true)
PushActionLayerByName("OptionsWindow")
elseif newState == SCENE_FRAGMENT_HIDING then
SetCameraOptionsPreviewModeEnabled(false, CAMERA_OPTIONS_PREVIEW_NONE)
RemoveActionLayerByName("OptionsWindow")
self:SaveCachedSettings()
elseif newState == SCENE_FRAGMENT_HIDDEN then
-- We may hide this scene while one of these panels is active, and disabling share features.
-- To undo that, just re-enable them here. This assumes that there aren't multiple reasons to disable share features.
if DoesPlatformSupportDisablingShareFeatures() and ZO_SharedOptions.DoesPanelDisableShareFeatures(self.currentPanel) then
EnableShareFeatures()
end
end
end)
ZO_ReanchorControlForLeftSidePanel(control)
CALLBACK_MANAGER:RegisterCallback("OnEditAccountEmailKeyboardDialogClosed", function() self:UpdatePanelVisibility(self.currentPanel) end)
local function OnDeferredSettingRequestCompleted(eventId, system, settingId, success, result)
if OPTIONS_WINDOW_FRAGMENT:IsShowing() and not self:AreDeferredSettingsForPanelLoading(self.currentPanel) then
if system == SETTING_TYPE_ACCOUNT and settingId == ACCOUNT_SETTING_ACCOUNT_EMAIL and result == ACCOUNT_EMAIL_REQUEST_RESULT_SUCCESS_EMAIL_UPDATED then
ZO_Dialogs_ShowPlatformDialog("ACCOUNT_MANAGEMENT_EMAIL_CHANGED")
end
self:ShowPanel(self.currentPanel)
end
end
EVENT_MANAGER:RegisterForEvent("KeyboardOptions", EVENT_DEFERRED_SETTING_REQUEST_COMPLETED, OnDeferredSettingRequestCompleted)
end
function ZO_KeyboardOptions:AddUserPanel(panelIdOrString, panelName, panelType, visible)
panelType = panelType or PANEL_TYPE_SETTINGS
local id = panelIdOrString
if type(panelIdOrString) == "string" then
id = self.currentPanelId
_G[panelIdOrString] = id
self.currentPanelId = self.currentPanelId + 1
end
self.panelNames[id] = panelName
-- SelectionCallback calls expect to place in a control as the first argument even if not used by this callback.
local callback = function(optionButtonControl, anchorFunction)
if anchorFunction then
anchorFunction(self.control)
else
ZO_ReanchorControlForLeftSidePanel(self.control)
end
SCENE_MANAGER:AddFragment(OPTIONS_WINDOW_FRAGMENT)
self:ChangePanels(id)
end
local unselectedCallback = function()
SCENE_MANAGER:RemoveFragment(OPTIONS_WINDOW_FRAGMENT)
SetCameraOptionsPreviewModeEnabled(false, CAMERA_OPTIONS_PREVIEW_NONE)
end
local panelData =
{
name = panelName,
visible = visible,
callback = callback,
unselectedCallback = unselectedCallback
}
if panelType == PANEL_TYPE_SETTINGS then
ZO_GameMenu_AddSettingPanel(panelData)
else
ZO_GameMenu_AddControlsPanel(panelData)
end
end
function ZO_KeyboardOptions:InitializeControl(control)
local data = control.data
local IS_KEYBOARD_CONTROL = true
local USE_SELECTED = nil
ZO_SharedOptions.InitializeControl(self, control, USE_SELECTED, IS_KEYBOARD_CONTROL)
-- Catch events...callbacks set in the xml
if data.eventCallbacks then
for event, callback in pairs(data.eventCallbacks) do
CALLBACK_MANAGER:RegisterCallback(event, callback, control)
end
end
local settingsScrollChild = self.control:GetNamedChild("SettingsScrollChild")
control:SetParent(settingsScrollChild)
-- Put the control in the panel table
if data.panel then
-- Panel doesn't exist yet, so create it
if not self.controlTable[data.panel] then
self.controlTable[data.panel] = {}
end
-- Add the control to the right panel list
table.insert(self.controlTable[data.panel], control)
-- Update visible state
control:SetHidden(not (data.panel == self.currentPanel))
end
ZO_Options_SetOptionActive(control)
end
function ZO_KeyboardOptions:ChangePanels(panelId)
-- Hide the old panel
if self.currentPanel then
local oldPanel = self.controlTable[self.currentPanel]
if oldPanel then
for index = 1, #oldPanel do
local control = oldPanel[index]
control:SetHidden(true)
end
end
end
self.currentPanel = panelId
local panelName = self.panelNames[panelId]
self.control:GetNamedChild("Title"):SetText(panelName)
self.emptyPanelLabel:SetText(zo_strformat(SI_INTERFACE_OPTIONS_SETTINGS_PANEL_UNAVAILABLE, panelName))
self.emptyPanelLabel:SetHidden(true)
-- Determine if the panel requires deferred loading
local readyToShowPanel = true
if self:PanelRequiresDeferredLoading(panelId) then
local isDeferredLoading = self:RequestLoadDeferredSettingsForPanel(panelId)
if isDeferredLoading then
self.loadingControl:Show()
readyToShowPanel = false
end
end
if readyToShowPanel then
self:ShowPanel(panelId)
end
end
function ZO_KeyboardOptions:PanelRequiresDeferredLoading(panelId)
local panelControls = self.controlTable[panelId]
if panelControls then
for i, control in ipairs(panelControls) do
local data = control.data
if IsSettingDeferred(data.system, data.settingId) then
return true
end
end
end
return false
end
function ZO_KeyboardOptions:AreDeferredSettingsForPanelLoading(panelId)
local panelControls = self.controlTable[panelId]
for i, control in ipairs(panelControls) do
local data = control.data
if IsSettingDeferred(data.system, data.settingId) and IsDeferredSettingLoading(data.system, data.settingId) then
return true
end
end
return false
end
function ZO_KeyboardOptions:RequestLoadDeferredSettingsForPanel(panelId)
local isDeferredLoading = false
local panelControls = self.controlTable[panelId]
for i, control in ipairs(panelControls) do
local data = control.data
if IsSettingDeferred(data.system, data.settingId) then
RequestLoadDeferredSetting(data.system, data.settingId)
isDeferredLoading = true
end
end
return isDeferredLoading
end
function ZO_KeyboardOptions:ShowPanel(panelId)
if DoesPlatformSupportDisablingShareFeatures() and ZO_SharedOptions.DoesPanelDisableShareFeatures(panelId) then
DisableShareFeatures()
end
self.loadingControl:Hide()
-- Show the new panel
local cameraPreviewMode = panelId == SETTING_PANEL_CAMERA
SetCameraOptionsPreviewModeEnabled(cameraPreviewMode, CAMERA_OPTIONS_PREVIEW_NONE)
self:UpdateCurrentPanelOptions(DONT_SAVE_CURRENT_VALUES)
self:UpdatePanelVisibility(panelId)
self.control:GetNamedChild("ToggleFirstPersonButton"):SetHidden(panelId ~= SETTING_PANEL_CAMERA) -- only in camera panel
self.control:GetNamedChild("ResetToDefaultButton"):SetHidden(panelId == SETTING_PANEL_ACCOUNT) -- everywhere but account panel
ZO_Scroll_ResetToTop(self.control:GetNamedChild("Settings"))
self.currentPanel = panelId
end
function ZO_KeyboardOptions:UpdatePanelVisibilityIfShowing(panelId)
if self.currentPanel == panelId then
self:UpdatePanelVisibility(panelId)
end
end
local function IsSettingVisible(data)
local isVisible = data.visible == nil or data.visible
if type(isVisible) == "function" then
isVisible = isVisible()
end
if isVisible and data.system and data.settingId then
if IsSettingDeferred(data.system, data.settingId) and not IsDeferredSettingLoaded(data.system, data.settingId) then
isVisible = false
end
end
return isVisible
end
function ZO_KeyboardOptions:UpdatePanelVisibility(panelId)
local panelControls = self.controlTable[panelId]
if panelControls then
-- Determine the visibility of each control on the panel
-- Since the controls are also headers and the like, we need to check if any
-- settings controls are showing so we don't end up showing just headers
local hasAnyVisibleSetting = false
for index, control in ipairs(panelControls) do
local data = control.data
local isVisible = IsSettingVisible(data)
control:SetHidden(not isVisible)
if isVisible and data.system ~= nil then
hasAnyVisibleSetting = true
end
end
if hasAnyVisibleSetting then
-- Set anchors in separate loop in case controls in panel are not processed in the order they appear on the screen.
for index, control in ipairs(panelControls) do
local isValid, point, relTo, relPoint, offsetX, offsetY = control:GetAnchor(0)
-- If the previous element can be dynamically hidden, then we need to update our anchors to reflect its hidden state
if isValid and relTo and relTo.data and relTo.data.visible ~= nil then
-- TODO: headers are still visible, even when every setting
-- under that header isn't. We should keep track when a setting is
-- visible underneath a header, and then for any header with 0
-- visible settings, we should mark them as not visible
-- like any other setting control.
if not control.originalPoint then
control.originalOffsetX = offsetX
control.originalOffsetY = offsetY
control.originalPoint = point
control.originalRelativePoint = relPoint
end
control:ClearAnchors()
if relTo:IsHidden() then
control:SetAnchor(TOPLEFT, relTo, TOPLEFT, 0, 0)
else
control:SetAnchor(control.originalPoint, relTo, control.originalRelativePoint, control.originalOffsetX, control.originalOffsetY)
end
end
end
end
self.emptyPanelLabel:SetHidden(hasAnyVisibleSetting)
self.control:GetNamedChild("Settings"):SetHidden(not hasAnyVisibleSetting)
else
self.emptyPanelLabel:SetHidden(false)
end
end
function ZO_KeyboardOptions:ApplySettings(control)
ApplySettings()
self.control:GetNamedChild("ApplyButton"):SetHidden(true)
-- Update the panel settings with the new values (may have changed if they are tied to another setting that changed...e.g. ui scale)
self:UpdateAllPanelOptions(SAVE_CURRENT_VALUES)
end
function ZO_KeyboardOptions:EnableApplyButton()
self.control:GetNamedChild("ApplyButton"):SetHidden(false)
end
function ZO_KeyboardOptions:LoadAllDefaults()
local controls = self.controlTable[self.currentPanel]
if controls then
for index, control in pairs(controls) do
ZO_SharedOptions.LoadDefaults(self, control, control.data)
end
self:UpdateCurrentPanelOptions(DONT_SAVE_CURRENT_VALUES)
end
end
function ZO_KeyboardOptions:UpdatePanelOptions(panelIndex, saveOptions)
local controls = self.controlTable[panelIndex]
if controls then
for index, control in pairs(controls) do
local data = control.data
if self:IsControlTypeAnOption(data) then
local value = ZO_Options_UpdateOption(control)
if saveOptions == SAVE_CURRENT_VALUES then
data.value = value -- Save the values (can't click cancel to restore old values after this)
end
elseif data.controlType == OPTIONS_CUSTOM then
if data.customSetupFunction then
data.customSetupFunction(control)
end
end
end
end
end
function ZO_KeyboardOptions:UpdateCurrentPanelOptions(saveOptions)
self:UpdatePanelOptions(self.currentPanel, saveOptions)
end
function ZO_KeyboardOptions:GetColorOptionHighlight()
return self.colorOptionHighlight
end
-- Pass SAVE_CURRENT_VALUES in the first parameter to save the updated values (can't click cancel to restore afterwards).
-- Pass DONT_SAVE_CURRENT_VALUES to update the values, but not save them (cancel will restore the previous values).
function ZO_KeyboardOptions:UpdateAllPanelOptions(saveOptions)
for index in pairs(self.controlTable) do
self:UpdatePanelOptions(index, saveOptions)
end
end
function ZO_KeyboardOptions:SetSectionTitleData(control, panel, text)
control.data =
{
panel = panel,
controlType = OPTIONS_SECTION_TITLE,
text = text,
}
end
function ZO_Options_Keyboard_OnInitialize(control)
KEYBOARD_OPTIONS = ZO_KeyboardOptions:New(control)
SYSTEMS:RegisterKeyboardObject("options", KEYBOARD_OPTIONS)
end
--keep this around for backwards compatibility
function ZO_OptionsWindow_InitializeControl(control)
KEYBOARD_OPTIONS:InitializeControl(control)
end
function ZO_OptionsWindow_ApplySettings(control)
KEYBOARD_OPTIONS:ApplySettings(control)
end
function ZO_OptionsWindow_ToggleFirstPerson(control)
ToggleGameCameraFirstPerson()
end
function ZO_OptionsWindow_AddUserPanel(panelIdString, panelName, panelType)
KEYBOARD_OPTIONS:AddUserPanel(panelIdString, panelName, panelType)
end
|
if not pcall(require, 'telescope') then
return
end
function ts_map(key, picker_f)
local rhs = string.format(":lua require'plugins.telescope.pickers'.%s()<CR>", picker_f)
local opts = {
noremap = true,
silent = true,
}
vim.api.nvim_set_keymap('n', key, rhs, opts)
-- vim.api.nvim_buf_set_keymap(0, 'n', key, rhs, opts)
end
-- Navigation:
-- ts_map('<Leader>k', 'moveuo')
-- Lsp:
ts_map('<Leader>cr', 'lsp_references')
ts_map('<Leader>ca', 'lsp_code_actions')
ts_map('<Leader>cd', 'lsp_definitions')
ts_map('<Leader>ci', 'lsp_implementations')
ts_map('<Leader>cd', 'lsp_document_symbols')
ts_map('<Leader>cw', 'lsp_workspace_symbols')
ts_map('<Leader>cD', 'lsp_diagnostics')
-- Files:
ts_map('<Leader>ff', 'find_files')
ts_map('<Leader>fr', 'find_recent')
ts_map('<Leader>fg', 'git_files')
ts_map('<Leader>fw', 'grep_word') -- Grep file in cwp
ts_map('<Leader>fl', 'live_grep') -- Grep in files in cwp
ts_map('<Leader>fe', 'file_browser')
-- NVim
ts_map('<Leader>fd', 'dotfiles')
ts_map('<Leader>fn', 'neovim_config')
ts_map('<Leader>fb', 'buffers')
ts_map('<Leader>fh', 'help_tags')
-- Git:
ts_map('<Leader>fs', 'git_status')
-- Misc:
vim.api.nvim_set_keymap('n', '<Leader>fm', [[:lua require'telescope.builtin'.keymaps()<CR>]], {})
|
--[[ ============================================================================================================
Author: Rook
Date: February 4, 2015
Called when the unit lands an attack on a target. Applies the modifier so long as the target is not a structure.
Additional parameters: keys.ColdDurationMelee and keys.ColdDurationRanged
================================================================================================================= ]]
function modifier_item_skadi_datadriven_on_orb_impact(keys)
if keys.target.GetInvulnCount == nil then
if keys.caster:IsRangedAttacker() then
keys.ability:ApplyDataDrivenModifier(keys.caster, keys.target, "modifier_item_skadi_datadriven_cold_attack", {duration = keys.ColdDurationRanged})
else --The caster is melee.
keys.ability:ApplyDataDrivenModifier(keys.caster, keys.target, "modifier_item_skadi_datadriven_cold_attack", {duration = keys.ColdDurationMelee})
end
end
end |
local helpers = {}
local npairs=require('nvim-autopairs')
npairs.setup()
local eq = assert.are.same
_G.npairs = npairs;
vim.api.nvim_set_keymap('i' , '<CR>','v:lua.npairs.check_break_line_char()', {expr = true , noremap = true})
function helpers.feed(text, feed_opts)
feed_opts = feed_opts or 'n'
local to_feed = vim.api.nvim_replace_termcodes(text, true, false, true)
vim.api.nvim_feedkeys(to_feed, feed_opts, true)
end
function helpers.insert(text)
helpers.feed('i' .. text, 'x')
end
local data = {
{
name = "add normal bracket" ,
key = [[{]],
before = [[aaaa| ]],
after = [[aaaa{|} ]]
},
{
name = "add normal bracket" ,
key = [[(]],
before = [[aaaa| ]],
after = [[aaaa(|) ]]
},
{
name = "add normal quote" ,
key = [["]],
before = [[aa| aa]],
after = [[aa"|" aa]]
},
{
name = "don't add single quote with previous alphabet char" ,
key = [[']],
before = [[aa| aa]],
after = [[aa'| aa]]
},
{
name = "don't add single quote on end line",
key = [[<right>']],
before = [[c aa|]],
after = [[c aa'|]]
},
{
name = "don't add quote after alphabet char" ,
key = [["]],
before = [[aa |aa]],
after = [[aa "|aa]]
},
{
name = "don't add pair after alphabet char" ,
key = [[(]],
before = [[aa |aa]],
after = [[aa (|aa]]
},
{
name = "move right end line " ,
key = [["]],
before = [[aaaa|"]],
after = [[aaaa"|]]
},
{
name = "move right when inside quote" ,
key = [["]],
before = [[("abcd|")]],
after = [[("abcd"|)]]
},
{
name = "move right when inside grave with special slash" ,
key = [[`]],
before = [[(`abcd\"|`)]],
after = [[(`abcd\"`|)]]
},
{
name = "move right when inside quote with special slash" ,
key = [["]],
before = [[("abcd\"|")]],
after = [[("abcd\""|)]]
},
{
name = "move right when inside single quote with special slash",
filetype="javascript",
key = [[']],
before = [[nvim_set_var('test_thing|')]],
after = [[nvim_set_var('test_thing'|)]]
},
{
name = "breakline on {" ,
filetype="javascript",
key = [[<cr>]],
before = [[a{|}]],
after = [[}]]
},
{
name = "breakline on (" ,
filetype="javascript",
key = [[<cr>]],
before = [[a(|)]],
after = [[)]]
},
{
name = "breakline on ]" ,
filetype="javascript",
key = [[<cr>]],
before = [[a[|] ]],
after = "] "
},
{
name = "breakline on < html" ,
filetype="html",
key = [[<cr>]],
before = [[<div>|</div>]],
after = [[</div>]]
}
}
local run_data = {}
local isOnly = false
for _, value in pairs(data) do
if value.only == true then
table.insert(run_data, value)
isOnly = true
break
end
end
if #run_data == 0 then run_data = data end
local function Test(test_data)
for _, value in pairs(test_data) do
it("test "..value.name, function()
local before = string.gsub(value.before , '%|' , "")
local after = string.gsub(value.after , '%|' , "")
local p_before = string.find(value.before , '%|')
local p_after = string.find(value.after , '%|')
local line = 1
if value.filetype ~= nil then
vim.bo.filetype = value.filetype
else
vim.bo.filetype = "text"
end
vim.fn.setline(line , before)
vim.fn.setpos('.' ,{0 , line , p_before , 0})
helpers.insert(value.key)
helpers.feed("<esc>")
local result = vim.fn.getline(line)
local pos = vim.fn.getpos('.')
if value.key ~= '<cr>' then
eq(p_after , pos[3]+ 1 , "\n\n pos error: " .. value.name .. "\n")
eq(after, result , "\n\n text error: " .. value.name .. "\n")
else
local line2 = vim.fn.getline(line + 2)
eq(line + 1, pos[2], '\n\n breakline error:' .. value.name .. "\n")
eq(after, line2 , "\n\n text error: " .. value.name .. "\n")
vim.fn.setline(line, '')
vim.fn.setline(line+ 1, '')
vim.fn.setline(line+ 2, '')
end
end)
end
end
describe('autopairs ', function()
Test(run_data)
run_data = {
{
name = "nil breaklin_file_type " ,
filetype="javascript",
key = [[<cr>]],
before = [[a[|] ]],
after = "] "
},
}
npairs.setup({
break_line_filetype = nil
})
Test(run_data)
run_data = {
{
name = "regex file tye" ,
filetype="javascript",
key = [[<cr>]],
before = [[a[|] ]],
after = "] "
},
}
npairs.setup({
break_line_filetype ={"java.*"}
})
Test(run_data)
npairs.setup({
ignored_next_char = "%w" -- default
})
Test({
{
name = "don't add pair if next char is aplhanumeric",
key = [[(]],
before = [[|foo ]],
after = [[(|foo ]]
},
{
name = "add pair if next char is non-alphanumeric",
key = [[{]],
before = [[|.foo ]],
after = [[{|}.foo ]]
},
})
npairs.setup({
ignored_next_char = "[%w%.]" -- alphanumeric and `.`
})
Test({
{
name = "don't add pair if next char is .",
key = [[(]],
before = [[|.foo ]],
after = [[(|.foo ]]
},
{
name = "add pair if next char is +",
key = [[{]],
before = [[|+foo ]],
after = [[{|}+foo ]]
},
})
end)
|
local tArgs = { ... }
if #tArgs == 0 then
print( "Usage: display <file>" )
return
end
local sPath = shell.resolve( tArgs[1] )
if fs.exists( sPath ) and fs.isDir( sPath ) then
printError( "Cannot display a directory." )
return
end
if fs.exists( sPath ) then
paintutils.drawImage(paintutils.loadImage(sPath), 1, 1)
else
printError( "file not found" )
return
end
while true do
local event = os.pullEvent()
if event == "mouse_click" or event == "key" or event == "paste" or event == "char" then
term.clear()
term.setCursorPos(1,1)
return
end
end
|
if (GetLocale() == "zhCN") then
BF_TEXT_UPDATETOVERSION = "|CFFFFD000 您的大脚版本已过期,请用大脚客户端更新,最新版本为:%s,大脚插件由178游戏网(www.178.com)制作.|r"
BF_TEXT_WRONGVERSION = "|CFFFFD000 您的大脚版本错误,请重新用大脚客户端更新,大脚插件由178游戏网(www.178.com)制作.|r"
elseif (GetLocale() == "zhTW") then
BF_TEXT_UPDATETOVERSION = "|CFFFFD000 您的大腳版本已過期,請用大腳客戶端更新,最新版本為:%s,大腳插件由178游戲網(www.178.com)制作。|r"
BF_TEXT_WRONGVERSION = "|CFFFFD000 您的大脚版本錯誤,请重新用大脚客户端更新,大脚插件由178游戏网(www.178.com)制作.|r"
else
BF_TEXT_UPDATETOVERSION = "|CFFFFD000 Your BigFoot version is outdated, please upgrade to current version %s|r"
BF_TEXT_WRONGVERSION = "|CFFFFD000 Your BigFoot version is incorrect, please download again.|r"
end
StaticPopupDialogs["BFUPDATE"] ={
button1 = TEXT(OKAY),
OnAccept = function()
end,
showAlert = 1,
timeout = 0,
};
BIGFOOT_VERSION_QUERY="BIGFOOT_VERSION_QUERY"
local e = BLibrary("BEvent")
local BMath = BLibrary("BMathClass")
local function sameLocale(a,b)
local localea = a:match("[a-zA-Z]+")
local localeb = b:match("[a-zA-Z]+")
if not localea or not localeb then return true end
--to be compatible with old version
if localea ~= localeb then
return false
else
return true
end
end
local function larger(a,b)
local adt={}
local bdt={}
local ad,bd
for ad in a:gmatch("%d+") do
tinsert(adt,ad)
end
for bd in b:gmatch("%d+") do
tinsert(bdt,bd)
end
for i=1,4 do
if adt[i]>bdt[i] then return true end
if adt[i]<bdt[i] then return false end
end
return false
end
local function printVersion(version)
BigFoot_Print(format(BF_TEXT_UPDATETOVERSION,version))
StaticPopupDialogs["BFUPDATE"].text=format(BF_TEXT_UPDATETOVERSION,version)
StaticPopup_Show("BFUPDATE");
end
local function printWrongVersion()
BigFoot_Print(BF_TEXT_WRONGVERSION)
StaticPopupDialogs["BFUPDATE"].text=BF_TEXT_WRONGVERSION
StaticPopup_Show("BFUPDATE");
end
local function checkVersion (message)
if not BigFoot_Config["BIGFOOT_VERSION_NEW"] then
BigFoot_Config["BIGFOOT_VERSION_NEW"]=BIGFOOT_VERSION
elseif sameLocale(BigFoot_Config["BIGFOOT_VERSION_NEW"],BIGFOOT_VERSION) and larger(BIGFOOT_VERSION,BigFoot_Config["BIGFOOT_VERSION_NEW"]) then
BigFoot_Config["BIGFOOT_VERSION_NEW"]=BIGFOOT_VERSION
end
if(sameLocale(BigFoot_Config["BIGFOOT_VERSION_NEW"],message) and larger(message,BigFoot_Config["BIGFOOT_VERSION_NEW"])) then
BigFoot_Config["BIGFOOT_VERSION_NEW"] = message;
end
end
local function isValid (message)
local i = 1;
local checksum,version
for word in string.gmatch(message,"([^|]+)") do
if i == 1 then checksum = word end
if i == 2 then version = word end
i = i + 1;
end
if checksum and version and checksum == BMath:LRC(version) then return true end
return false
end
e:RegisterEvent("PLAYER_LOGIN");
function e:PLAYER_LOGIN()
if not isValid(BF_VERSION_CHECKSUM.."|"..BIGFOOT_VERSION) then
printWrongVersion();
return;
else
RegisterAddonMessagePrefix("BF_VER_CHK");
self:RegisterEvent("CHAT_MSG_ADDON");
self:RegisterEvent("GROUP_ROSTER_UPDATE")
end
if not BigFoot_Config["BIGFOOT_VERSION_NEW"] then
BigFoot_Config["BIGFOOT_VERSION_NEW"]=BIGFOOT_VERSION
elseif not sameLocale(BigFoot_Config["BIGFOOT_VERSION_NEW"],BIGFOOT_VERSION) then
BigFoot_Config["BIGFOOT_VERSION_NEW"]=BIGFOOT_VERSION
elseif larger(BIGFOOT_VERSION,BigFoot_Config["BIGFOOT_VERSION_NEW"]) then
BigFoot_Config["BIGFOOT_VERSION_NEW"]=BIGFOOT_VERSION
end
if sameLocale(BigFoot_Config["BIGFOOT_VERSION_NEW"],BIGFOOT_VERSION) and larger(BigFoot_Config["BIGFOOT_VERSION_NEW"],BIGFOOT_VERSION) then
printVersion(BigFoot_Config["BIGFOOT_VERSION_NEW"])
end
end
function e:CHAT_MSG_ADDON(...)
local filter,message,_,sender =...
if(filter =="BF_VER_CHK") then
if sender and not sender:find(UnitName("player")) then
if not isValid(message)then return end
local version = string.sub(message, string.find(message, "|(.+)")+1)
checkVersion(version)
end
end
end
local hasSend;
function e:GROUP_ROSTER_UPDATE()
if not hasSend and IsInRaid() then
-- local raidmember = GetNumGroupMembers()
-- if raidmember >= 0 then
-- local playername=UnitName('player')
-- for i=1, raidmember do
-- BigFoot_DelayCall(function()
-- local name,sever = UnitName('raid'..i)
-- if not sever and name ~= UNKNOWNOBJECT and UnitIsPlayer(name) and UnitIsConnected(name) and name~=playername then
-- SendAddonMessage("BF_VER_CHK",BIGFOOT_VERSION_QUERY,'WHISPER',name)
-- end
-- end,3)
-- end
-- end
BigFoot_DelayCall(function()
SendAddonMessage("BF_VER_CHK",BF_VERSION_CHECKSUM.."|"..BIGFOOT_VERSION,(IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT") or "RAID")
end,3);
hasSend = true;
else
-- local partymember = GetNumSubgroupMembers()
if GetNumSubgroupMembers() >= 1 then
-- for i=1, partymember do
-- BigFoot_DelayCall(function()
-- local name,sever = UnitName('party'..i)
-- if not sever and UnitIsPlayer(name) and UnitIsConnected(name) and name ~= UNKNOWNOBJECT then
-- SendAddonMessage("BF_VER_CHK",BIGFOOT_VERSION_QUERY,'WHISPER',name)
-- end
-- end,3);
-- end
if not hasSend then
BigFoot_DelayCall(function()
SendAddonMessage("BF_VER_CHK",BF_VERSION_CHECKSUM.."|"..BIGFOOT_VERSION,(IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "INSTANCE_CHAT") or "PARTY")
end,3);
hasSend = true;
end
return;
end
hasSend = nil;
end
end
----also put ace validation here
local _LibStubVersion = 2
local __AceVersionTable = {
["AceLibrary"] = 91091,
["AceOO-2.0"] = 91091,
["AceEvent-2.0"] = 91097,
["AceDB-2.0"] = 91094,
["AceDebug-2.0"] = 91091,
["AceLocale-2.2"] = 91094,
["AceConsole-2.0"] = 91094,
["AceAddon-2.0"] = 91100,
["AceHook-2.1"] = 91091,
["AceModuleCore-2.0"] = 91091,
["CallbackHandler-1.0"] = 5,
["AceAddon-3.0"] = 5,
["AceEvent-3.0"] = 3,
["AceTimer-3.0"] = 5,
["AceBucket-3.0"] = 3,
["AceHook-3.0"] = 5,
["AceDB-3.0"] = 21,
["AceDBOptions-3.0"] = 12,
["AceLocale-3.0"] = 2,
["AceConsole-3.0"] = 7,
["AceGUI-3.0"] = 33,
["AceConfig-3.0"] = 2,
["AceConfigRegistry-3.0"] = 12,
["AceConfigTab-3.0"] = 1,
["AceConfigCmd-3.0"] = 12,
["AceConfigDialog-3.0"] = 49,
["AceComm-3.0"] = 6,
["AceTab-3.0"] = 8,
["AceSerializer-3.0"] = 3,
["AceGUISharedMediaWidgets-1.0"] = 32,
["Abacus-2.0"] = 92247000,
["LibCrayon-3.0"] = 91800,
["LibQuixote-2.0"] = 90180,
["LibBossIDs-1.0"] = 44,
["Dewdrop-2.0"] = 90320,
["FuBarPlugin-MinimapContainer-2.0"] = 90003,
["LibAboutPanel"] = 1,
["Roster-2.1"] = 90092,
["LibBabble-Boss-3.0"] = 90298,
["LibBabble-Class-3.0"] = 90050,
["LibBabble-3.0"] = 2,
["LibBabble-Inventory-3.0"] = 90101,
["LibDBIcon-1.0"] = 11,
["LibAbacus-3.0"] = 92247,
["Waterfall-1.0"] = 90130,
["Gratuity-2.0"] = 70090039,
["CandyBar-2.0"] = 90154,
["LibGraph-2.0"] = 90041,
["Tablet-2.0"] = 90216,
["LibStatLogic-1.1"] = 92,
["LibGratuity-3.0"] = 90039,
["LibDualSpec-1.0"] = 4,
["LibPeriodicTable-3.1"] = 90006,
["LibBabble-Zone-3.0"] = 90279,
["LibTourist-3.0"] = 90098,
["LibSink-2.0"] = 90063,
["LibDataBroker-1.1"] = 4,
["LibBabble-Spell-3.0"] = 90123,
["LibSimpleFrame-1.0"] = 90046,
["LibSharedMedia-3.0"] = 90058,
["Window-1.0"] = 90034,
["LibBanzai-2.0"] = 90040,
["LibTipHooker-1.1"] = 11,
["LibHealComm-4.0"] = 66,
["Crayon-2.0"] = 91800000,
["FuBarPlugin-2.0"] = 90003,
}
local function existAssert(_libName)
if _G[_libName] or LibStub:GetLibrary(_libName,true) then return true end
print(("|cffff0000<Version Check>|r%s does not exist!"):format(_libName))
return false
end
local function versionAssert(_exp,_act,_libName)
if not _exp == _act then
print (("|cffff0000<Version Check>|r %s version incorrect! expect: %s, found: %s !"):format(_libName,_exp,_act))
end
end
function ValidateAceLibs()
local _versionExp,_versionAct
--check LibStub
if not existAssert("LibStub") then return end
versionAssert(_LibStubVersion,LibStub.minor,"LibStub")
for _major,minorExp in pairs(__AceVersionTable) do
if existAssert(_major) then
local _,_minorAct = LibStub:GetLibrary(_major,true);
versionAssert(_minorAct,minorExp,_major)
end
end
print("|cff00FF00<Version Check>|r Validation passed, All AceLibs are in correct versions!")
end
|
-----------------------------------
-- Area: Southern San d'Oria
-- NPC: Benaige
-- Standard Merchant NPC
-- !pos -142 -6 47 230
-----------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs")
require("scripts/globals/shop")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local stock =
{
628, 234, 1, -- Cinnamon
629, 43, 1, -- Millioncorn
622, 43, 2, -- Dried Marjoram
610, 54, 2, -- San d'Orian Flour
627, 36, 2, -- Maple Sugar
1840, 1800, 2, -- Semolina
5726, 442, 2, -- Zucchini
5740, 511, 2, -- Paprika
621, 25, 3, -- Crying Mustard
611, 36, 3, -- Rye Flour
936, 14, 3, -- Rock Salt
4509, 10, 3, -- Distilled Water
5234, 198, 3, -- Cibol
}
player:showText(npc, ID.text.BENAIGE_SHOP_DIALOG)
tpz.shop.nation(player, stock, tpz.nation.SANDORIA)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
--[[----------------------------------------------------------------------------
premake4.lua -- Noel Cower
This build script is public domain.
------------------------------------------------------------------------------]]
-- Set up snow table
snow = {}
--[[----------------------------------------------------------------------------
join_arrays
Joins zero or more arrays into a single array. Discards original keys in
input tables.
------------------------------------------------------------------------------]]
function snow.join_arrays(...)
local result = {}
local inputs = {...}
for ik,iv in pairs(inputs) do
for jk,jv in pairs(iv) do
result[#result + 1] = jv
end
end
return result
end
function snow.tostring(e)
if e == nil then
return ""
elseif type(e) == "function" then
return snow.tostring(e())
elseif type(e) == "number" then
return tostring(e)
elseif type(e) == "boolean" then
if e then
return "1"
else
return "0"
end
else
return tostring(e)
end
end
--[[----------------------------------------------------------------------------
formatrb_string
Returns arguments combined for format.rb
------------------------------------------------------------------------------]]
function snow.formatrb_string(t)
local result = ""
for k,v in pairs(t) do
result = result .. " '" .. snow.tostring(k) .. "=" .. snow.tostring(v) .. "'"
end
return result
end
--[[----------------------------------------------------------------------------
get_headers
Retrieves a list of all headers, excluding any that match the suffixes in
the excluded_suffixes argument (if provided).
------------------------------------------------------------------------------]]
function snow.get_headers(excluded_suffixes)
local headers = snow.join_arrays(
os.matchfiles("include/**.hh"),
os.matchfiles("include/**.cc"),
os.matchfiles("include/*.hh"),
os.matchfiles("include/*.cc") )
local swap = {}
for header_k, header_path in pairs(headers) do
if excluded_suffixes then
-- Check for exclusions
for excl_k, excl_suffix in pairs(excluded_suffixes) do
if string.endswith(header_path, excl_suffix) then
print(excl_k .. ": Excluding " .. header_path)
header_path = nil
break
end -- if matches excluded header
end -- for in excluded_suffixes
end -- if excluded_suffixes
if header_path then
swap[header_path] = header_path
end
end -- for in headers
return swap
end
function snow.install(source_path, install_path, verbose)
if verbose then
print("Installing '" .. source_path .."' to '" .. install_path .. "'")
end
local done, errmsg = os.copyfile(source_path, install_path)
if not done then
print("os.copyfile: " .. errmsg)
print("Unable to copy " .. source_path, " unable to continue installation")
return false
end
return true
end
function snow.correct_dirsep(str)
if os.is("windows") then
return string.gsub(str, "/", "\\")
else
return string.gsub(str, "\\", "/")
end
end
function snow.dirname(str)
local last = string.findlast(str, "/", true)
if last ~= nil then
return string.sub(str, 0, last)
end
return str
end
function snow.mkdir_p(path)
local dirsep = "/"
if os.is("windows") then
dirsep = "\\"
end
local components = string.explode(path, "/")
local last_dir = 0
do -- Make sure nothing along the way is a file
local dir_build = ""
for i, v in ipairs(components) do
if v ~= "" then
dir_build = dir_build .. dirsep .. v
if os.isdir(dir_build) == true then
last_dir = i
elseif os.isfile(dir_build) then
return false -- Cannot create dir if file of the same name exists already
end
end
end -- for in components
end -- do check path
do
local dir_build = ""
for i, v in ipairs(components) do
if #v > 0 then
dir_build = dir_build .. dirsep .. v
if i > last_dir then
local done, errmsg = os.mkdir(dir_build)
if not done then
print("Unable to create directory: " .. dir_build)
return false
end -- if not done
end -- if i > last_dir
end
end -- for in components
end -- do build directory
return true
end -- mkdir_p
-- Main build configuration
solution "snow"
project "snow-common"
configurations { "Debug-Static", "Debug-Shared", "Release-Static", "Release-Shared" }
targetdir "lib"
-- Option defaults
g_verbose_install = false
g_exclude_suffixes = {}
g_prefix = "/usr/local"
if _OPTIONS["verbose-install"] then
g_verbose_install = true
end
if _OPTIONS["prefix"] then
g_prefix = _OPTIONS["prefix"]
end
g_libdir = g_prefix .. "/lib"
g_pkgconfig_dir = g_libdir .. "/pkgconfig"
-- Build options
newoption {
trigger = "verbose-install",
description = "Provides verbose information during installation"
}
newoption {
trigger = "universal",
description = "Builds for x86_64 and i386 if enabled. Otherwise builds for native architecture. [OS X only]"
}
newoption {
trigger = "no-exceptions",
description = "Disables exceptions in snow-common -- replaces throws with exit(1)"
}
newoption {
trigger = "prefix",
description = "Installation prefix",
value = "Default: /usr/local"
}
-- Installation
newaction {
trigger = "install",
description = "Install libsnow-common",
execute = function()
local headers = snow.get_headers(g_exclude_suffixes)
local dirs_needed = {}
for k,v in pairs(headers) do
local dir = snow.dirname(v)
local prefixed_dir = g_prefix .. "/" .. dir
if not dirs_needed[prefixed_dir] then
if g_verbose_install then
print("Marking " .. prefixed_dir .. " as required")
end
dirs_needed[prefixed_dir] = true
end
end
-- Make sure prefix/lib/pkgconfig exists
dirs_needed[g_pkgconfig_dir] = g_pkgconfig_dir
-- Create directories
print("Creating directories...")
for k,v in pairs(dirs_needed) do
if not os.isdir(k) then
if g_verbose_install then
print("Creating directory " .. k)
end
if not snow.mkdir_p(k) then
print("Could not create directories needed, unable to continue installation")
return false
end
end
end
-- Copy headers over
print("Copying headers...")
for k,v in pairs(headers) do
local source_path = snow.correct_dirsep(v)
local install_path = snow.correct_dirsep(g_prefix .. "/" .. v)
if not snow.install(source_path, install_path, g_verbose_install) then
return false
end
end
print("Copying libraries...")
local lib_files = os.matchfiles("lib/libsnow-common.*")
for k,v in pairs(lib_files) do
local source_path = snow.correct_dirsep(v)
local install_path = snow.correct_dirsep(g_prefix .. "/" .. v)
if not snow.install(source_path, install_path, g_verbose_install) then
return false
end
end
print("Copying 'snow-common.pc'...")
if not snow.install("snow-common.pc", g_pkgconfig_dir .. "/snow-common.pc", g_verbose_install) then
return false
end
end
}
-- Compiler flags
g_version = "0.1.0"
language "C++"
buildoptions { "-std=c++11" }
flags { "FloatStrict", "NoRTTI" }
objdir "obj"
-- Add sources/include directories
includedirs { "include" }
files { "src/**.cc" }
configuration "*-Shared"
kind "SharedLib"
configuration "*-Static"
kind "StaticLib"
configuration "Release-*"
defines { "NDEBUG" }
configuration "Debug-*"
defines { "DEBUG" }
flags { "Symbols" }
g_build_config_opts = {
USE_EXCEPTIONS = not _OPTIONS["no-exceptions"],
HAS_SHA256 = false,
HAS_LBIND = false
}
g_pkgconfig_opts = {
PREFIX = g_prefix,
VERSION = g_version,
PRIVATE_PKGS = "",
PRIVATE_LIBS = ""
}
-- Exceptions
configuration "no-exceptions"
flags { "NoExceptions" }
-- OS X specific options
configuration { "macosx", "universal" }
buildoptions { "-arch x86_64", "-arch i386" }
linkoptions { "-arch x86_64", "-arch i386" }
configuration "macosx"
buildoptions { "-stdlib=libc++" }
links { "c++" }
configuration { "macosx", "*-Shared" }
links { "Cocoa.framework" }
configuration {}
-- Generate build-config/pkg-config
local config_src = "'include/snow/build-config.hh.in'"
local config_dst = "'include/snow/build-config.hh'"
if _ACTION and _ACTION ~= "install" then
-- Generate build-config.hh
print("Generating 'include/snow/build-config.hh'...")
os.execute("./format.rb " .. config_src .. " " .. config_dst .. snow.formatrb_string(g_build_config_opts))
-- Generate snow-common.pc
print("Generating 'snow-common.pc'...")
local formatrb_exec = "./format.rb 'snow-common.pc.in' 'snow-common.pc'" .. snow.formatrb_string(g_pkgconfig_opts)
if os.execute(formatrb_exec) ~= 0 then
print("Could not create 'snow-common.pc', unable to continue installation")
return false
end
end
|
require "example"
|
--***********************************************************
--** THE INDIE STONE **
--***********************************************************
require "ISUI/ISCollapsableWindow"
---@class DebugLogSettings : ISCollapsableWindow
DebugLogSettings = ISCollapsableWindow:derive("DebugLogSettings")
local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small)
function DebugLogSettings:onTickBox(index, selected, debugType)
DebugLog.setLogEnabled(debugType, selected)
DebugLog:save()
end
function DebugLogSettings:createChildren()
local fontHgt = getTextManager():getFontFromEnum(UIFont.Small):getLineHeight()
local entryHgt = fontHgt + 2 * 2
local x = 12
local y = self:titleBarHeight() + 6
local maxWidth = 0
local debugTypes = DebugLog.getDebugTypes()
for i=1,debugTypes:size() do
local debugType = debugTypes:get(i-1)
local tickBox = ISTickBox:new(x, y, self.width, entryHgt, "", self, self.onTickBox, debugType)
tickBox:initialise()
tickBox:addOption(debugType:name(), debugType)
tickBox:setSelected(1, DebugLog.isEnabled(debugType))
tickBox:setWidthToFit()
self:addChild(tickBox)
maxWidth = math.max(maxWidth, tickBox:getRight())
y = y + entryHgt + 6
if self.y + y + entryHgt + 6 >= getCore():getScreenHeight() then
x = x + maxWidth
y = self:titleBarHeight() + 6
maxWidth = 0
end
end
local width = 0
local height = 0
for _,child in pairs(self:getChildren()) do
width = math.max(width, child:getRight())
height = math.max(height, child:getBottom())
end
self:setWidth(width + 12)
self:setHeight(height + self:resizeWidgetHeight())
end
function DebugLogSettings:onMouseDownOutside(x, y)
self:setVisible(false)
self:removeFromUIManager()
end
function DebugLogSettings:new(x, y, width, height)
local o = ISCollapsableWindow:new(x, y, width, height)
setmetatable(o, self)
self.__index = self
o.backgroundColor = {r=0, g=0, b=0, a=1.0}
o.resizable = false
return o
end
|
function strip_raw_outmeta()
for k,v in pairs(outmeta) do
if k:sub(1,4) == "raw_" then outmeta[k] = nil end
end
end
function consume_tag(wat)
local ret = inmeta[wat]
inmeta[wat] = nil
if ret ~= nil and ret ~= "" then
ret = ret:gsub("^[ \t]+",""):gsub("[ \t]+$","")
end
if ret == "" then return nil
else return ret
end
end
function set_raw_outmeta()
for k,v in pairs(inmeta) do
outmeta["raw_"..k] = v
end
end
-- (three-character tags are ID3v2, four-character tags are ID3v2.3 or ID3v2.4)
local ID3V2_TAGS<const> = {
BUF = "recommended_buffer_size",
CNT = "play_counter",
COM = "comment",
CRA = "audio_encryption",
CRM = "encrypted_meta_frame",
ETC = "event_timing_codes",
EQU = "equalization",
GEO = "general_encapsulated_object",
IPL = "involved_people_list",
LNK = "linked_information",
MCI = "music_cd_identifier",
MLL = "mpeg_location_lookup_table",
PIC = "attached_picture",
POP = "popularimeter",
REV = "reverb",
RVA = "relative_volume_adjustment",
SLT = "synchronized_lyric_or_text",
STC = "synced_tempo_codes",
TAL = "album",
TBP = "bpm",
TCM = "composer",
TCO = "content_type",
TCR = "copyright_message",
TDA = "date",
TDY = "playlist_delay",
TEN = "encoded_by",
TFT = "file_type",
TIM = "time",
TKE = "initial_key",
TLA = "language",
TLE = "length",
TMT = "media_type",
TOA = "original_artist_or_performer",
TOF = "original_filename",
TOL = "original_lyricist_or_text_writer",
TOR = "original_release_year",
TOT = "original_album",
TP1 = "artist",
TP2 = "orchestra",
TP3 = "conductor",
TP4 = "interpreter",
TPA = "part_of_a_set",
TPB = "publisher",
TRC = "international_standard_recording_code",
TRD = "recording_dates",
TRK = "track",
TSI = "size",
TSS = "encoder",
TT1 = "grouping",
TT2 = "title",
TT3 = "subtitle",
TXT = "lyricist_or_text_writer",
TXX = "user_defined_text_information_frame",
TYE = "year",
UFI = "unique_file_identifier",
ULT = "unsynchronized_lyric_or_text_transcription",
WAF = "official_audio_file_webpage",
WAR = "official_artist_webpage",
WAS = "official_audio_source_webpage",
WCM = "commercial_information",
WCP = "copyright_or_legal_information",
WPB = "publisher_official_webpage",
WXX = "user_defined_url_link_frame",
AENC = "audio_encryption",
APIC = "attached_picture",
ASPI = "audio_seek_point_index",
COMM = "comment",
COMR = "commercial_frame",
ENCR = "encryption_method_registration",
EQU2 = "equalization",
ETCO = "event_timing_codes",
GEOB = "general_encapsulated_object",
GRID = "group_identification_registration",
LINK = "linked_information",
MCDI = "music_cd_identifier",
MLLT = "mpeg_location_lookup_table",
OWNE = "ownership_frame",
PRIV = "private_frame",
PCNT = "play_counter",
POPM = "popularimeter",
POSS = "position_synchronisation_frame",
RBUF = "recommended_buffer_size",
RVA2 = "relative_volume_adjustment",
RVRB = "reverb",
SEEK = "seek_frame",
SIGN = "signature_frame",
SYLT = "synchronised_lyric_or_text",
SYTC = "synchronised_tempo_codes",
TALB = "album",
TBPM = "bpm",
TCOM = "composer",
TCON = "content_type",
TCOP = "copyright_message",
TDEN = "encoding_time",
TDLY = "playlist_delay",
TDOR = "original_releaseOtime",
TDRC = "recording_time",
TDRL = "release_time",
TDTG = "tagging_time",
TENC = "encoded_by",
TEXT = "lyricist_or_text_writer",
TFLT = "file_type",
TIPL = "involved_people_list",
TIT1 = "grouping",
TIT2 = "title",
TIT3 = "subtitle",
TKEY = "initial_key",
TLAN = "language",
TLEN = "length",
TMCL = "musician_credits_list",
TMED = "media_type",
TMOO = "mood",
TOAL = "original_album",
TOFN = "original_filename",
TOLY = "original_lyricist_or_textwriter",
TOPE = "original_artist",
TOWN = "file_owner_or_licensee",
TPE1 = "artist",
TPE2 = "orchestra",
TPE3 = "conductor",
TPE4 = "interpreter",
TPOS = "part_of_a_set",
TPRO = "produced_notice",
TPUB = "publisher",
TRCK = "track",
TRSN = "internet_radio_station_name",
TRSO = "internet_radio_station_owner",
TSOA = "sort_album",
TSOP = "sort_artist",
TSOT = "sort_title",
TSRC = "international_standard_recording_code",
TSSE = "software_or_hardware_and_settings_used_for_encoding",
TSST = "set_subtitle",
TXXX = "user_defined_text_information_frame",
UFID = "unique_file_identifier",
USER = "terms_of_use",
USLT = "unsynchronised_lyric_or_text_transcription",
WCOM = "commercial_information",
WCOP = "copyright_or_legal_information",
WOAF = "official_audio_file_webpage",
WOAR = "official_artist_webpage",
WOAS = "official_audio_source_webpage",
WORS = "official_internet_radio_station_homepage",
WPAY = "payment",
WPUB = "publisher_official_webpage",
WXXX = "user_defined_url_link_frame",
}
function remap_id3v2_tags()
for tag, base in pairs(ID3V2_TAGS) do
local value = consume_tag(tag)
if value then
local key = "id3v2_"..base
if not inmeta[key] then
inmeta[key] = value
end
end
end
end
|
workspace "TrueEngine"
architecture "x64"
startproject "Sandbox"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
-- Include directories relative to root folder (solution directory)
IncludeDir = {}
IncludeDir["GLFW"] = "TrueEngine/vendor/GLFW/include"
IncludeDir["Glad"] = "TrueEngine/vendor/Glad/include"
IncludeDir["ImGui"] = "TrueEngine/vendor/imgui"
group "Dependencies"
include "TrueEngine/vendor/GLFW"
include "TrueEngine/vendor/Glad"
include "TrueEngine/vendor/imgui"
group ""
project "TrueEngine"
location "TrueEngine"
kind "SharedLib"
language "C++"
staticruntime "off"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "tepch.h"
pchsource "TrueEngine/src/tepch.cpp"
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.ImGui}"
}
links
{
"GLFW",
"Glad",
"ImGui",
"opengl32.lib"
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines
{
"TE_PLATFORM_WINDOWS",
"TE_BUILD_DLL",
"GLFW_INCLUDE_NONE"
}
postbuildcommands
{
("{COPY} %{cfg.buildtarget.relpath} \"../bin/" .. outputdir .. "/Sandbox\"")
}
filter "configurations:Debug"
defines "TE_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "TE_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "TE_DIST"
runtime "Release"
optimize "On"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
language "C++"
staticruntime "off"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"TrueEngine/vendor/spdlog/include",
"TrueEngine/src"
}
links
{
"TrueEngine"
}
filter "system:windows"
cppdialect "C++17"
systemversion "latest"
defines
{
"TE_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "TE_DEBUG"
runtime "Debug"
symbols "On"
filter "configurations:Release"
defines "TE_RELEASE"
runtime "Release"
optimize "On"
filter "configurations:Dist"
defines "TE_DIST"
runtime "Release"
optimize "On" |
local InviteToGameAnalytics = {}
InviteToGameAnalytics.__index = InviteToGameAnalytics
InviteToGameAnalytics.ButtonName = {
SettingsHub = "settingsHub",
ModalPrompt = "modalPrompt",
}
InviteToGameAnalytics.EventName = {
InviteSent = "inputShareGameInviteSent",
EntryPoint = "inputShareGameEntryPoint",
}
InviteToGameAnalytics.DiagCounters = {
EntryPoint = {
[InviteToGameAnalytics.ButtonName.SettingsHub] = settings():GetFVariable("LuaShareGameSettingsHubEntryCounter"),
[InviteToGameAnalytics.ButtonName.ModalPrompt] = settings():GetFVariable("LuaShareGameModalPromptEntryCounter"),
},
InviteSent = {
[InviteToGameAnalytics.ButtonName.SettingsHub] = settings():GetFVariable("LuaShareGameSettingsHubInviteCounter"),
[InviteToGameAnalytics.ButtonName.ModalPrompt] = settings():GetFVariable("LuaShareGameModalPromptInviteCounter"),
},
}
function InviteToGameAnalytics.new()
local self = {
_eventStreamImpl = nil,
_diagImpl = nil,
_buttonName = nil,
}
setmetatable(self, InviteToGameAnalytics)
return self
end
function InviteToGameAnalytics:withEventStream(eventStreamImpl)
self._eventStreamImpl = eventStreamImpl
return self
end
function InviteToGameAnalytics:withDiag(diagImpl)
self._diagImpl = diagImpl
return self
end
function InviteToGameAnalytics:withButtonName(buttonName)
self._buttonName = buttonName
return self
end
function InviteToGameAnalytics:onActivatedInviteSent(senderId, conversationId, participants)
local buttonName = self:_getButtonName()
local eventContext = "inGame"
local eventName = InviteToGameAnalytics.EventName.InviteSent
local participantsString = table.concat(participants, ",")
local additionalArgs = {
btn = buttonName,
placeId = tostring(game.PlaceId),
gameId = tostring(game.GameId),
senderId = senderId,
conversationId = tostring(conversationId),
participants = participantsString,
}
self:_getEventStream():setRBXEventStream(eventContext, eventName, additionalArgs)
local counterName = InviteToGameAnalytics.DiagCounters.InviteSent[self:_getButtonName()]
if counterName then
self:_getDiag():reportCounter(counterName, 1)
end
end
function InviteToGameAnalytics:inputShareGameEntryPoint()
local buttonName = self:_getButtonName()
local eventContext = "inGame"
local eventName = InviteToGameAnalytics.EventName.EntryPoint
local additionalArgs = {
btn = buttonName,
placeId = tostring(game.PlaceId),
gameId = tostring(game.GameId),
}
self:_getEventStream():setRBXEventStream(eventContext, eventName, additionalArgs)
local counterName = InviteToGameAnalytics.DiagCounters.EntryPoint[self:_getButtonName()]
if counterName then
self:_getDiag():reportCounter(counterName, 1)
end
end
function InviteToGameAnalytics:_getEventStream()
assert(self._eventStreamImpl, "EventStream implementation not found. Did you forget to construct withEventStream?")
return self._eventStreamImpl
end
function InviteToGameAnalytics:_getDiag()
assert(self._diagImpl, "Diag implementation not found. Did you forget to construct withDiag?")
return self._diagImpl
end
function InviteToGameAnalytics:_getButtonName()
assert(self._buttonName, "ButtonName not found. Did you forget to construct withButtonName?")
return self._buttonName
end
return InviteToGameAnalytics
|
--- A way of injecting plugins via the Howl DSL
-- @module howl.modules.plugins
local class = require "howl.class"
local mixin = require "howl.class.mixin"
local fs = require "howl.platform".fs
local Plugins = class("howl.modules.plugins")
:include(mixin.configurable)
function Plugins:initialize(context)
self.context = context
end
function Plugins:configure(data)
if #data == 0 then
self:addPlugin(data, data)
else
for i = 1, #data do
self:addPlugin(data[i])
end
end
end
local function toModule(root, file)
local name = file:gsub("%.lua$", ""):gsub("/", "."):gsub("^(.*)%.init$", "%1")
if name == "" or name == "init" then
return root
else
return root .. "." .. name
end
end
function Plugins:addPlugin(data)
if not data.type then error("No plugin type specified") end
local type = data.type
data.type = nil
local file
if data.file then
file = data.file
data.file = nil
end
local manager = self.context.packageManager
local package = manager:addPackage(type, data)
self.context.logger:verbose("Using plugin from package " .. package:getName())
local fetchedFiles = package:require(file and {file})
local root = "external." .. package:getName()
local count = 0
for file, loc in pairs(fetchedFiles) do
if file:find("%.lua$") then
count = count + 1
local func, msg = loadfile(fetchedFiles[file], _ENV)
if func then
local name = toModule(root, file)
preload[name] = func
self.context.logger:verbose("Including plugin file " .. file .. " as " .. name)
else
self.context.logger:warning("Cannot load plugin file " .. file .. ": " .. msg)
end
end
end
if not file then
if fetchedFiles["init.lua"] then
file = "init.lua"
elseif count == 1 then
file = next(fetchedFiles)
elseif count == 0 then
self.context.logger:error(package:getName() .. " does not export any files")
error("Error adding plugin")
else
self.context.logger:error("Cannot guess a file for " .. package:getName())
error("Error adding plugin")
end
end
self.context.logger:verbose("Using package " .. package:getName() .. " with " .. file)
local name = toModule(root, file)
if not preload[name] then
self.context.logger:error("Cannot load plugin as " .. name .. " could not be loaded")
error("Error adding plugin")
end
self.context:include(require(name))
return self
end
return {
name = "plugins",
description = "Inject plugins into Howl at runtime.",
setup = function(context)
context.mediator:subscribe({ "HowlFile", "env" }, function(env)
env.plugins = Plugins(context)
end)
end
}
|
-- Borrowed this from Factorio
yatm.fluids.fluid_registry.register("yatm_fluids", "heavy_oil", {
description = "Heavy Oil",
aliases = {
"yatm_core:heavy_oil",
},
groups = {
oil = 1,
heavy_oil = 1,
flammable = 1,
},
nodes = {
texture_basename = "yatm_heavy_oil",
groups = { oil = 1, heavy_oil = 1, liquid = 3, flammable = 1 },
use_texture_alpha = "opaque",
post_effect_color = {a=192, r=200, g=122, b=51},
},
bucket = {
texture = "yatm_bucket_heavy_oil.png",
groups = { heavy_oil_bucket = 1 },
force_renew = false,
},
fluid_tank = {},
})
|
-- Dat View
--
-- Class: GGPK Data
-- GGPK Data
--
local ipairs = ipairs
local t_insert = table.insert
local function scanDir(directory, extension)
local i = 0
local t = { }
local pFile = io.popen('dir "'..directory..'" /b')
for filename in pFile:lines() do
--ConPrintf("%s\n", filename)
if extension then
if filename:match(extension) then
i = i + 1
t[i] = filename
else
--ConPrintf("No Files Found matching extension '%s'", extension)
end
else
i = i + 1
t[i] = filename
end
end
pFile:close()
return t
end
-- Path can be in any format recognized by the extractor at oozPath, ie,
-- a .ggpk file or a Steam Path of Exile directory
local GGPKClass = newClass("GGPKData", function(self, path)
self.path = path
self.temp = io.popen("cd"):read('*l')
self.oozPath = self.temp .. "\\ggpk\\"
self.dat = { }
self.txt = { }
self:ExtractFiles()
self:AddDatFiles()
end)
function GGPKClass:ExtractFiles()
local datList, txtList = self:GetNeededFiles()
local fileList = ''
for _, fname in ipairs(datList) do
fileList = fileList .. '"' .. fname .. '" '
end
for _, fname in ipairs(txtList) do
fileList = fileList .. '"' .. fname .. '" '
end
local cmd = 'cd ' .. self.oozPath .. ' && bun_extract_file.exe extract-files "' .. self.path .. '" . ' .. fileList
ConPrintf(cmd)
os.execute(cmd)
end
function GGPKClass:AddDatFiles()
local datFiles = scanDir(self.oozPath .. "Data\\", '%w+%.dat$')
for _, f in ipairs(datFiles) do
local record = { }
record.name = f
local rawFile = io.open(self.oozPath .. "Data\\" .. f, 'rb')
record.data = rawFile:read("*all")
rawFile:close()
--ConPrintf("FILENAME: %s", fname)
t_insert(self.dat, record)
end
end
function GGPKClass:GetNeededFiles()
local datFiles = {
"Data/Stats.dat",
"Data/BaseItemTypes.dat",
"Data/WeaponTypes.dat",
"Data/ShieldTypes.dat",
"Data/ComponentArmour.dat",
"Data/Flasks.dat",
"Data/ComponentCharges.dat",
"Data/ComponentAttributeRequirements.dat",
"Data/PassiveSkills.dat",
"Data/PassiveSkillBuffs.dat",
"Data/PassiveTreeExpansionJewelSizes.dat",
"Data/PassiveTreeExpansionJewels.dat",
"Data/PassiveJewelSlots.dat",
"Data/PassiveTreeExpansionSkills.dat",
"Data/PassiveTreeExpansionSpecialSkills.dat",
"Data/Mods.dat",
"Data/ModType.dat",
"Data/ModDomains.dat",
"Data/ModGenerationType.dat",
"Data/ModFamily.dat",
"Data/ModAuraFlags.dat",
"Data/ActiveSkills.dat",
"Data/ActiveSkillTargetTypes.dat",
"Data/ActiveSkillType.dat",
"Data/Ascendancy.dat",
"Data/ClientStrings.dat",
"Data/ItemClasses.dat",
"Data/SkillTotems.dat",
"Data/SkillTotemVariations.dat",
"Data/SkillMines.dat",
"Data/Essences.dat",
"Data/EssenceType.dat",
"Data/Characters.dat",
"Data/BuffDefinitions.dat",
"Data/BuffCategories.dat",
"Data/BuffVisuals.dat",
"Data/HideoutNPCs.dat",
"Data/NPCs.dat",
"Data/CraftingBenchOptions.dat",
"Data/CraftingItemClassCategories.dat",
"Data/CraftingBenchUnlockCategories.dat",
"Data/MonsterVarieties.dat",
"Data/MonsterResistances.dat",
"Data/MonsterTypes.dat",
"Data/DefaultMonsterStats.dat",
"Data/SkillGems.dat",
"Data/GrantedEffects.dat",
"Data/GrantedEffectsPerLevel.dat",
"Data/ItemExperiencePerLevel.dat",
"Data/EffectivenessCostConstants.dat",
"Data/StatInterpolationTypes.dat",
"Data/Tags.dat",
"Data/GemTags.dat",
"Data/ItemVisualIdentity.dat",
"Data/AchievementItems.dat",
"Data/MultiPartAchievements.dat",
"Data/PantheonPanelLayout.dat",
"Data/AlternatePassiveAdditions.dat",
"Data/AlternatePassiveSkills.dat",
"Data/AlternateTreeVersions.dat",
"Data/GrantedEffectQualityTypes.dat",
"Data/GrantedEffectQualityStats.dat",
"Data/GrantedEffectGroups.dat",
}
local txtFiles = {
"Metadata/StatDescriptions/passive_skill_aura_stat_descriptions.txt",
"Metadata/StatDescriptions/passive_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/active_skill_gem_stat_descriptions.txt",
"Metadata/StatDescriptions/advanced_mod_stat_descriptions.txt",
"Metadata/StatDescriptions/aura_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/banner_aura_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/beam_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/brand_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/buff_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/curse_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/debuff_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/gem_stat_descriptions.txt",
"Metadata/StatDescriptions/minion_attack_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/minion_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/minion_spell_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/monster_stat_descriptions.txt",
"Metadata/StatDescriptions/offering_skill_stat_descriptions.txt",
"Metadata/StatDescriptions/skillpopup_stat_filters.txt",
"Metadata/StatDescriptions/skill_stat_descriptions.txt",
"Metadata/StatDescriptions/stat_descriptions.txt",
"Metadata/StatDescriptions/variable_duration_skill_stat_descriptions.txt",
}
return datFiles, txtFiles
end
|
function love.draw()
love.graphics.print("Hello castle-cli", 400, 300)
end
|
LinkLuaModifier("modifier_temari_sheer_wind_caster", "abilities/heroes/temari/temari_sheer_wind.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_temari_sheer_wind_stack_counter", "abilities/heroes/temari/temari_sheer_wind.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_temari_sheer_wind_stack_buff", "abilities/heroes/temari/temari_sheer_wind.lua", LUA_MODIFIER_MOTION_NONE)
temari_sheer_wind = class({})
function temari_sheer_wind:GetBehavior()
return DOTA_ABILITY_BEHAVIOR_PASSIVE
end
function temari_sheer_wind:GetIntrinsicModifierName()
return "modifier_temari_sheer_wind_caster"
end
function temari_sheer_wind:RefreshCounter()
local caster = self:GetCaster()
local counter = caster:FindModifierByName("modifier_temari_sheer_wind_stack_counter")
counter:SetDuration(self:GetDuration(), true)
end
function temari_sheer_wind:ApplyStacks()
if not IsServer() then return end
local caster = self:GetCaster()
if caster:HasModifier("modifier_temari_sheer_wind_stack_counter") then
local counter = caster:FindModifierByName("modifier_temari_sheer_wind_stack_counter")
if counter:GetStackCount() == self:GetSpecialValueFor("sheer_wind_max_stacks") then
counter:SetDuration(self:GetDuration(), true)
else
counter:IncrementStackCount()
counter:SetDuration(self:GetDuration(), true)
end
local buff_perc = counter:GetStackCount() / self:GetSpecialValueFor("sheer_wind_max_stacks") * 100
ParticleManager:SetParticleControl(counter.buff_vfx, 10, Vector(buff_perc,0,0))
else
local new_modifier = caster:AddNewModifier(caster, self, "modifier_temari_sheer_wind_stack_counter", {duration = self:GetDuration()})
new_modifier:SetStackCount(1)
local buff_perc = 100
ParticleManager:SetParticleControl(new_modifier.buff_vfx, 10, Vector(buff_perc,0,0))
end
end
function temari_sheer_wind:DecreaseStack()
if not IsServer() then return end
local caster = self:GetCaster()
if caster:HasModifier("modifier_temari_sheer_wind_stack_counter") then
local counter = caster:FindModifierByName("modifier_temari_sheer_wind_stack_counter")
if counter:GetStackCount() == 1 then
caster:RemoveModifierByName("modifier_temari_sheer_wind_stack_counter")
else
counter:DecrementStackCount()
local buff_perc = counter:GetStackCount() * 100
ParticleManager:SetParticleControl(counter.buff_vfx, 10, Vector(buff_perc,0,0))
end
end
end
modifier_temari_sheer_wind_caster = class({})
function modifier_temari_sheer_wind_caster:IsHidden() return true end
function modifier_temari_sheer_wind_caster:IsPassive() return true end
function modifier_temari_sheer_wind_caster:DeclareFunctions()
return {
MODIFIER_EVENT_ON_ABILITY_EXECUTED
}
end
function modifier_temari_sheer_wind_caster:OnAbilityExecuted(event)
if not IsServer() then return end
-- filter
if event.unit~=self:GetParent() then return end
if self:GetParent():PassivesDisabled() then return end
if not event.ability then return end
if event.ability:IsItem() or event.ability:IsToggle() then return end
local ability = self:GetAbility()
local caster = ability:GetCaster()
local min_duration = 0
if not IsServer() then return end
local buff_modifiers = caster:FindAllModifiersByName("modifier_temari_sheer_wind_stack_buff")
local buff_to_refresh = buff_modifiers[1]
if #buff_modifiers >= 3 then
for i=1,#buff_modifiers do
if buff_modifiers[i]:GetElapsedTime() > min_duration then
buff_to_refresh = buff_modifiers[i]
min_duration = buff_modifiers[i]:GetElapsedTime()
end
end
buff_to_refresh:SetDuration(ability:GetDuration(), true)
ability:RefreshCounter()
else
caster:AddNewModifier(caster, ability, "modifier_temari_sheer_wind_stack_buff", {duration = ability:GetDuration()})
end
end
modifier_temari_sheer_wind_stack_counter = class({})
function modifier_temari_sheer_wind_stack_counter:IsHidden() return false end
function modifier_temari_sheer_wind_stack_counter:IsPassive() return false end
function modifier_temari_sheer_wind_stack_counter:OnCreated()
self.buff_vfx = ParticleManager:CreateParticle("particles/units/heroes/temari/temari_sheer_wind_buff.vpcf",
PATTACH_CUSTOMORIGIN_FOLLOW,
self:GetAbility():GetCaster())
local buff_perc = 1 / self:GetAbility():GetSpecialValueFor("sheer_wind_max_stacks") * 100
-- COntrol Point 10: X - is percentage of buff power, e.g. 1 our of 3 max stacks = 33%
ParticleManager:SetParticleControl(self.buff_vfx, 10, Vector(buff_perc, 0, 0))
ParticleManager:SetParticleControlEnt(self.buff_vfx, 0, self:GetAbility():GetCaster(), PATTACH_ABSORIGIN_FOLLOW, "attach_origin", Vector(0,0,0), false)
ParticleManager:SetParticleControlEnt(self.buff_vfx, 3, self:GetAbility():GetCaster(), PATTACH_ABSORIGIN_FOLLOW, "attach_origin", Vector(0,0,0), false)
end
function modifier_temari_sheer_wind_stack_counter:OnRemoved()
ParticleManager:DestroyParticle(self.buff_vfx, false)
ParticleManager:ReleaseParticleIndex(self.buff_vfx)
end
modifier_temari_sheer_wind_stack_buff = class({})
function modifier_temari_sheer_wind_stack_buff:IsHidden() return false end
function modifier_temari_sheer_wind_stack_buff:IsPassive() return false end
function modifier_temari_sheer_wind_stack_buff:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
function modifier_temari_sheer_wind_stack_buff:DeclareFunctions()
return {
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE
}
end
function modifier_temari_sheer_wind_stack_buff:OnCreated()
local ability4 = self:GetAbility():GetCaster():FindAbilityByName("special_bonus_temari_4")
if ability4 ~= nil then
if ability4:GetLevel() > 0 then --using GetLevel instead of IsTrained because IsTrained isn't abailable on client
self.movespeed_bonus = self:GetAbility():GetSpecialValueFor("sheer_wind_move_speed_bonus_special")
self.attackspeed_bonus = self:GetAbility():GetSpecialValueFor("sheer_wind_attack_speed_bonus_special")
else
self.movespeed_bonus = self:GetAbility():GetSpecialValueFor("sheer_wind_move_speed_bonus")
self.attackspeed_bonus = self:GetAbility():GetSpecialValueFor("sheer_wind_attack_speed_bonus")
end
end
self:GetAbility():ApplyStacks()
end
function modifier_temari_sheer_wind_stack_buff:OnRemoved()
self:GetAbility():DecreaseStack()
end
function modifier_temari_sheer_wind_stack_buff:GetModifierMoveSpeedBonus_Percentage()
return self.movespeed_bonus
end
function modifier_temari_sheer_wind_stack_buff:GetModifierAttackSpeedBonus_Constant()
return self.attackspeed_bonus
end
|
_addon.name = 'voidwatch'
_addon.author = 'Dabidobido'
_addon.version = '0.8.12'
_addon.commands = {'vw'}
-- copied lots of code from https://github.com/Muddshuvel/Voidwatch/blob/master/voidwatch.lua
require('logger')
require('coroutine')
packets = require('packets')
res = require('resources')
config = require('config')
interact_distance_square = 5*5
local default_settings = {
["displacers"] = 5,
["cobalt"] = 1,
["rubicund"] = 1,
["autoloop"] = false,
["autosell"] = false,
["autows"] = false,
["autowstp"] = 1000,
["WS"] = "Evisceration",
["scdelay"] = 3,
["converttocell"] = false,
["warpwhendone"] = false,
["trustset"] = "botulus",
["refreshtrusts"] = true,
}
local settings = config.load(default_settings)
local bags = {
'inventory',
'safe',
'safe2',
'storage',
'locker',
'satchel',
'sack',
'case',
'wardrobe',
'wardrobe2',
'wardrobe3',
'wardrobe4',
}
local pulse_items = {
[18457] = 'Murasamemaru',
[18542] = 'Aytanri',
[18904] = 'Ephemeron',
[19144] = 'Coruscanti',
[19145] = 'Asteria',
[19174] = 'Borealis',
[19794] = 'Delphinius',
}
local cells = {
['Cobalt Cell'] = 3434,
['Rubicund Cell'] = 3435,
['Phase Displacer'] = 3853,
}
local phase_cell_options = {
[1] = 17,
[2] = 33,
[3] = 49,
[4] = 65,
[5] = 81,
}
local voidwatch_officers = {
[235] = { option_index = 2, cobalt_unknown1 = 769, rubicund_unknown1 = 770 },
}
local voidwatch_mobs = T{
"Ig-Alima", "Botulus Rex", "Aello", "Uptala", "Qilin", "Bismarck", "Morta", "Kaggen", "Akvan", "Pil"
}
local mob_stun_moves = {
["Ig-Alima"] = T{ "Oblivion's Mantle", "Dread Spikes" },
}
local skillchain_opener = T{ "Ayame" }
-- state vars
local wait_for_adrick_0x34 = false
local wait_for_box_0x34 = false
local wait_for_officer_0x34 = false
local wait_for_rift_0x34 = false
local wait_for_box_spawn = false
local wait_for_rift_spawn = false
local wait_for_boss_spawn = false
local use_cleric = false
local started = false
local running = false
local interrupted = false
local buying_cobalt = false
local buying_rubicund = false
local number_to_buy = 0
local sc_opener = nil
local wait_for_sc = nil
local function leader()
local self = windower.ffxi.get_player()
local party = windower.ffxi.get_party()
return (party.alliance_leader == self.id) or ((party.party1_leader == self.id) and (not party.alliance_leader)) or (not party.party1_leader)
end
local function get_mob_by_name(name)
local mobs = windower.ffxi.get_mob_array()
for i, mob in pairs(mobs) do
if (mob.name == name) and (math.sqrt(mob.distance) < 6) then
return mob
end
end
end
local function poke_thing(thing)
local npc = get_mob_by_name(thing)
if npc and npc.distance <= interact_distance_square then
local p = packets.new('outgoing', 0x1a, {
['Target'] = npc.id,
['Target Index'] = npc.index,
})
packets.inject(p)
end
end
local function poke_rift()
local npc = get_mob_by_name('Planar Rift')
if npc and npc.distance <= interact_distance_square then
log('poke rift')
wait_for_rift_0x34 = true
poke_thing('Planar Rift')
end
end
local function poke_officer()
local npc = get_mob_by_name('Voidwatch Officer')
if npc and npc.distance <= interact_distance_square then
log('poke officer')
wait_for_officer_0x34 = true
poke_thing('Voidwatch Officer')
end
end
local function poke_ardrick()
local npc = get_mob_by_name('Ardrick')
if npc and npc.distance <= interact_distance_square then
log('poke_ardrick')
wait_for_adrick_0x34 = true
poke_thing('Ardrick')
end
end
local function poke_box()
local npc = get_mob_by_name('Riftworn Pyxis')
if npc and npc.distance <= interact_distance_square then
log('poke_box')
wait_for_box_0x34 = true
poke_thing('Riftworn Pyxis')
end
end
local function leader()
local self = windower.ffxi.get_player()
local party = windower.ffxi.get_party()
return (party.alliance_leader == self.id) or ((party.party1_leader == self.id) and (not party.alliance_leader)) or (not party.party1_leader)
end
local function reset(new_id, old_id)
wait_for_adrick_0x34 = false
wait_for_box_0x34 = false
wait_for_officer_0x34 = false
wait_for_rift_0x34 = false
wait_for_box_spawn = false
wait_for_rift_spawn = false
wait_for_boss_spawn = false
use_cleric = false
started = false
running = false
interrupted = false
buying_cobalt = false
buying_rubicund = false
number_to_buy = 0
sc_opener = nil
wait_for_sc = nil
end
local function trade_cells()
log('trade cells')
use_cleric = false
local npc = get_mob_by_name('Planar Rift')
if npc and npc.distance <= interact_distance_square then
local trade = packets.new('outgoing', 0x36, {
['Target'] = npc.id,
['Target Index'] = npc.index,
})
local remaining = {
cobalt = settings["cobalt"],
rubicund = settings["rubicund"],
phase = settings["displacers"],
}
local idx = 1
local n = 0
local inventory = windower.ffxi.get_items(0)
for index = 1, inventory.max do
if (remaining.cobalt > 0) and (inventory[index].id == cells['Cobalt Cell']) then
if (inventory[index].count >= remaining.cobalt) then
trade['Item Index %d':format(idx)] = index
trade['Item Count %d':format(idx)] = 1
idx = idx + 1
remaining.cobalt = 0
n = n + 1
end
elseif (remaining.rubicund > 0) and (inventory[index].id == cells['Rubicund Cell']) then
if (inventory[index].count >= remaining.rubicund) then
trade['Item Index %d':format(idx)] = index
trade['Item Count %d':format(idx)] = 1
idx = idx + 1
remaining.rubicund = 0
n = n + 1
end
elseif (remaining.phase > 0) and (inventory[index].id == cells['Phase Displacer']) then
local count = 0
if (inventory[index].count >= remaining.phase) then
count = remaining.phase
end
trade['Item Index %d':format(idx)] = index
trade['Item Count %d':format(idx)] = count
idx = idx + 1
remaining.phase = remaining.phase - count
n = n + count
end
end
if n ~= settings['cobalt'] + settings['rubicund'] + settings['displacers'] then
log("not enough cells/displacers")
reset()
if settings['warpwhendone'] then windower.send_command('input /item "Instant Warp" <me>') end
return
end
trade['Number of Items'] = n
packets.inject(trade)
if leader() then
coroutine.schedule(poke_rift, 1.5)
end
end
end
local function sparky_purge()
log("sparky purge")
windower.send_command('input //sparky purge')
end
local function start_fight()
if not interrupted then
log('start fight')
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = phase_cell_options[settings["displacers"]],
['_unknown1'] = 0,
})
packets.inject(p)
local party = windower.ffxi.get_party()
if skillchain_opener:contains(party.p0.name) then
sc_opener = party.p0.mob.id
elseif skillchain_opener:contains(party.p1.name) then
sc_opener = party.p1.mob.id
elseif skillchain_opener:contains(party.p2.name) then
sc_opener = party.p2.mob.id
elseif skillchain_opener:contains(party.p3.name) then
sc_opener = party.p3.mob.id
elseif skillchain_opener:contains(party.p4.name) then
sc_opener = party.p4.mob.id
elseif skillchain_opener:contains(party.p5.name) then
sc_opener = party.p5.mob.id
else
sc_opener = nil
end
else
log('interrupted')
interrupted = false
end
end
local function buy_cell()
log('buying ' .. number_to_buy + 1 .. 'x12 cells')
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = voidwatch_officers[zone].option_index,
['_unknown1'] = cell_unknown,
})
packets.inject(p)
end
local function buy_phase()
log('buying ' .. number_to_buy .. ' phase displacers')
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = 1
})
if number_to_buy > 99 then
p['_unknown1'] = 99
number_to_buy = number_to_buy - 99
else
p['_unknown1'] = number_to_buy
number_to_buy = 0
end
packets.inject(p)
end
local function parse_menu_data(p)
npc_id = p['NPC']
npc_index = p['NPC Index']
menu_id = p['Menu ID']
zone = p['Zone']
end
local function get_everything()
log('get everything')
wait_for_rift_spawn = true
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = 10,
})
packets.inject(p)
if need_to_relinquish then
coroutine.schedule(poke_box, 1)
wait_for_box_0x34 = true
elseif settings["autosell"] then
coroutine.schedule(sparky_purge, 1)
end
if settings['refreshtrusts'] and windower.ffxi.get_party().party1_count < 6 then
log('resummon trusts')
windower.send_command('wait 2; input //tru ' .. settings['trustset'])
end
end
local function get_pulse(index, convert)
log('get everything')
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = index
})
if convert then
p['_unknown1'] = 1
end
packets.inject(p)
coroutine.schedule(poke_box, 1)
end
local function relinquish_everything()
log('relinquish everything')
local p = packets.new('outgoing', 0x5b, {
['Target'] = npc_id,
['Target Index'] = npc_index,
['Menu ID'] = menu_id,
['Zone'] = zone,
['Option Index'] = 9,
})
packets.inject(p)
if settings["autosell"] then
coroutine.schedule(sparky_purge, 1)
end
end
local function is_item_rare(id)
if res.items[id].flags['Rare'] then
return true
end
return false
end
local function have_item(id)
local items = windower.ffxi.get_items()
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
local function have_temp_item(id)
local items = windower.ffxi.get_items()
if items.enabled_temporary then end
for i = 1, items.temporary.count do
if items.temporary[i].id == id then
return true
end
end
return false
end
local function face_target()
local target = windower.ffxi.get_mob_by_index(windower.ffxi.get_player().target_index or 0)
local self_vector = windower.ffxi.get_mob_by_index(windower.ffxi.get_player().index or 0)
if target then
local angle = (math.atan2((target.y - self_vector.y), (target.x - self_vector.x))*180/math.pi)*-1
windower.ffxi.turn((angle):radian())
end
end
local function parse_incoming(id, data)
if started then
if id == 0x34 then
if wait_for_rift_0x34 then
interrupted = false
wait_for_rift_0x34 = false
wait_for_boss_spawn = true
local p = packets.parse('incoming', data)
parse_menu_data(p)
coroutine.schedule(start_fight, 0.1)
return true
elseif wait_for_box_0x34 then
wait_for_box_0x34 = false
local p = packets.parse('incoming', data)
if need_to_relinquish then
need_to_relinquish = false
parse_menu_data(p)
coroutine.schedule(relinquish_everything, 0.2)
return true
end
local got_pulse = false
for i = 1, 8 do
local item = p['Menu Parameters']:unpack('I', 1 + (i - 1)*4)
if not (item == 0) then
if pulse_items[item] then
log("got pulse")
got_pulse = true
parse_menu_data(p)
get_pulse(i, settings['converttocell'] or have_item(item))
return true
elseif is_item_rare(item) and have_item(item) then
need_to_relinquish = true
end
end
end
if not got_pulse then
parse_menu_data(p)
coroutine.schedule(get_everything, 1)
return true
end
end
elseif id == 0x38 and wait_for_box_spawn then
local p = packets.parse('incoming', data)
local mob = windower.ffxi.get_mob_by_id(p['Mob'])
if mob and (mob.name == 'Riftworn Pyxis') then
if p['Type'] == 'deru' then
wait_for_sc = nil
wait_for_box_spawn = false
coroutine.schedule(poke_box, 2)
end
end
elseif id == 0x5b then
local p = packets.parse('incoming', data)
local mob = windower.ffxi.get_mob_by_index(p['Index'])
if mob and voidwatch_mobs:contains(mob.name) then
log("mob spawn")
wait_for_boss_spawn = false
wait_for_rift_spawn = false
wait_for_box_spawn = true
windower.send_command('wait 1; input /target <bt>; wait 0.2; input /attack on')
coroutine.schedule(face_target, 1.5)
end
elseif id == 0xe then
if settings["autoloop"] and wait_for_rift_spawn then
local p = packets.parse('incoming', data)
local npc = windower.ffxi.get_mob_by_id(p['NPC'])
if npc and npc.name == 'Planar Rift' and npc.distance <= interact_distance_square then
wait_for_rift_spawn = false
log('rift spawn')
coroutine.schedule(trade_cells, 1)
end
end
elseif id == 0x2a then
local p = packets.parse('incoming', data)
if p['Message ID'] == 40285 then
-- param 1 + param 2 = blue, param 3 + param 4 = red
end
elseif id == 0x52 then
local p = packets.parse('incoming', data)
if p['Type'] == 2 and (wait_for_boss_spawn or wait_for_rift_0x34) then
interrupted = true
coroutine.schedule(poke_rift, 0.1)
end
end
end
if id == 0x34 then
if wait_for_officer_0x34 then
wait_for_officer_0x34 = false
local p = packets.parse('incoming', data)
parse_menu_data(p)
if voidwatch_officers[zone] then
number_to_buy = number_to_buy - 1
if buying_cobalt then
if number_to_buy == 0 then buying_cobalt = false end
cell_unknown = voidwatch_officers[zone].cobalt_unknown1
elseif buying_rubicund then
if number_to_buy == 0 then buying_rubicund = false end
cell_unknown = voidwatch_officers[zone].rubicund_unknown1
else
cell_unknown = nil
end
if cell_unknown then
coroutine.schedule(buy_cell, 0.1)
return true
else
log("Didn't set buying_cobalt or buying_rubicund")
end
else
log("No info for voidwatch officer in zone " .. zone)
end
elseif wait_for_adrick_0x34 then
wait_for_adrick_0x34 = false
local p = packets.parse('incoming', data)
parse_menu_data(p)
coroutine.schedule(buy_phase, 0.1)
return true
end
end
end
local function ws()
local command = 'input /ws "' .. settings['WS'] .. '" <t>'
if wait_for_sc and windower.ffxi.get_player().main_job == "THF" then
if windower.ffxi.get_ability_recasts()[66] == 0 then
command = 'input /ja "Trick Attack" <me>; wait 1; input /ws "' .. settings['WS'] .. '" <t>'
end
end
wait_for_sc = nil
windower.send_command(command)
end
local function do_ws()
face_target()
coroutine.schedule(ws, 0.1)
end
local function parse_action(action)
if started then
local mob = windower.ffxi.get_mob_by_id(action.actor_id)
if mob then
local player = windower.ffxi.get_player()
if player.in_combat and player.target_index then
local player_target = windower.ffxi.get_mob_by_index(player.target_index)
if player_target then
if settings['autows'] then
if mob.id == player_target.id and mob_stun_moves[mob.name] and can_stun then
local need_to_stun = false
if action.category == 7 and action.param == 24931 then
need_to_stun = mob_stun_moves[mob.name]:contains(res.monster_abilities[action.targets[1].actions[1].param].name)
elseif action.category == 8 and action.param == 24931 then
need_to_stun = mob_stun_moves[mob.name]:contains(res.spells[action.targets[1].actions[1].param].name)
end
if need_to_stun then
windower.send_command("input /ma Stun <t>")
elseif use_cleric then
use_cleric = false
windower.send_command("input /item \"Cleric's Drink\" <me>")
elseif player.vitals.tp >= settings["autowstp"] then
do_ws()
end
elseif action.actor_id == player.id and action.category == 1 then
if running then
running = false
windower.ffxi.run(false)
end
if mob_stun_moves[player_target.name] and can_stun then
if player.vitals.tp >= settings["autowstp"] then
if player_target.hpp >= 80 or player_target.hpp <= 15 then
do_ws()
else
local recasts = windower.ffxi.get_spell_recasts()
if recasts[252] > 2 then -- ws if stun got recast
do_ws()
end
end
end
else
if use_cleric then
use_cleric = false
windower.send_command("input /item \"Cleric's Drink\" <me>")
elseif wait_for_sc then
if os.time() > wait_for_sc and player.vitals.tp >= 1000 then
do_ws()
end
elseif player.vitals.tp >= settings["autowstp"] then
do_ws()
end
end
elseif sc_opener and action.category == 3
and action.targets[1].id == player_target.id then -- someone wsed the mob
if action.targets[1].actions[1].param > 0 then
if action.actor_id == sc_opener then
wait_for_sc = os.time() + settings['scdelay']
else
wait_for_sc = nil
end
end
end
end
end
else
for k,v in pairs(action.targets) do
if v.id == player.id then -- a mob doing anything to player
if wait_for_box_spawn then
log('retry attack boss')
windower.send_command("wait 2; input /attack on")
break
end
end
end
end
end
end
end
local function gain_buff(id)
if started then
local player = windower.ffxi.get_player()
if player.in_combat and player.target_index then
local player_target = windower.ffxi.get_mob_by_index(player.target_index)
if player_target and mob_stun_moves[player_target.name] then
if id == 6 then -- silence
log('using echo drops')
windower.send_command('input /item "Echo Drops" <me>')
end
end
end
end
end
local function check_stun()
local player = windower.ffxi.get_player()
can_stun = player.sub_job == "BLM" or player.sub_job == "DRK" or player.main_job == "BLM" or player.main_job == "DRK"
end
local function zone_change()
check_stun()
reset()
end
local function on_load()
check_stun()
end
local function parse_action_message(actor_id, target_id, actor_index, target_index, message_id, param_1, param_2, param_3)
if started then
if message_id == 5 then -- can't see target
face_target()
elseif message_id == 4 or message_id == 78 then -- out of range
face_target()
running = true
windower.ffxi.run(true)
end
end
end
local function handle_command(...)
local args = T{...}
if args[1] == "t" then
reset()
started = true
trade_cells()
elseif args[1] == "bc" then
number_to_buy = 1
if args[2] then
number_to_buy = tonumber(args[2])
if not number_to_buy then number_to_buy = 1 end
end
buying_cobalt = true
for i = 1, number_to_buy do
coroutine.schedule(poke_officer, (i-1) * 2)
end
elseif args[1] == "br" then
number_to_buy = 1
if args[2] then
number_to_buy = tonumber(args[2])
if not number_to_buy then number_to_buy = 1 end
end
buying_rubicund = true
for i = 1, number_to_buy do
coroutine.schedule(poke_officer, (i-1) * 2)
end
elseif args[1] == "bp" and args[2] then
number_to_buy = tonumber(args[2])
if number_to_buy then
if number_to_buy > 0 then
local count = math.ceil(number_to_buy / 99)
for i = 1, count do
coroutine.schedule(poke_ardrick, (i - 1) * 2)
end
else
log("Number must be more than 0")
end
end
elseif args[1] == "setp" and args[2] then
local number = tonumber(args[2])
if number then
if number >= 0 and number <= 5 then
settings["displacers"] = number
config.save(settings)
log("Using " .. number .. " of phase displacers each fight.")
else
log("Number must be between 0 and 5")
end
end
elseif args[1] == "autosell" then
settings['autosell'] = not settings['autosell']
config.save(settings)
log("Auto Sell changed to " .. tostring(settings['autosell']))
elseif args[1] == "autoloop" then
settings['autoloop'] = not settings['autoloop']
config.save(settings)
log("Auto Loop changed to " .. tostring(settings['autoloop']))
elseif args[1] == "autows" then
settings['autows'] = not settings['autows']
config.save(settings)
log("Auto WS changed to " .. tostring(settings['autows']))
elseif args[1] == "setws" and #args >= 2 then
local ws_name = ""
for i = 2, #args do
ws_name = ws_name .. args[i] .. " "
end
ws_name = string.sub(ws_name, 1, #ws_name - 1)
settings['WS'] = ws_name
config.save(settings)
log("WS changed to " .. settings['WS'])
elseif args[1] == "stop" then
log('stopping')
reset()
elseif args[1] == "converttocell" then
settings['converttocell'] = not settings['converttocell']
config.save(settings)
log("Convert to cell changed to " .. tostring(settings['converttocell']))
elseif args[1] == "usecleric" then
use_cleric = have_temp_item(5395)
log("Using Cleric Drink next opportunity: " .. tostring(use_cleric))
elseif args[1] == "setc" and args[2] then
local number = tonumber(args[2])
if number then
if number >= 0 and number <= 1 then
settings["cobalt"] = number
config.save(settings)
log("Using " .. number .. " cobalt cell each fight.")
else
log("Number must be between 0 and 1")
end
end
elseif args[1] == "setr" and args[2] then
local number = tonumber(args[2])
if number then
if number >= 0 and number <= 1 then
settings["rubicund"] = number
config.save(settings)
log("Using " .. number .. " rubicund cell each fight.")
else
log("Number must be between 0 and 1")
end
end
elseif args[1] == "settp" and args[2] then
local number = tonumber(args[2])
if number then
if number >= 1000 and number <= 3000 then
settings["autowstp"] = number
config.save(settings)
log("Auto WS at " .. number .. " TP.")
else
log("Number must be between 1000 and 3000")
end
end
elseif args[1] == "warpwhendone" then
settings['warpwhendone'] = not settings['warpwhendone']
config.save(settings)
log("Warp when done changed to " .. tostring(settings['warpwhendone']))
elseif args[1] == "trustset" and args[2] then
settings['trustset'] = args[2]
config.save(settings)
log("Trust set changed to " .. tostring(settings['trustset']))
elseif args[1] == "refreshtrusts" then
settings['refreshtrusts'] = not settings['refreshtrusts']
config.save(settings)
log("Refresh trusts changed to " .. tostring(settings['refreshtrusts']))
elseif args[1] == "scdelay" and args[2] then
local number = tonumber(args[2])
if number then
if number > 1 and number < 10 then
settings['scdelay'] = number
config.save(settings)
log("Skillchain delay changed to " .. tostring(settings['scdelay']))
else
log("Number must be between 1 and 10(?)")
end
end
else
notice('//vw t: trade cells and displacers and start fight')
notice('//vw bc (number): buy number * 12 cobalt cells from nearby Voidwatch Officer')
notice('//vw br (number): buy number * 12 rubicund cells from nearby Voidwatch Officer')
notice('//vw bp (number): buy (number) phase displacers from Ardrick')
notice('//vw setp (number): set number of phase displacers to use')
notice('//vw setc (number): set number of cobalt cells to use')
notice('//vw setr (number): set number of rubicund cells to use')
notice('//vw autosell: toggles whether to auto sell drops or not. Uses //sparky purge.')
notice('//vw autoloop: toggles whether to auto loop or not.')
notice('//vw autows: toggles whether to auto WS or not.')
notice('//vw converttocell: toggles whether to convert pulse to cells or not.')
notice('//vw setws: set the WS name to auto WS.')
notice('//vw settp: set the TP threshold for auto WS.')
notice('//vw warpwhendone: toggle warping when done. Uses a Scroll of Instant Warp.')
notice('//vw refreshtrusts: toggles whether to resummon trusts after battle.')
notice('//vw trustset (name): sets the name of the trust set. Uses Trusts addon to summon trusts.')
notice('//vw scdelay (number): sets the skillchain delay when a sc_opener is in the party.')
notice('//vw stop: stops all parsing of incoming packets.')
end
end
windower.register_event('addon command', handle_command)
windower.register_event('incoming chunk', parse_incoming)
windower.register_event('zone change', zone_change)
windower.register_event('action', parse_action)
windower.register_event('gain buff', gain_buff)
windower.register_event('load', on_load)
windower.register_event('action message', parse_action_message) |
--[[
DevelopPresets.lua
Object that represents develop settings from a catalog point of view.
--]]
local DevelopPresets, dbg, dbgf = Object:newClass{ className = "DevelopPresets", register=true }
--- Get
function DevelopPresets:getDevPresetNames()
local names = {}
local folders = LrApplication.developPresetFolders()
for i, folder in ipairs( folders ) do
local presets = folder:getDevelopPresets()
for i,v in ipairs( presets ) do
names[#names + 1] = v:getName()
end
end
return names
end
return DevelopPresets
|
--------------------------------
-- @module GLProgramState
-- @extend Ref
-- @parent_module cc
--------------------------------
-- Get the flag of vertex attribs used by OR operation.
-- @function [parent=#GLProgramState] getVertexAttribsFlags
-- @param self
-- @return unsigned int#unsigned int ret (return value: unsigned int)
--------------------------------
-- @overload self, int, vec4_table
-- @overload self, string, vec4_table
-- @function [parent=#GLProgramState] setUniformVec4
-- @param self
-- @param #string uniformName
-- @param #vec4_table value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Applies the specified custom auto-binding.<br>
-- param uniformName Name of the shader uniform.<br>
-- param autoBinding Name of the auto binding.
-- @function [parent=#GLProgramState] applyAutoBinding
-- @param self
-- @param #string uniformName
-- @param #string autoBinding
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, vec2_table
-- @overload self, string, vec2_table
-- @function [parent=#GLProgramState] setUniformVec2
-- @param self
-- @param #string uniformName
-- @param #vec2_table value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, vec3_table
-- @overload self, string, vec3_table
-- @function [parent=#GLProgramState] setUniformVec3
-- @param self
-- @param #string uniformName
-- @param #vec3_table value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Apply GLProgram, attributes and uniforms.<br>
-- param modelView The applied modelView matrix to shader.
-- @function [parent=#GLProgramState] apply
-- @param self
-- @param #mat4_table modelView
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Returns the Node bound to the GLProgramState
-- @function [parent=#GLProgramState] getNodeBinding
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- @overload self, int, long, vec4_table
-- @overload self, string, long, vec4_table
-- @function [parent=#GLProgramState] setUniformVec4v
-- @param self
-- @param #string uniformName
-- @param #long size
-- @param #vec4_table pointer
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Apply GLProgram, and built in uniforms.<br>
-- param modelView The applied modelView matrix to shader.
-- @function [parent=#GLProgramState] applyGLProgram
-- @param self
-- @param #mat4_table modelView
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Sets the node that this render state is bound to.<br>
-- The specified node is used to apply auto-bindings for the render state.<br>
-- This is typically set to the node of the model that a material is<br>
-- applied to.<br>
-- param node The node to use for applying auto-bindings.
-- @function [parent=#GLProgramState] setNodeBinding
-- @param self
-- @param #cc.Node node
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, int
-- @overload self, string, int
-- @function [parent=#GLProgramState] setUniformInt
-- @param self
-- @param #string uniformName
-- @param #int value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Sets a uniform auto-binding.<br>
-- This method parses the passed in autoBinding string and attempts to convert it<br>
-- to an enumeration value. If it matches to one of the predefined strings, it will create a<br>
-- callback to get the correct value at runtime.<br>
-- param uniformName The name of the material parameter to store an auto-binding for.<br>
-- param autoBinding A string matching one of the built-in AutoBinding enum constants.
-- @function [parent=#GLProgramState] setParameterAutoBinding
-- @param self
-- @param #string uniformName
-- @param #string autoBinding
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, long, vec2_table
-- @overload self, string, long, vec2_table
-- @function [parent=#GLProgramState] setUniformVec2v
-- @param self
-- @param #string uniformName
-- @param #long size
-- @param #vec2_table pointer
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Get the number of user defined uniform count.
-- @function [parent=#GLProgramState] getUniformCount
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- Apply attributes.<br>
-- param applyAttribFlags Call GL::enableVertexAttribs(_vertexAttribsFlags) or not.
-- @function [parent=#GLProgramState] applyAttributes
-- @param self
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Returns a new copy of the GLProgramState. The GLProgram is reused
-- @function [parent=#GLProgramState] clone
-- @param self
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- @{ <br>
-- Setter and Getter of the owner GLProgram binded in this program state.
-- @function [parent=#GLProgramState] setGLProgram
-- @param self
-- @param #cc.GLProgram glprogram
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, long, float
-- @overload self, string, long, float
-- @function [parent=#GLProgramState] setUniformFloatv
-- @param self
-- @param #string uniformName
-- @param #long size
-- @param #float pointer
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
--
-- @function [parent=#GLProgramState] getGLProgram
-- @param self
-- @return GLProgram#GLProgram ret (return value: cc.GLProgram)
--------------------------------
-- @overload self, string, unsigned int
-- @overload self, string, cc.Texture2D
-- @overload self, int, cc.Texture2D
-- @overload self, int, unsigned int
-- @function [parent=#GLProgramState] setUniformTexture
-- @param self
-- @param #int uniformLocation
-- @param #unsigned int textureId
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Apply user defined uniforms.
-- @function [parent=#GLProgramState] applyUniforms
-- @param self
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, float
-- @overload self, string, float
-- @function [parent=#GLProgramState] setUniformFloat
-- @param self
-- @param #string uniformName
-- @param #float value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, mat4_table
-- @overload self, string, mat4_table
-- @function [parent=#GLProgramState] setUniformMat4
-- @param self
-- @param #string uniformName
-- @param #mat4_table value
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- @overload self, int, long, vec3_table
-- @overload self, string, long, vec3_table
-- @function [parent=#GLProgramState] setUniformVec3v
-- @param self
-- @param #string uniformName
-- @param #long size
-- @param #vec3_table pointer
-- @return GLProgramState#GLProgramState self (return value: cc.GLProgramState)
--------------------------------
-- Get the number of vertex attributes.
-- @function [parent=#GLProgramState] getVertexAttribCount
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
-- returns a new instance of GLProgramState for a given GLProgram
-- @function [parent=#GLProgramState] create
-- @param self
-- @param #cc.GLProgram glprogram
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- @overload self, string, cc.Texture2D
-- @overload self, string
-- @function [parent=#GLProgramState] getOrCreateWithGLProgramName
-- @param self
-- @param #string glProgramName
-- @param #cc.Texture2D texture
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- gets-or-creates an instance of GLProgramState for a given GLProgram
-- @function [parent=#GLProgramState] getOrCreateWithGLProgram
-- @param self
-- @param #cc.GLProgram glprogram
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
--------------------------------
-- gets-or-creates an instance of GLProgramState for given shaders
-- @function [parent=#GLProgramState] getOrCreateWithShaders
-- @param self
-- @param #string vertexShader
-- @param #string fragShader
-- @param #string compileTimeDefines
-- @return GLProgramState#GLProgramState ret (return value: cc.GLProgramState)
return nil
|
local PANEL = {}
function PANEL:Init()
self.List = vgui.Create("DPanelList", self)
self.List:SetSpacing(1)
self.List:EnableVerticalScrollbar()
self.EntList = {}
self:ApplySchemeSettings()
end
function PANEL:PerformLayout(w, h)
local Border = 10
local Tall = 402
local iTop = Tall - Border
self.List:SetPos(Border, Border)
self.List:SetSize(w - Border * 2, iTop - Border * 2)
self.List:InvalidateLayout(true)
self:SetSize(w, Tall) -- TODO: Perform layout loop?
end
function PANEL:Paint(w, h)
local bgColor = Color(130, 130, 130, 255)
draw.RoundedBox(4, 0, 0, w, h, bgColor)
return true
end
function PANEL:Clear()
for k, panel in pairs(self.List.Items) do
panel:Remove()
end
self.List.Items = {}
end
function PANEL:SortByName()
table.sort(self.List.Items, function(a, b)
if b.name == nil then return false end
if a.name == nil then return true end
return b.name > a.name
end)
end
function PANEL:Populate()
self:Clear()
local n = 0
for k, v in pairs(list.Get(self.ListName)) do
local Button = vgui.Create("CAFButton", self)
n = n + 1
Button:SetCommands(self.ToolName, v.name, v.model, v.type, n)
self.List:AddItem(Button)
end
self:SortByName()
end
function PANEL:SetList(ToolName, ListName)
self.ToolName = ToolName
self.ListName = ListName
self:Populate()
end
vgui.Register("CAFControl", PANEL, "Panel") |
return {
postgres = {
up = [[
-- Unique constraint on "name" already adds btree index
DROP INDEX IF EXISTS "workspaces_name_idx";
]],
},
cassandra = {
up = [[]],
}
}
|
--=========== Copyright © 2017, Planimeter, All rights reserved. =============--
--
-- Purpose:
--
--============================================================================--
local ffi = require( "ffi" )
io.input( "HLLib.h" )
ffi.cdef( io.read( "*all" ) )
return ffi.load( ffi.os == "Windows" and "HLLib" or "hllib" )
|
gui = require('Gspot') -- import the library
--mainmenu = gui() -- create a gui instance. don't have to do this, but you may want a gui for each gamestate so they can talk to each other, and you won't have to recontsruct the gui every time you enter a state
font = love.graphics.newFont(192)
love.load = function()
love.keyboard.setKeyRepeat(500, 250)
love.graphics.setFont(font)
love.graphics.setColor(255, 192, 0, 128) -- just setting these so we know the gui isn't stealing our thunder
sometext = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
local textout = gui:typetext(sometext, {y = 32, w = 128})
local macros = {}
macros.white = {255, 255, 255}
macros.blue = {128, 128, 255}
macros.green = {0, 255, 0}
macros.red = {255, 0, 0}
macros.fontBig = love.graphics.newFont(60)
macros.fontCyrillic = love.graphics.newFont(14) -- use a cyrillic ttf here!
macros.fontMed = love.graphics.newFont(12)
macros.fontSmall = love.graphics.newFont(8)
macros['Harro_71.png'] = love.graphics.newImage('img.png')
local message = [[
Hello, {green}im {red}{fontBig}Richtext{fontMed} {Harro_71.png}
{white}UTF8 german: {green}Ähnlichkeit mit Übungen ist Öffentlich.
{fontCyrillic}{white}UTF8 cyrillic: {red}а б в г д е ё ж з и й к л м н о
{fontSmall}{green}V{red}i{green}v{red}a{green}m{red}u{green}s {red}commodo ultricies scelerisque. In hac habitasse platea dictumst.
{fontMed}{blue}Fusce tempor euismod mollis. Ut lobortis {white}commodo {green}nulla, ac adipiscing urna auctor quis. Cras facilisis cursus metus, vel cursus leo posuere non. Aliquam sit amet vulputate orci. Vivamus ut ante ante, {red}{green}non {fontSmall}{red}hendrerit {blue}quam. {white}Cras{white} ligula libero, {green}{white}elementum{green}{white} id posuere sollicitudin, gravida ut nibh
]]
local richtext = gui:richtext( message, {x=120, y = 140, w = 400}, nil, macros, macros.fontMed )
-- button
local button = gui:button('A Button', {x = 128, y = gui.style.unit, w = 128, h = gui.style.unit}) -- a button(label, pos, optional parent) gui.style.unit is a standard gui unit (default 16), used to keep the interface tidy
button.click = function(this, x, y) -- set element:click() to make it respond to gui's click event
gui:feedback('Clicky')
end
-- image
local image = gui:image('An Image', {160, 32, 0, 0}, nil, 'img.png') -- an image(label, pos, parent, love.image or path)
image.click = function(this, x, y)
gui:feedback(tostring(this.pos))
end
image.enter = function(this) this.Gspot:feedback("I'm In!") end -- every element has a reference to the gui instance which created it
image.leave = function(this) this.Gspot:feedback("I'm Out!") end
-- hidden element
local hidden = gui:hidden('', {128, 128, 128, 128}) -- creating a hidden element, to see it at work
hidden.tip = "Can't see me, but I still respond"
-- elements' children will be positioned relative to their parent's position
group1 = gui:collapsegroup('Group 1', {gui.style.unit, gui.style.unit * 3, 128, gui.style.unit}) -- group(label, pos, optional parent)
group1.style.fg = {255, 192, 0, 255}
group1.tip = 'Drag and drop' -- add a tooltip
group1.drag = true -- respond to default drag behaviour
group1.drop = function(this, bucket) -- respond to drop event
if bucket then gui:feedback('Dropped on '..tostring(bucket))
else gui:feedback('Dropped on nothing') end
end
-- option (must have a parent)
for i = 1, 3 do
option = gui:option('Option '..i, {0, gui.style.unit * i, 128, gui.style.unit}, group1, i) -- option(label, pos, parent, value) option stores this.value in this.parent.value when clicked, and is selected if this.value == this.parent.value
option.tip = 'Select '..option.value
end
-- another group, with various behaviours
group2 = gui:group('Group 2', {gui.style.unit, 128, 256, 256})
group2.drag = true
group2.tip = 'Drag, right-click, and catch'
group2.rclick = function(this) -- respond to right-click event by creating a button.
gui:feedback('Right-click')
local button = gui:button('A dynamic button', {love.mouse.getX(), love.mouse.getY(), 128, gui.style.unit}) -- button's parent will be the calling element
button.click = function(this) -- temp button to click before removed itself
gui:feedback('I\'ll be back!')
gui:rem(this)
end
end
group2.catch = function(this, ball) -- respond when an element is dragged and then dropped on this element
gui:feedback('Caught '..ball:type())
end
-- scrollgroup's children, excepting its scrollbar, will scroll
scrollgroup = gui:scrollgroup(nil, {0, gui.style.unit, 256, 256}, group2) -- scrollgroup will create its own scrollbar
scrollgroup.scrollh.tip = 'Scroll (mouse or wheel)' -- scrollgroup.scrollh is the horizontal scrollbar
scrollgroup.scrollv.tip = scrollgroup.scrollh.tip -- scrollgroup.scrollv is the vertical scrollbar
--scrollgroup.scroller:setshape('circle') -- to set a round handle
scrollgroup.scrollh.drop = function(this) gui:feedback('Scrolled to : '..this.values.current..' / '..this.values.min..' - '..this.values.max) end
scrollgroup.scrollv.drop = scrollgroup.scrollh.drop
-- initialize element.shape to 'circle' by specifying pos.r -- pos.w and pos.h will be set accordingly
local checkbox = gui:checkbox(nil, {r = 8}, scrollgroup) -- scrollgroup.scrollh.values.max, scrollgroup.scrollv.values.max will be updated when a child is added to scrollgroup
checkbox.click = function(this)
gui[this.elementtype].click(this) -- calling option's base click() to preserve default functionality, as we're overriding a reserved behaviour
if this.value then this.style.fg = {255, 128, 0, 255}
else this.style.fg = {255, 255, 255, 255} end
end
local checkboxlabel = gui:text('check', {x = 16}, checkbox, true) -- using the autosize flag to resize the element's width to fit the text
checkboxlabel.click = function(this, x, y)
this.parent:click()
end
local loader = gui:progress('Loading', {x = 64, y = 16, w = 64}, scrollgroup)
loader.updateinterval = 0.25 -- just setting this so we can see the progress bar at work
loader.done = function(this)
done = this:replace(gui:feedback('Done', {0, this.pos.y}, this.parent, false)) -- replace with a new element at the same level in draw order
end
for i = 1, 8 do
loader:add(function() return scrollgroup:addchild(gui:text(sometext, {w = 128}), 'grid') end)
--gui:text(sometext, {w = 128}) -- if not autosize, Gspot wraps text to element.pos.w and adjusts element.pos.h to fit it in
--element:addchild(element, 'vertical') -- using the autostack flag to reposition below existing child elements
--the two lines above accomplish the same as gui:text(str, {y = scrollgroup:getmaxh(), w = 128}, scrollgroup)
end
-- additional scroll controls
button = gui:button('up', {group2.pos.w, 0}, group2) -- a small button attached to the scrollgroup's group, because all of a scrollgroup's children scroll
button.click = function(this)
local scroll = scrollgroup.scrollv
scroll.values.current = math.max(scroll.values.min, scroll.values.current - scroll.values.step) -- decrement scrollgroup.scrollv.values.current by scrollgroup.scrollv.values.step, and the slider will go up a notch
scroll:drop()
end
button = gui:button('dn', {group2.pos.w, group2.pos.h + gui.style.unit}, group2)
button.click = function(this)
local scroll = scrollgroup.scrollv
scroll.values.current = math.min(scroll.values.max, scroll.values.current + scroll.values.step) -- this one increment's the scrollbar's values.current, moving the slider down a notch
scroll:drop()
end
-- text input
input = gui:input('Chat', {64, love.graphics.getHeight() - 32, 256, gui.style.unit})
input.keydelay = 500 -- these two are set by default for input elements, same as doing love.setKeyRepeat(element.keydelay, element.keyrepeat) but Gspot will return to current keyrepeat state when it loses focus
input.keyrepeat = 200 -- keyrepeat is used as default keydelay value if not assigned as above. use element.keyrepeat = false to disable repeating
input.done = function(this) -- Gspot calls element:done() when you hit enter while element has focus. override this behaviour with element.done = false
gui:feedback('I say '..this.value)
this.value = ''
this.Gspot:unfocus()
end
button = gui:button('Speak', {input.pos.w + gui.style.unit, 0, 64, gui.style.unit}, input) -- attach a button
button.click = function(this)
this.parent:done()
end
-- easy custom gui element
gui.boxy = function(this, label, pos, parent) -- careful not to override existing element types, and remember we're inside the gui's scope now
local group = this:group(label, pos, parent) -- using the easy method, our custom element should be based on an existing element type
group.tip = 'Drag, and right-click to spawn'
group.drag = true
group.rclick = function(this) gui:boxy('More custom goodness', {love.mouse.getX(), love.mouse.getY(), 128, 64}) end -- boxy will spawn more windows
local x = this:button('X', {x = group.pos.w - this.style.unit, y = 0, w = this.style.unit, h = this.style.unit}, group) -- adding a control
x.click = function(this) this.Gspot:rem(this.parent) end -- which removes this boxy
return group -- return the element
end
boxy = gui:boxy('Custom goodness', {256, 256, 128, 64}) -- now make one of our windows
-- or if you want more control
gui.mostbasic = {}
gui.mostbasic.load = function(this, Gspot, label, pos, parent)
local element = Gspot:element('group', label, pos, parent) -- Gspot:element(elementtype, label, pos, parent) gives the element its required values and inheritance. elementtype must be an existing type, or it won't work
return Gspot:add(element) -- Gspot:add() adds it to Gspot.elements, and returns the new element
end
gui.mostbasic.update = function(this, dt) end -- dt is passed along by Gspot:update(dt)
gui.mostbasic.draw = function(this, pos) end -- pos is the element's absolute position, supplied by Gspot:draw()
--show, hide, and update
text = gui:text('Hit F1 to show/hide', {love.graphics.getWidth() - 128, gui.style.unit, 128, gui.style.unit}) -- a hint (see love.keypressed() below)
showhider = gui:group('Mouse Below', {love.graphics.getWidth() - 128, gui.style.unit * 2, 128, 64})
counter = gui:text('0', {0, gui.style.unit, 128, 0}, showhider)
counter.count = 0
counter.update = function(this, dt) -- set an update function, which will be called every frame, unless we also specify element.updateinterval
if this.parent == gui.mousein then
this.count = this.count + dt
if this.count > 1 then this.count = 0 end
this.label = this.count
end
end
showhider:hide() -- display state will be propagated to children
end
love.update = function(dt)
gui:update(dt)
end
love.draw = function()
local bg = 'OBEY'
love.graphics.print(bg, 0, 240, math.pi / 4, 1, 1)
gui:draw()
love.graphics.print(bg, 320, 240, math.pi / 4, 1, 1)
end
love.keypressed = function(key, code)
if gui.focus then
gui:keypress(key, code) -- only sending input to the gui if we're not using it for something else
else
if key == 'return'then -- binding enter key to input focus
input:focus()
elseif key == 'f1' then -- toggle show-hider
if showhider.display then showhider:hide() else showhider:show() end
else
gui:feedback(key) -- why not
end
end
end
love.mousepressed = function(x, y, button)
gui:mousepress(x, y, button) -- pretty sure you want to register mouse events
end
love.mousereleased = function(x, y, button)
gui:mouserelease(x, y, button)
end |
local C, N, oUF = unpack(select(2, ...))
local playerClass = N.playerClass
local FormatTime = N.FormatTime
local UF = N.UnitFrame
-- Lua APIs
local unpack = unpack
local huge = math.huge
local tsort = table.sort
-- WoW APIs
local CreateFrame = CreateFrame
local GetTime = GetTime
local UnitAura = UnitAura
local UnitClass = UnitClass
-- aura bar timer
local function CreateAuraTimer(button, elapsed)
if (button.expiration) then
button.expiration = button.expiration - elapsed
button.bar:SetValue(button.expiration)
-- set text color
if (button.expiration > 0 and button.expiration < C.db.TimeThreshold) then
button.time:SetFormattedText(FormatTime(button.expiration))
if (button.expiration < 5) then
button.time:SetTextColor(1, .3, .3)
elseif (button.expiration < 10) then
button.time:SetTextColor(1, 1, 0)
else
button.time:SetTextColor(1, 1, 1)
end
else
button:SetScript('OnUpdate', nil)
button.time:SetText()
end
end
end
local function PostCreateIcon(auras, button)
auras.disableMouse = true -- disables tooltip
auras.enableCooldown = true -- cooldown spiral
button.cd.noCooldownCount = true -- hide CooldownCount
button.icon:SetTexCoord(.08, .92, .08, .92)
local overlay = CreateFrame('Frame', nil, button, 'BackdropTemplate')
overlay:SetPoint('TOPLEFT', button, -1, 1)
overlay:SetPoint('BOTTOMRIGHT', button, 1, -1)
overlay:SetBackdrop(C.pixelBD)
overlay:SetBackdropColor(unpack(C.maincolor))
overlay:SetBackdropBorderColor(unpack(C.maincolor))
overlay:SetFrameLevel(0)
auras.overlay = overlay
local bar = CreateFrame('StatusBar', nil, button, 'BackdropTemplate')
bar:SetStatusBarTexture(C.Normal)
bar:SetPoint('BOTTOMLEFT', button, 'BOTTOMRIGHT', 4, 0)
N:SetSize(bar, 150, 3)
button.bar = bar
local spark = bar:CreateTexture(nil, 'OVERLAY')
spark:SetTexture([[Interface\CastingBar\UI-CastingBar-Spark]])
spark:SetPoint('CENTER', bar:GetStatusBarTexture(), 'RIGHT')
spark:SetBlendMode('ADD')
spark:SetSize(8, 20)
bar.spark = spark
local bg = CreateFrame('StatusBar', nil, bar, 'BackdropTemplate')
bg:SetPoint('TOPLEFT', bar, -1, 1)
bg:SetPoint('BOTTOMRIGHT', bar, 1, -1)
bg:SetBackdrop(C.pixelBD)
bg:SetBackdropColor(.2, .2, .2, .5)
bg:SetBackdropBorderColor(unpack(C.maincolor))
bg:SetFrameLevel(0)
bar.bg = bg
local name = bar:CreateFontString(nil, 'OVERLAY')
name:SetFont(N:GetFont('NameFont'), C.SmallFS, C.FontF)
name:SetPoint('BOTTOMLEFT', bar, 'TOPLEFT', 2, -1)
name:SetWidth(bar:GetWidth() * 0.8)
name:SetJustifyH('LEFT')
name:SetWordWrap(false)
button.name = name
button.time = bar:CreateFontString(nil, 'OVERLAY')
button.time:SetFont(C.PlugFont, C.SmallFS, C.FontF)
button.time:SetPoint('BOTTOMRIGHT', bar, 'TOPRIGHT', 10, -1)
button.time:SetWidth(bar:GetWidth() * 0.2)
button.time:SetJustifyH('LEFT')
button.count:SetFont(C.PlugFont, C.SmallFS, C.FontF)
button.count:SetPoint('CENTER', button, 2, 0)
button.count:SetTextColor(unpack(C.countcolor))
end
local function PostUpdateIcon(auras, unit, button, index, _, duration, expiration, debuffType)
local name, _, _, _, _, _, caster = UnitAura(unit, index, button.filter)
button.name:SetText(name)
if (duration and duration > 0) then
button.expiration = expiration - GetTime()
button:SetScript('OnUpdate', CreateAuraTimer)
button.bar:SetMinMaxValues(0, duration)
button.bar.spark:Show()
-- set icon saturation
if (button.isPlayer) then
button.icon:SetDesaturated(false)
else
button.icon:SetDesaturated(true)
end
-- set bar color
if (button.isDebuff) then
local color = _G.DebuffTypeColor[debuffType or 'none']
button.bar:SetStatusBarColor(color.r, color.g, color.b, .7)
else
if C.db.Aurabar.Color then
local _, class = UnitClass(caster or unit)
local color = _G.RAID_CLASS_COLORS[class]
if class then
button.bar:SetStatusBarColor(color.r, color.g, color.b, .7)
end
else
button.bar:SetStatusBarColor(.15, .85, 1, .7)
end
end
else
button.time:SetText()
button.expiration = huge
button.bar:SetStatusBarColor(.2, .2, .2, .6)
button.bar.spark:Hide()
end
end
local function PreSetPosition(auras)
tsort(auras, N.SortAuras)
return 1, auras.createdIcons
end
local function AuraBarFilter(_, _, _, name, _, _, _, _, _, _, _, _, spellID)
if (not name) then return end
if C.AuraList[spellID] then
-- 'Shadow Vulnerability' Visible only for Warlock
if (spellID == 17800) then
if (playerClass == 'WARLOCK') then
return true
else
return
end
end
return true
end
end
local functions = {}
function functions:UpdateAuraBar()
local element = self.Auras
if C.db.Aurabar.Enable then
element.Holder:Show()
element.forceShow = C.db.forceShow
else
element.Holder:Hide()
end
element.numTotal = C.db.Aurabar.Amount
element.size = C.db.Aurabar.IconSize
if self:IsElementEnabled('Auras') then
element:ForceUpdate()
end
end
function UF:CreateAuraBar(frame)
N:Mixin(frame, functions)
local holder = CreateFrame('Frame', 'AuraBarHolder', frame)
local AuraBar = CreateFrame('Frame', nil, holder)
AuraBar.Holder = holder
AuraBar.numTotal = C.db.Aurabar.Amount
AuraBar.size = C.db.Aurabar.IconSize
AuraBar.spacing = 4
N:SetSize(AuraBar, AuraBar.size, (AuraBar.size + AuraBar.spacing) * AuraBar.numTotal)
AuraBar.CustomFilter = AuraBarFilter
AuraBar.PreSetPosition = PreSetPosition
AuraBar.PostCreateIcon = PostCreateIcon
AuraBar.PostUpdateIcon = PostUpdateIcon
frame.Auras = AuraBar
end |
---@class LspModule
---@field keys LspKeyMappers
---@field buffer_keys LspKeyMappers
---@field on_attaches OnAttachFn[]
---@field caps_setters CapsSetter[]
---@class LspKeyMapper
---@field [1] string key
---@field [2] string command
---@field [3] string introduce
---@alias LspKeyMappers table<string, LspKeyMapper>
---@alias OnAttachFn function(client:table,bufnr:number)
---@alias CapsSetter function(caps:table):table
-- local opts = { noremap=true, silent=true }
---@type LspModule
local lsp = {
keys = {
diag_float = { '<leader>e', vim.diagnostic.open_float, 'Open diagnostic floating window' },
diag_prev = { '[d', vim.diagnostic.goto_prev, 'Goto prev diagnostic' },
diag_next = { ']d', vim.diagnostic.goto_next, 'Goto next diagnostic' },
diag_loclist = { '<leader>q', vim.diagnostic.setloclist, 'Add buffer diagnostics to the location list.' },
},
buffer_keys = {
goto_decl = { 'gD', vim.lsp.buf.declaration, 'Goto declaration' },
goto_def = { 'gd', vim.lsp.buf.definition, 'Goto definition' },
hover = { 'K', vim.lsp.buf.hover, 'Display hover information' },
goto_impl = { 'gi', vim.lsp.buf.implementation, 'Goto implementation' },
sign_help = { '<C-k>', vim.lsp.buf.signature_help, 'Display signature information' },
add_folder = { '<leader>wa', vim.lsp.buf.add_workspace_folder, 'Add workspace folder' },
del_folder = { '<leader>wr', vim.lsp.buf.remove_workspace_folder, 'Remove workspace folder' },
list_folders = {
'<leader>wl',
function()
print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
end,
'List workspace folder',
},
type_def = { '<leader>D', vim.lsp.buf.type_definition, 'Goto type definition' },
rename = { '<leader>rn', vim.lsp.buf.rename, 'Rename symbol' },
code_action = { '<leader>ca', vim.lsp.buf.code_action, 'Code action' },
list_ref = { 'gr', vim.lsp.buf.references, 'List references' },
-- format = { '<leader>f', vim.lsp.buf.formatting, 'Format buffer' },
},
on_attaches = {},
caps_setters = {},
}
---set lsp function of the key
---@param mapper LspKeyMapper
---@param command string
function lsp.set_key_cmd(mapper, command)
mapper[2] = command
end
---set lsp key of the function
---@param mapper LspKeyMapper
---@param key string
function lsp.set_cmd_key(mapper, key)
mapper[1] = key
end
---add 'on_attach' hook
---@param fn OnAttachFn
function lsp.add_on_attach(fn)
lsp.on_attaches[#lsp.on_attaches + 1] = fn
end
---add a capabilities setter
---@param setter CapsSetter
function lsp.add_caps_setter(setter)
lsp.caps_setters[#lsp.caps_setters + 1] = setter
end
---mapping lsp keys
---@param bufnr number buffer number
local function mapping(bufnr)
local wk = require('which-key')
local mappings = {}
for _, mapper in pairs(lsp.keys) do
mappings[mapper[1]] = { mapper[2], mapper[3] }
end
wk.register(mappings, { silent = true })
local buf_mappings = {}
for _, mapper in pairs(lsp.buffer_keys) do
buf_mappings[mapper[1]] = { mapper[2], mapper[3] }
end
wk.register(buf_mappings, { buffer = bufnr })
end
---on attach function
---@param client table client object
---@param bufnr number buffer number
local function on_attach(client, bufnr)
mapping(bufnr)
for _, fn in ipairs(lsp.on_attaches) do
fn(client, bufnr)
end
end
local function capabilities()
local caps = vim.lsp.protocol.make_client_capabilities()
caps.textDocument.completion.completionItem.snippetSupport = true
caps.textDocument.completion.completionItem.resolveSupport = {
properties = { 'documentation', 'detail', 'additionalTextEdits' },
}
for _, setter in ipairs(lsp.caps_setters) do
caps = setter(caps)
end
return caps
end
---set lsp config
---@param name string language server string
---@param config table language server config
function lsp.set_config(name, config)
local lspconfig = require('lspconfig')
config.on_attach = on_attach
config.capabilities = capabilities()
lspconfig[name].setup(config)
end
function lsp.add_default(name, default_config)
local configs = require('lspconfig.configs')
if not configs[name] then
configs[name] = {
default_config = default_config,
}
end
end
function lsp.stop_all_clients()
vim.lsp.stop_client(vim.lsp.get_active_clients())
end
return lsp
|
--[[
@Author: Ermano Arruda (exa371 at bham dot ac dot uk), June 2016
Just a simple food class. Food can either be poisonous or not.
]]
require 'torch'
local Food = torch.class("Food")
function Food:__init(is_poison, world,ppm,vm)
self.vm = vm -- force magnitude
self.ppm = ppm
self.shape = love.physics.newCircleShape( 15 )
self.body = love.physics.newBody( world, 100, 0, "dynamic" )
self.body:setLinearDamping(0)
self.body:setMass(0.01)
self.fixture = love.physics.newFixture( self.body, self.shape, 1 )
self.fixture:setRestitution(1.0)
self.fixture:setFriction(0)
self.is_poison = is_poison
self.is_active = true
if is_poison then
self.color = {r=47, g=193, b=14}
else
self.color = {r=193, g=47, b=14}
end
self:reinitRandom()
end
function Food:toggleActive()
self.is_active = not self.is_active
end
function Food:reinitRandom()
self:setRandomVelocity()
self:setRandomPos()
end
function Food:setRandomVelocity()
local rf = torch.randn(2)
rf = rf:div(rf:norm())
local fx = rf[1]*self.ppm*self.vm
local fy = rf[2]*self.ppm*self.vm
self.body:setLinearVelocity(fx,fy)
--self.body:applyForce(fx,fy)
end
function Food:setRandomPos()
local rp = torch.rand(2)
local px = rp[1]*love.graphics.getWidth()
local py = rp[2]*love.graphics.getHeight()
self.body:setPosition(px, py)
end
function Food:draw()
love.graphics.setColor(self.color.r, self.color.g, self.color.b)
love.graphics.circle("fill", self.body:getX(), self.body:getY(), self.shape:getRadius())
end
|
-- Copyright © 2016, 2017, 2018, 2019, 2020 Emmanuel Roubion
--
-- Author: Emmanuel Roubion
-- URL: https://github.com/maanuair/dotfiles
-- This file is part of Emmanuel's Roubion dot files, released under
-- the MIT License as published by the Massachusetts Institute of Technology
--
-- These dotfiles are distributed in the hope they wil lbe useful, but
-- without any warranty. See the MIT License for more details
--
-- You should have received a copy of the MIT License along with this file.
-- If not, see https://opensource.org/licenses/mit-license.php
-- 8<-----
-- Some JIRA related helpers functions
-- Requirements and local vars
local utils = require('utils')
local jiraAccount = require ('jiraAccount')
local inspect = require('inspect')
local log = hs.logger.new('jira.lua', 'debug')
local jira = {}
local function startsWith(str, start)
return str:sub(1, #start) == start
end
-- Returns a Jira URL to browse the given issue Key
function jira.getBrowseUrl(key)
log.f("getBrowseUrl: Build url for issue key '%s'", key)
local url = "";
-- According to the issue key, we use either the base or alt URL
key = string.upper(key)
if string.len(key) == 0 or startsWith(key, jiraAccount.getDefaultProjectPrefix()) then
-- It uses the ! above, so that when the key is empty, the test fails into the else :-)
url = jiraAccount.getBaseUrl()
else
url = jiraAccount.getAltBaseUrl()
end
log.f("getBrowseUrl: use base URL '%s'", url)
url = string.format("%sbrowse/%s", url, key)
return url
end
-- Type JIRA issue browsing base url
function jira.typeBrowseUrl()
local url = jira.getBrowseUrl(utils.getTrimmedSelectedText())
hs.eventtap.keyStrokes(url)
end
-- Type a JIRA bug template
function jira.typeBugTemplate()
local source=[[
# *Steps to reproduce*
##
##
# *Expected result*
##
##
# *Actual*
##
##
# *Reproducibility*
## 100%
# *Traces*
## File attached foobar.log
## {code}Or traces captured directly pasted here, between "code" tag elements, maybe multi lines. {code}
## !Foobar Sreenshot.png|thumbnail!
# *Extra Information*
##
##
]]
hs.eventtap.keyStrokes(source)
end
-- Type a JIRA story template, in JIRA mark-up style
function jira.typeStoryTemplate()
local source=[[
*As a* <role> in <interface>
*I can* <do this>
*in order to* <get some result>
]]
hs.eventtap.keyStrokes(source)
end
-- Search the highlighted selection in Request.jira.com
function jira.search()
local url = jiraAccount.getBaseUrl() .. "issues/?jql=project IN " .. jiraAccount.getDefaultSearchProjects() .. " AND text ~ '" .. utils.getTrimmedSelectedText() .. "' AND issueType IN (Epic, Story, Bug) ORDER BY issueKey DESC"
log.f("Searching '%s'", url)
-- TODO: if empty, pop-up a chooser
utils.browseUrl(url)
end
-- Return the JIRA project matching the given issueKey
local function getProjectFromIssueKey(issueKey)
result = nil
defaultProject = nil
projectFound = false
-- Iterate over each JIRA server
for p,project in ipairs(jiraAccount.getJiraProjects()) do
log.f("getProjectFromIssueKey: iterating over JIRA server '%s'...", project["url"])
for k,key in ipairs(project["keys"]) do
log.f("getProjectFromIssueKey: > iterating over project key '%s'...", key)
if string.find(issueKey, key.."%-") ~= nil then
log.f("getProjectFromIssueKey: issueKey '%s' matches key '%s' of server '%s'.", issueKey, key, project["url"])
result = project
projectFound = true
break
end
end -- key
if projectFound then
break
end
end -- project
-- Project not found ?
if not projectFound then
-- No project matched, so use the fall back if it exists
log.f("getProjectFromIssueKey: could not find a matching project for issueKey '%s', check fall back project", issueKey)
project = getProjectFromIssueKey("*-123")
if project ~= nil then
projectFound = true
end
end
if not projectFound then
log.f("getProjectFromIssueKey: could not match issue key '%s'.", issueKey)
end
return result
end
local function notifyJiraProjectNotFound(infoText)
hs.notify.new({
title = "JIRA project not found",
informativeText = infoText
}):send()
end
-- Return the URL to browse for the given project and issueKey, or nil when not found.
local function getUrlForProjectAndIssueKey(project, issueKey)
result = nil
-- Any project ?
if project == nil
then
log.f("getUrlFromIssueKey: no project given with issueKey '%s'. Abort.", issueKey)
notifyJiraProjectNotFound("No URL found for issueKey '".. issueKey .. "'. \nAborted. ")
else
result = project["url"] .. "/browse/" .. issueKey
end
return result
end
-- Browse the issue key currently highlighted selection, or pop up a chooser
function jira.browseIssue()
local issueKey = utils.getTrimmedSelectedText()
if string.len(issueKey) == 0 then
log.f("browseIssue: no selection: invoking graphical chooser")
lookupJiraIssue()
else
-- Transform to upper case, in case it is needed...
issueKey = string.upper(issueKey)
log.f("browseIssue: got selection '%s'", issueKey)
-- Find the corresponding project
project = getProjectFromIssueKey(issueKey)
if project ~= nil then
url = getUrlForProjectAndIssueKey(project, issueKey)
log.f("browseIssue: browse issue '%s' at url '%s'.", issueKey, url)
utils.browseUrl(url)
else
log.f("browseIssue: no matching project for issueKey '%s'", issueKey)
notifyJiraProjectNotFound("No project for issue key '".. issueKey .. "'.")
end
end
end
-- Below from https://github.com/CasperKoning/dothammerspoon/blob/master/jira.lua
-- Jira viewer: (also see https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-version-2-tutorial)
function createAuthorisationRequestBody()
log.f("createAuthorisationRequestBody(): entering")
local s = '{ "username": "' .. hs.http.encodeForQuery(jiraAccount.getUsername()) .. '", "password": "' .. hs.http.encodeForQuery(jiraAccount.getPassword()) .. '" }'
-- log.f("createAuthorisationRequestBody(): JSON auth payload is: \n%s", s)
return s
end
function getSession()
log.f("getSession(): entering")
-- Prepare request
local url = jiraAccount.getBaseUrl() .. 'rest/auth/latest/session'
local auth = createAuthorisationRequestBody()
local headers = { ["Content-Type"] = "application/json" }
log.f("getSession(): requesting session as follows:")
log.f(" url: %s", url)
log.f(" payload: %s", auth)
log.f(" headers: %s", inspect(headers))
-- Perform request
status, body, returnedHeaders = hs.http.post(jiraAccount.getBaseUrl() .. 'rest/auth/latest/session', auth, headers)
log.f("getSession(): request returned:")
log.f(" status: %s", status)
log.f(" body: %s", body)
log.f(" headers: %s", inspect(returnedHeaders))
-- Check result
if status == 200 then
-- Parse result
local json = hs.json.decode(body)
log.f("getSession(): got result: %s", inspect(json))
-- Extract useful part
session = json["session"]
return session["name"], session["value"]
else
return nil, nil
end
end
function clearTable (t)
while #t ~= 0 do rawset(t, #t, nil) end
end
function lookupJiraIssue()
sessionName, sessionValue = getSession()
if (sessionName ~= nil and sessionValue ~= nil) then
log.f("lookupJiraIssue(): got a valid session.")
local cookieHeaders = { ["cookie"] = sessionName .. "=" .. sessionValue, ["Content-Type"] = "application/json" }
local picker = hs.chooser.new(function(userInput)
-- When user chose an item in the proposed list
if userInput ~= nil then
log.f("chooser: user chose '%s'", inspect(userInput))
if userInput["key"] ~= Nil then
local url = jira.getBrowseUrl(userInput["key"])
log.f("chooser: user chose '%s', browsing to '%s'", userInput["key"], url)
hs.execute("open " .. url)
end
end
end)
picker:query(jiraAccount.getDefaultIssueSearch())
local results = {}
picker:queryChangedCallback(
function(q)
if q == jiraAccount.getDefaultIssueSearch() then
-- Do nothing :-)
clearTable(results)
table.insert(results, { text = q, subText = "Please type a valid key...", key = q })
picker:rows(1) -- Set, but UI will not update acordingly, c.f. https://github.com/Hammerspoon/hammerspoon/issues/1725
picker:choices(results)
elseif string.len(q) > 3 and string.match(string.sub(q, 4), "[^%d]") == nil then
-- Search for a JIRA key
log.f("queryChangedCallback(): search for query '%s'", q)
hs.http.asyncGet(
getJiraQueryUrl(q),
cookieHeaders,
function(status, body, headers)
log.f("getSession(): request returned:")
log.f(" status: %s", status)
log.f(" body: %s", body)
log.f(" headers: %s", inspect(headers))
if status == 200 then
json = hs.json.decode(body)
if json["fields"] ~= nil then
key = json["key"]
summary = json["fields"]["summary"]
else
key = "No result found (should not hapen !)"
summary = "Key " .. q .. "cannot be found"
end
else
key = "HTTP status code " .. status
summary = "Unexpected HTTP status code"
end
clearTable(results)
table.insert(results, { text = key, subText = summary, key = key })
picker:rows(1) -- Set, but UI will not update acordingly, c.f. https://github.com/Hammerspoon/hammerspoon/issues/1725
picker:choices(results)
end
)
else
-- Search for non JIRA key: for now, we jsut don't search :)
log.f("queryChangedCallback(): won't search for query '%s'", q)
local summary = q .. " is not a valid key"
clearTable(results)
table.insert(results, { text = q, subText = summary, key = q })
picker:rows(1) -- Set, but UI will not update acordingly, c.f. https://github.com/Hammerspoon/hammerspoon/issues/1725
picker:choices(results)
end
end
)
picker:rows(1)
picker:show()
else
log.f("lookupJiraIssue(): could not get a valid session.")
notify = hs.notify.new()
notify:title("Jira")
notify:informativeText("Could not get authorization")
notify:send()
end
end
function getJiraQueryUrl(q)
local url = string.format("%s%s%s", jiraAccount.getBaseUrl(), "rest/api/latest/issue/", q)
log.f("jiraQuey(): return url '%s'", url)
return url
end
return jira
|
-- © 2021 Emmanuel Lajeunesse
-- Roblox Services --
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- Module
local DebuGui = require(ReplicatedStorage.DebuGui)
-- Get Existing Window
local Gui1 = DebuGui.WaitForWindow('Core')
-- This should end up at the bottom after everything from example 1 is finished
Gui1.AddBool('NewWindowBool', true).SetName('Racing Condition Test') |
---------------------------------------------------------------------------------------------------
-- User story: TBD
-- Use case: TBD
--
-- Requirement summary:
-- TBD
--
-- Description:
-- In case:
-- 1) Application is registered with PROJECTION appHMIType
-- 2) and starts audio services
-- 3) HMI rejects StartStream
-- SDL must:
-- 1) end service
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/MobileProjection/Phase1/common')
local runner = require('user_modules/script_runner')
local events = require('events')
local constants = require('protocol_handler/ford_protocol_constants')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local appHMIType = "PROJECTION"
--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = { appHMIType }
--[[ Local Functions ]]
local function ptUpdate(pTbl)
pTbl.policy_table.app_policies[common.getConfigAppParams().fullAppID].AppHMIType = { appHMIType }
end
local function startService()
common.getMobileSession():StartService(11)
local EndServiceEvent = events.Event()
EndServiceEvent.matches =
function(_, data)
return data.frameType == constants.FRAME_TYPE.CONTROL_FRAME and
data.serviceType == constants.SERVICE_TYPE.VIDEO and
data.sessionId == common.getMobileSession().sessionId and
data.frameInfo == constants.FRAME_INFO.END_SERVICE
end
common.getMobileSession():ExpectEvent(EndServiceEvent, "Expect EndServiceEvent")
:Do(function()
common.getMobileSession():Send({
frameType = constants.FRAME_TYPE.CONTROL_FRAME,
serviceType = constants.SERVICE_TYPE.VIDEO,
frameInfo = constants.FRAME_INFO.END_SERVICE_ACK
})
end)
common.getHMIConnection():ExpectRequest("Navigation.StartStream")
:Do(function(_, data)
local function response()
common.getHMIConnection():SendError(data.id, data.method, "REJECTED", "Request is rejected")
end
RUN_AFTER(response, 550)
end)
:Times(4)
common.getHMIConnection():ExpectRequest("Navigation.StopStream")
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Set StartStreamRetry value to 3,500", common.setSDLIniParameter, { "StartStreamRetry", "3,500" })
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("PolicyTableUpdate with HMI types", common.policyTableUpdate, { ptUpdate })
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("Stop video service by rejecting StartStream", startService)
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local self = {}
mUI.RenderEngine = self
self.events = {}
function self:Listen(event,id,callback,priority)
self.events[event] = self.events[event] or {}
for _,data in ipairs(self.events[event]) do
if data.id == id then
data.callback = callback
data.priority = priority or 100
return
end
end
self.events[event][#self.events[event]+1] = {
callback = callback,
id = id,
priority = priority or 100
}
end
function self:Emit(event,...)
self.events[event] = self.events[event] or {}
table.sort(self.events[event],function(t1,t2)
return t1.priority < t2.priority
end)
for _,data in ipairs(self.events[event]) do
if data.callback(...) then return end
end
end
self.renderers = {}
function self:registerRenderer(identifier,callback)
self.renderers[identifier] = callback
end
function self:registerInternalTag(identifier)
self.renderers[identifier] = false
end
function self:protectedTagCall(tag,fn,...)
return xpcall(fn,function(err)
ErrorNoHalt("Unable to render "..tag.identifier.." at line "..tag.token.line.." col "..tag.token.col.."\n"..err.."\n")
end,...)
end
function self:renderInternal(tag,template)
if self.renderers[tag.identifier] then
self:protectedTagCall(tag,self.renderers[tag.identifier],tag,template)
else
ErrorNoHalt("Unable to render "..tag.identifier.." at line "..tag.token.line.." col "..tag.token.col.."\n")
end
end
function self:walk(tag,template)
tag.template = template
if self.renderers[tag.identifier] == false then return end
self:protectedTagCall(tag,self.Emit,self,"PreRender",tag,template)
if mUI.ViewManager:IsNullView() then return end
self:renderInternal(tag,template)
self:protectedTagCall(tag,self.Emit,self,"PostRender",tag,template)
if tag.renderData.canRenderChildren then
self:protectedTagCall(tag,self.Emit,self,"EnterChild",tag,template)
for _,child in ipairs(tag.children) do
self:protectedTagCall(tag,self.Emit,self,"OnChild",child,tag,template)
self:walk(child,template)
end
self:protectedTagCall(tag,self.Emit,self,"ExitChild",tag,template)
end
end
function self:Render(base,template)
for _,child in ipairs(base.children) do
self:walk(child,template)
end
if #mUI.ViewManager.viewStack ~= 1 then error("View stack leak!!")mUI.ViewManager.viewStack = {mUI.ViewManager.defaultView} end
end
|
-- TODO: THIS IS NOT DONE, IT IS NOT FULLY IMPLEMENTED.
require "resty.nettle.types.asn1"
local lib = require "resty.nettle.hogweed"
local band = require "bit".band
local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local ffi_cdef = ffi.cdef
local ffi_typeof = ffi.typeof
local tonumber = tonumber
local floor = math.floor
local fmod = math.fmod
ffi_cdef[[
enum asn1_iterator_result nettle_asn1_der_iterator_first(struct asn1_der_iterator *iterator, size_t length, const uint8_t *input);
enum asn1_iterator_result nettle_asn1_der_iterator_next(struct asn1_der_iterator *iterator);
enum asn1_iterator_result nettle_asn1_der_decode_constructed(struct asn1_der_iterator *i, struct asn1_der_iterator *contents);
enum asn1_iterator_result nettle_asn1_der_decode_constructed_last(struct asn1_der_iterator *i);
enum asn1_iterator_result nettle_asn1_der_decode_bitstring(struct asn1_der_iterator *i, struct asn1_der_iterator *contents);
enum asn1_iterator_result nettle_asn1_der_decode_bitstring_last(struct asn1_der_iterator *i);
int nettle_asn1_der_get_uint32(struct asn1_der_iterator *i, uint32_t *x);
]]
local ctx = ffi_typeof "struct asn1_der_iterator"
local uint = ffi_new "uint32_t[1]"
local decoders = {
[lib.ASN1_BOOLEAN] = function(context)
end,
[lib.ASN1_INTEGER] = function(context)
end,
[lib.ASN1_BITSTRING] = function(context)
end,
[lib.ASN1_OCTETSTRING] = function(context)
end,
[lib.ASN1_NULL] = function(context)
end,
[lib.ASN1_IDENTIFIER] = function(context)
end,
[lib.ASN1_REAL] = function(context)
end,
[lib.ASN1_ENUMERATED] = function(context)
end,
[lib.ASN1_UTF8STRING] = function(context)
end,
[lib.ASN1_SEQUENCE] = function(context)
end,
[lib.ASN1_SET] = function(context)
end,
[lib.ASN1_PRINTABLESTRING] = function(context)
end,
[lib.ASN1_TELETEXSTRING] = function(context)
end,
[lib.ASN1_IA5STRING] = function(context)
end,
[lib.ASN1_UTC] = function(context)
end,
[lib.ASN1_UNIVERSALSTRING] = function(context)
end,
[lib.ASN1_BMPSTRING] = function(context)
end,
}
local function integer(context)
lib.nettle_asn1_der_get_uint32(context, uint)
return tonumber(uint[0])
end
local function identifier(context)
local oid = {}
local ind = 0
local pos = 0
local lst = context.length - 1
local str = context.data
if pos <= lst then
local oct = str[pos]
oid[2] = fmod(oct, 40)
oid[1] = floor((oct - oid[2]) / 40)
ind = 2
pos = pos + 1
end
while pos <= lst do
local c = 0
local oct
repeat
oct = str[pos]
pos = pos + 1
c = c * 128 + band(0x7F, oct)
until oct < 128
ind = ind + 1
oid[ind] = c
end
return oid
end
local asn1 = {}
asn1.__index = asn1
local function parse(state)
local i = 1
while i > 0 do
if state[i][2] == lib.ASN1_ITERATOR_CONSTRUCTED then
if state[i][1].pos == state[i][1].buffer_length then
state[i][2] = lib.nettle_asn1_der_decode_constructed_last(state[i][1])
else
i = i + 1
state[i] = { ffi_new(ctx) }
state[i][2] = lib.nettle_asn1_der_decode_constructed(state[i-1][1], state[i][1])
end
elseif state[i][2] == lib.ASN1_ITERATOR_PRIMITIVE then
local t = state[i][1].type
if t == lib.ASN1_BOOLEAN then
print "ASN1_BOOLEAN"
elseif t == lib.ASN1_INTEGER then
print "ASN1_INTEGER"
print(" number: ", integer(state[i][1]))
elseif t == lib.ASN1_BITSTRING then
print "ASN1_BITSTRING"
if state[i][1].pos == state[i][1].buffer_length then
--state[i][2] = lib.nettle_asn1_der_decode_bitstring_last(state[i][1])
--state[i][1] = state[i][1]
else
local s2 = {{ ffi_new(ctx) }}
s2[1][2] = lib.nettle_asn1_der_decode_bitstring(state[i][1], s2[1][1])
parse(s2)
end
elseif t == lib.ASN1_OCTETSTRING then
print "ASN1_OCTETSTRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_NULL then
print "ASN1_NULL"
elseif t == lib.ASN1_IDENTIFIER then
print "ASN1_IDENTIFIER"
print(" data: ", table.concat(identifier(state[i][1]), "."))
elseif t == lib.ASN1_REAL then
print "ASN1_REAL"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_ENUMERATED then
print "ASN1_ENUMERATED"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_UTF8STRING then
print "ASN1_UTF8STRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_SEQUENCE then
print "ASN1_SEQUENCE"
elseif t == lib.ASN1_SET then
print "ASN1_SET"
elseif t == lib.ASN1_PRINTABLESTRING then
print "ASN1_PRINTABLESTRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_TELETEXSTRING then
print "ASN1_TELETEXSTRING"
elseif t == lib.ASN1_IA5STRING then
print "ASN1_IA5STRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_UTC then
print "ASN1_UTC"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_UNIVERSALSTRING then
print "ASN1_UNIVERSALSTRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
elseif t == lib.ASN1_BMPSTRING then
print "ASN1_BMPSTRING"
print(" data: ", ffi_str(state[i][1].data, state[i][1].length))
else
print "UNKNOWN"
end
state[i][2] = lib.nettle_asn1_der_iterator_next(state[i][1])
elseif state[i][2] == lib.ASN1_ITERATOR_END then
print("ASN1_ITERATOR_END")
state[i] = nil
i = i - 1
if i ~= 0 then
state[i][2] = lib.ASN1_ITERATOR_PRIMITIVE
end
elseif state[i][2] == lib.ASN1_ITERATOR_ERROR then
print("ASN1_ITERATOR_ERROR")
state[i] = nil
i = i - 1
end
end
end
function asn1.decode(input)
local state = {{ ffi_new(ctx) }}
state[1][2] = lib.nettle_asn1_der_iterator_first(state[1][1], #input, input)
parse(state)
end
return asn1
|
local shell = require("shell")
local fs = require("filesystem")
local args = shell.parse(...)
local ec = 0
if #args == 0 then
repeat
local read = io.read("*L")
if read then
io.write(read)
end
until not read
else
for i = 1, #args do
local arg = args[i]
if fs.isDirectory(arg) then
io.stderr:write(string.format('cat %s: Is a directory\n', arg))
ec = 1
else
local file, reason = args[i] == "-" and io.stdin or io.open(shell.resolve(args[i]))
if not file then
io.stderr:write(string.format("cat: %s: %s\n",args[i],tostring(reason)))
ec = 1
else
repeat
local line = file:read("*L")
if line then
io.write(line)
end
until not line
file:close()
end
end
end
end
return ec
|
//afkkick default config
local function SetupDefaultConfig()
local DefaultConfig = { }
DefaultConfig.kAFKKickDelay = 150
DefaultConfig.kAFKKickCheckDelay = 5
DefaultConfig.kAFKKickMinimumPlayers = 5
DefaultConfig.kAFKKickWarning1 = 30
DefaultConfig.kAFKKickWarning2 = 10
DefaultConfig.kMonitoredTeams = { 0, 1, 2, 3 }
return DefaultConfig
end
DAK:RegisterEventHook("PluginDefaultConfigs", {PluginName = "afkkick", DefaultConfig = SetupDefaultConfig })
local function SetupDefaultLanguageStrings()
local DefaultLangStrings = { }
DefaultLangStrings["AFKKickClientMessage"] = "You are being kicked for idling for more than %d seconds."
DefaultLangStrings["AFKKickMessage"] = "%s kicked from the server for idling more than %d seconds."
DefaultLangStrings["AFKKickDisconnectReason"] = "Kicked from the server for idling more than %d seconds."
DefaultLangStrings["AFKKickReturnMessage"] = "You are no longer flagged as idle."
DefaultLangStrings["AFKKickWarningMessage1"] = "You will be kicked in %d seconds for idling."
DefaultLangStrings["AFKKickWarningMessage2"] = "You will be kicked in %d seconds for idling."
return DefaultLangStrings
end
DAK:RegisterEventHook("PluginDefaultLanguageDefinitions", SetupDefaultLanguageStrings) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.