content stringlengths 5 1.05M |
|---|
include("terms")
style =
{["off_color"] = "fff",
["on_color"] = "fff",
["line_color"] = "000",
["line_width"] = "2"};
meas = {"\(^\circ\)", "'"}
numb = {"\(\small\alpha\)", "\(\small\beta\)", "\(\small\gamma\)", "\(\small\alpha_1\)", "\(\small\beta_1\)", "\(\small\gamma_1\)" }
name = {"BC", "AB", "AC"}
answ = {"=", ">", "<"}
ang_g = {}
ang_m = {}
ang = {}
sign = {""}
result = ""
reply = ""
ind = math.random(3)
ang_g[2] = 50 +(2 - ind) * math.random(30)
ang_m[2] = math.random(51) - 1
ang[2] = ang_g[2] * 60 + ang_m[2]
ang_g[1] = 178 - 2 * ang_g[2]
ang_m[1] = 120 - 2 * ang_m[2]
temp = math.floor(ang_m[1]/60)
ang_g[1] = ang_g[1] + temp
ang_m[1] = ang_m[1] - 60 * temp
ang[1] = ang_g[1] * 60 + ang_m[1]
ang_g[3] = ang_g[2]
ang_m[3] = ang_m[2]
ang[3] = ang[2]
ang_g[4] = 2 * ang_g[2]
ang_m[4] = 2 * ang_m[2]
temp = math.floor(ang_m[4]/60)
ang_g[4] = ang_g[4] + temp
ang_m[4] = ang_m[4] - 60 * temp
ang[4] = 2 * ang[2]
ang_g[5] = 179 - ang_g[2]
ang_m[5] = 60 - ang_m[2]
temp = math.floor(ang_m[5]/60)
ang_g[5] = ang_g[5] + temp
ang_m[5] = ang_m[5] - 60 * temp
ang[5] = ang_g[5] * 60 + ang_m[5]
ang_g[6] = ang_g[5]
ang_m[6] = ang_m[5]
ang[6] = ang[5]
ch = math.random(6)
quest = ang_g[ch] .. meas[1]
if (ang_m[ch] ~= 0) then
quest = quest .. " " .. ang_m[ch] .. meas[2]
end
if (ang[1] > 5400) then
result = "answer == '" .. msg1[3] .. "' " ..
"|| answer == '" .. msg2[3] .. "'" ;
ans = "answer = '" .. msg1[3] .. "' ";
else
if (ang[1] < 5400) then
result = "answer == '" .. msg1[1] .. "' " ..
"|| answer == '" .. msg2[1] .. "'" ;
ans = "answer = '" .. msg1[1] .. "' ";
else
result = "answer == '" .. msg1[2] .. "' " ..
"|| answer == '" .. msg2[2] .. "'" ;
ans = "answer = '" .. msg1[2] .. "' ";
end
end
if (ang[1] > ang[2]) then
sign[1] = answ[1]
sign[2] = answ[3]
reply = lib.check_string_case(name[2],30) .. " " .. " " .. lib.check_one_option_dropdown(answ, sign[1]) .. " " .. " " .. lib.check_string_case(name[3],30) .. " " .. lib.check_one_option_dropdown(answ, sign[2]) .. " " .. lib.check_string_case(name[1],30)
else
if (ang[1] < ang[2]) then
sign[1] = answ[3]
sign[2] = answ[1]
reply = lib.check_string_case(name[1],30) .. " " .. " " .. lib.check_one_option_dropdown(answ, sign[1]) .. " " .. " " .. lib.check_string_case(name[2],30) .. " " .. lib.check_one_option_dropdown(answ, sign[2]) .. " " .. lib.check_string_case(name[3],30)
else
sign[1] = answ[1]
sign[2] = answ[1]
reply = lib.check_string_case(name[1],30) .. " " .. " " .. lib.check_one_option_dropdown(answ, sign[1]) .. " " .. " " .. lib.check_string_case(name[2],30) .. " " .. lib.check_one_option_dropdown(answ, sign[2]) .. " " .. lib.check_string_case(name[3],30)
end
end
mycanvas = function(no)
ow = 5
w = 125
ov = 75
v = 20
lib.start_canvas(250, 100, "center")
lib.add_straight_path(v, ov, {{w+v+5*ow, 0}, {-ov, -3*v}, {-ov, 3*v} }, style, true, false)
lib.add_line(w+ov-2*ow, ov, v, 0, style, false, false)
lib.add_line(w-2*ow, v-ow, v, -v+4, style, false, false)
lib.add_input(ov+ow, 0, 50, 20, "A")
lib.add_input(v, ov, 50, 20, "B")
lib.add_input(w+2*v, ov, 50, 20, "C")
lib.add_input(ov+3*ow, 3*ow, 50, 30, numb[1])
lib.add_input(w-3*ow, ow, 50, 30, numb[4])
lib.add_input(2*v, ov-v, 50, 30, numb[2])
lib.add_input(ow, ov-v, 50, 30, numb[5])
lib.add_input(w+v-ow, ov-v, 50, 30, numb[3])
lib.add_input(w+2*(v+ow), ov-v, 50, 30, numb[6])
lib.end_canvas()
end
|
local mType = Game.createMonsterType("Raging mage")
local monster = {}
monster.description = "a raging mage"
monster.experience = 3250
monster.outfit = {
lookType = 416,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.health = 3500
monster.maxHealth = 3500
monster.race = "blood"
monster.corpse = 12678
monster.speed = 200
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 70,
health = 10,
damage = 10,
random = 10,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = true,
illusionable = false,
canPushItems = true,
canPushCreatures = true,
staticAttackChance = 80,
targetDistance = 1,
runHealth = 300,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.summon = {
maxSummons = 1,
summons = {
{name = "Golden Servant", chance = 50, interval = 2000, count = 1}
}
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Behold the all permeating powers I draw from this gate!!", yell = false},
{text = "ENERGY!!", yell = false},
{text = "I WILL RETURN!! My death will just be a door to await my homecoming, my physical hull will be... my... argh...", yell = false}
}
monster.loot = {
{id = 3031, chance = 97000, maxCount = 169},
{id = 3035, chance = 77400, maxCount = 9},
{id = 5911, chance = 31100},
{id = 239, chance = 26830, maxCount = 5},
{id = 238, chance = 23170, maxCount = 5},
{id = 3062, chance = 9760},
{id = 7443, chance = 6710, maxCount = 2},
{id = 8043, chance = 4880},
{id = 3049, chance = 4880}, -- Stealth ring
{id = 11454, chance = 4270},
{id = 3728, chance = 3600, maxCount = 4},
{id = 7368, chance = 1830, maxCount = 7},
{id = 3007, chance = 1830},
{id = 3006, chance = 1830},
{id = 3029, chance = 1830, maxCount = 5},
{id = 12803, chance = 1220},
{id = 2995, chance = 1220},
{id = 9045, chance = 1220},
{id = 3079, chance = 610},
{id = 9067, chance = 610},
{id = 5741, chance = 610},
{id = 8074, chance = 610}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -50},
{name ="thunderstorm rune", interval = 2000, chance = 35, minDamage = -100, maxDamage = -200, range = 7, target = true},
{name ="combat", interval = 2000, chance = 15, type = COMBAT_MANADRAIN, minDamage = -100, maxDamage = -200, range = 7, target = false},
{name ="energyfield", interval = 2000, chance = 15, range = 7, radius = 2, shootEffect = CONST_ANI_ENERGY, target = true}
}
monster.defenses = {
defense = 25,
armor = 25
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = -25},
{type = COMBAT_ENERGYDAMAGE, percent = 100},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 100},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = 0},
{type = COMBAT_DEATHDAMAGE , percent = 15}
}
monster.immunities = {
{type = "paralyze", condition = true},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType.onThink = function(monster, interval)
end
mType.onAppear = function(monster, creature)
if monster:getType():isRewardBoss() then
monster:setReward(true)
end
end
mType.onDisappear = function(monster, creature)
end
mType.onMove = function(monster, creature, fromPosition, toPosition)
end
mType.onSay = function(monster, creature, type, message)
end
mType:register(monster)
|
#!/usr/bin/env tarantool
test = require("sqltester")
test:plan(15)
--!./tcltestrunner.lua
-- 2011 August 13
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, never taking more than you give.
--
-------------------------------------------------------------------------
--
-- This file implements tests for SQLite library. The focus of the tests
-- in this file is testing the capabilities of sqlite_stat3.
--
testprefix = "analyze8"
-- Scenario:
--
-- Two indices. One has mostly singleton entries, but for a few
-- values there are hundreds of entries. The other has 10-20
-- entries per value.
--
-- Verify that the query planner chooses the first index for the singleton
-- entries and the second index for the others.
--
test:do_test(
1.0,
function()
test:execsql([[
CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, a,b,c,d);
CREATE INDEX t1a ON t1(a);
CREATE INDEX t1b ON t1(b);
CREATE INDEX t1c ON t1(c);
]])
for i=0, 1000 do
if (i % 2 == 0)
then
a = i
else
a =(i % 8) * 100
end
b = math.floor(i / 10)
c = math.floor(i / 8)
c = ((c * c) * c)
test:execsql("INSERT INTO t1 (a,b,c,d) VALUES("..a..", "..b..", "..c..", "..i..")")
end
return test:execsql("ANALYZE")
end, {
-- <1.0>
-- </1.0>
})
-- The a==100 comparison is expensive because there are many rows
-- with a==100. And so for those cases, choose the t1b index.
-- But for a==99 and a==101, there are far fewer rows so choose
-- the t1a index.
test:do_eqp_test(
1.1,
[[SELECT * FROM t1 WHERE a=100 AND b=55]],
{
-- <1.1>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1B (B=?)"}
-- </1.1>
})
test:do_eqp_test(
1.2,
[[SELECT * FROM t1 WHERE a=99 AND b=55]],
{
-- <1.2>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1A (A=?)"}
-- </1.2>
})
test:do_eqp_test(
1.3,
[[SELECT * FROM t1 WHERE a=101 AND b=55]],
{
-- <1.3>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1A (A=?)"}
-- </1.3>
})
test:do_eqp_test(
1.4,
[[SELECT * FROM t1 WHERE a=100 AND b=56]],
{
-- <1.4>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1B (B=?)"}
-- </1.4>
})
test:do_eqp_test(
1.5,
[[SELECT * FROM t1 WHERE a=99 AND b=56]],
{
-- <1.5>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1A (A=?)"}
-- </1.5>
})
test:do_eqp_test(
1.6,
[[SELECT * FROM t1 WHERE a=101 AND b=56]],
{
-- <1.6>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1A (A=?)"}
-- </1.6>
})
test:do_eqp_test(
2.1,
[[SELECT * FROM t1 WHERE a=100 AND b BETWEEN 50 AND 54]],
{
-- <2.1>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1B (B>? AND B<?)"}
-- </2.1>
})
-- There are many more values of c between 0 and 100000 than there are
-- between 800000 and 900000. So t1c is more selective for the latter
-- range.
--
-- Test 3.2 is a little unstable. It depends on the planner estimating
-- that (b BETWEEN 30 AND 34) will match more rows than (c BETWEEN
-- 800000 AND 900000). Which is a pretty close call (50 vs. 32), so
-- the planner could get it wrong with an unlucky set of samples. This
-- case happens to work, but others ("b BETWEEN 40 AND 44" for example)
-- will fail.
--
test:do_execsql_test(
"3.0.0",
[[
SELECT count(*) FROM t1 WHERE b BETWEEN 30 AND 34
]], {
-- <3.0>
50
-- </3.0>
})
test:do_execsql_test(
"3.0.1",
[[
SELECT count(*) FROM t1 WHERE c BETWEEN 0 AND 100000;
]], {
-- <3.0>
376
-- </3.0>
})
test:do_execsql_test(
"3.0.2",
[[
SELECT count(*) FROM t1 WHERE c BETWEEN 800000 AND 900000;
]], {
-- <3.0>
32
-- </3.0>
})
test:do_eqp_test(
"3.1",
[[SELECT * FROM t1 WHERE b BETWEEN 30 AND 34 AND c BETWEEN 0 AND 100000]],
{
-- <3.1>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1B (B>? AND B<?)"}
-- </3.1>
})
test:do_eqp_test(
"3.2",
[[SELECT * FROM t1
WHERE b BETWEEN 30 AND 34 AND c BETWEEN 800000 AND 900000]],
{
-- <3.2>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1C (C>? AND C<?)"}
-- {0, 0, 0, "SEARCH TABLE t1 USING COVERING INDEX t1b (b>? AND b<?)"}
})
test:do_eqp_test(
3.3,
[[SELECT * FROM t1 WHERE a=100 AND c BETWEEN 0 AND 100000]],
{
-- <3.3>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1A (A=?)"}
-- </3.3>
})
test:do_eqp_test(
"3.4",
[[SELECT * FROM t1
WHERE a=100 AND c BETWEEN 800000 AND 900000]],
{
-- <3.4>
{0, 0, 0, "SEARCH TABLE T1 USING COVERING INDEX T1C (C>? AND C<?)"}
-- </3.4>
})
test:finish_test()
|
object_tangible_tcg_series7_combine_object_tie_canopy = object_tangible_tcg_series7_shared_combine_object_tie_canopy:new {
}
ObjectTemplates:addTemplate(object_tangible_tcg_series7_combine_object_tie_canopy, "object/tangible/tcg/series7/combine_object_tie_canopy.iff") |
-- first load all the CAMPVis Lua modules we need
require("cgt")
require("base")
require("cvio")
require("vis")
require("application")
-- All created CAMPVis objects have to be kept alive and must not be garbage-collected by Lua.
-- In order to keep them alive after this LuaDemo has finished, they have to reside in the global
-- Lua table. At the same time however, we do not want to spam that table. Thus, we create a
-- global table for this script, where everything resides in.
LuaDemo = {}
-- create DataContainer and Pipeline
LuaDemo.dc = application:createAndAddDataContainer("This DataContainer was created by Lua.")
LuaDemo.pipeline = campvis.AutoEvaluationPipeline(LuaDemo.dc, "A pipeline created by Lua")
local pipeline = LuaDemo.pipeline;
-- create the processors we need
local canvas_size = pipeline:getProperty("CanvasSize")
LuaDemo.lsp = base.LightSourceProvider()
LuaDemo.tcp = base.TrackballCameraProvider(canvas_size)
LuaDemo.image_reader = cvio.MhdImageReader()
LuaDemo.vr = vis.VolumeRenderer(canvas_size)
-- register the processors with the pipeline
pipeline:addProcessor(LuaDemo.lsp)
pipeline:addProcessor(LuaDemo.tcp)
pipeline:addProcessor(LuaDemo.image_reader)
pipeline:addProcessor(LuaDemo.vr)
-- setup event listener and register it with the pipeline
LuaDemo.tcp:addLqModeProcessor(LuaDemo.vr)
pipeline:addEventListenerToBack(LuaDemo.tcp)
-- create an init callback function, so that the following code gets called when the pipeline gets
-- initialized by CAMPVis.
-- Actually CAMPVis provides the Lua VM with an OpenGL context as well, so this code could also be
-- here directly. However, this way we nicely can demonstrate how to use CAMPVis signals from Lua.
local initCallback = function()
-- set up the processors' properties
LuaDemo.vr.p_outputImage:setValue("combine")
pipeline:getProperty("renderTargetID"):setValue("combine")
LuaDemo.image_reader.p_url:setValue(campvis.SOURCE_DIR .. "/modules/vis/sampledata/smallHeart.mhd")
LuaDemo.image_reader.p_targetImageID:setValue("reader.output")
LuaDemo.image_reader.p_targetImageID:addSharedProperty(LuaDemo.vr.p_inputVolume)
-- alternative 1 to automatically adjust the camera to the data
LuaDemo.image_reader.p_targetImageID:addSharedProperty(LuaDemo.tcp.p_image)
-- alternative 2 to automatically adjust the camera to the data
local callback = function(arg)
local data_container = pipeline:getDataContainer()
local img_data = data_container:getData(LuaDemo.image_reader.p_targetImageID:getValue()):getData()
LuaDemo.tcp:reinitializeCamera(img_data:getWorldBounds())
end
LuaDemo.image_reader.s_validated:connect(callback)
-- let us create a fancy transfer function
local dvrTF = campvis.Geometry1DTransferFunction(128, cgt.vec2(0, 0.05))
dvrTF:addGeometry(campvis.TFGeometry1D_createQuad(cgt.vec2(0.12, 0.15), cgt.col4(85, 0, 0, 128), cgt.col4(255, 0, 0, 128)))
dvrTF:addGeometry(campvis.TFGeometry1D_createQuad(cgt.vec2(.19, .28), cgt.col4(89, 89, 89, 155), cgt.col4(89, 89, 89, 155)))
dvrTF:addGeometry(campvis.TFGeometry1D_createQuad(cgt.vec2(.41, .51), cgt.col4(170, 170, 128, 64), cgt.col4(192, 192, 128, 64)))
LuaDemo.vr:getNestedProperty("RaycasterProps::TransferFunction"):replaceTF(dvrTF)
end
-- register the callback with the s_init signal
pipeline.s_init:connect(initCallback)
-- so, we now finished creating our LuaDemo. All that's missing is registering it with the CAMPVis application
application:addPipeline(pipeline)
|
-- Based on sha2.lua version 9 (2020-05-10) made by Egor Skriptunoff, ported for the WoW environment
-- https://github.com/Egor-Skriptunoff/pure_lua_SHA
local MAJOR_VERSION = "LibHash-1.0"
local MINOR_VERSION = 1
if not LibStub then error(MAJOR_VERSION .. " requires LibStub.")end
local lib = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION)
if not lib then return end
local unpack, table_concat, byte, char, string_rep, sub, gsub, gmatch, floor, ceil, math_min, math_max, tonumber, type = table.unpack or unpack, table.concat, string.byte, string.char, string.rep, string.sub, string.gsub, string.gmatch, math.floor, math.ceil, math.min, math.max, tonumber, type
--------------------------------------------------------------------------------
-- BASIC 32-BIT BITWISE FUNCTIONS
--------------------------------------------------------------------------------
local AND, OR, XOR, SHL, SHR, ROL, ROR, HEX, XOR_BYTE
function SHL(x, n)
return (x * 2 ^ n) % 2 ^ 32
end
function SHR(x, n)
-- return (x % 2^32 - x % 2^n) / 2^n
x = x % 2 ^ 32 / 2 ^ n
return x - x % 1
end
function ROL(x, n)
x = x % 2 ^ 32 * 2 ^ n
local r = x % 2 ^ 32
return r + (x - r) / 2 ^ 32
end
function ROR(x, n)
x = x % 2 ^ 32 / 2 ^ n
local r = x % 1
return r * 2 ^ 32 + (x - r)
end
local AND_of_two_bytes = {[0] = 0} -- look-up table (256*256 entries)
local idx = 0
for y = 0, 127 * 256, 256 do
for x = y, y + 127 do
x = AND_of_two_bytes[x] * 2
AND_of_two_bytes[idx] = x
AND_of_two_bytes[idx + 1] = x
AND_of_two_bytes[idx + 256] = x
AND_of_two_bytes[idx + 257] = x + 1
idx = idx + 2
end
idx = idx + 256
end
local function and_or_xor(x, y, operation)
-- operation: nil = AND, 1 = OR, 2 = XOR
local x0 = x % 2 ^ 32
local y0 = y % 2 ^ 32
local rx = x0 % 256
local ry = y0 % 256
local res = AND_of_two_bytes[rx + ry * 256]
x = x0 - rx
y = (y0 - ry) / 256
rx = x % 65536
ry = y % 256
res = res + AND_of_two_bytes[rx + ry] * 256
x = (x - rx) / 256
y = (y - ry) / 256
rx = x % 65536 + y % 256
res = res + AND_of_two_bytes[rx] * 65536
res = res + AND_of_two_bytes[(x + y - rx) / 256] * 16777216
if operation then
res = x0 + y0 - operation * res
end
return res
end
function AND(x, y)
return and_or_xor(x, y)
end
function OR(x, y)
return and_or_xor(x, y, 1)
end
function XOR(x, y, z, t, u) -- 2..5 arguments
if z then
if t then
if u then
t = and_or_xor(t, u, 2)
end
z = and_or_xor(z, t, 2)
end
y = and_or_xor(y, z, 2)
end
return and_or_xor(x, y, 2)
end
function XOR_BYTE(x, y)
return x + y - 2 * AND_of_two_bytes[x + y * 256]
end
local HexTable = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}
function HEX(x)
local res = {}
for i = 8, 1, -1 do
local y = x % 16
x = (x - y) / 16
res[i] = HexTable[y + 1]
end
return table.concat(res, "")
end
local function XOR32A5(x)
return XOR(x, 0xA5A5A5A5) % 4294967296
end
local function create_array_of_lanes()
return {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
end
--------------------------------------------------------------------------------
-- CREATING OPTIMIZED INNER LOOP
--------------------------------------------------------------------------------
-- Inner loop functions
local sha256_feed_64, sha512_feed_128, md5_feed_64, sha1_feed_64, keccak_feed
-- Arrays of SHA2 "magic numbers" (in "INT64" and "FFI" branches "*_lo" arrays contain 64-bit values)
local sha2_K_lo, sha2_K_hi, sha2_H_lo, sha2_H_hi, sha3_RC_lo, sha3_RC_hi = {}, {}, {}, {}, {}, {}
local sha2_H_ext256 = {[224] = {}, [256] = sha2_H_hi}
local sha2_H_ext512_lo, sha2_H_ext512_hi = {[384] = {}, [512] = sha2_H_lo}, {[384] = {}, [512] = sha2_H_hi}
local md5_K, md5_sha1_H = {}, {0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0}
local md5_next_shift = {0, 0, 0, 0, 0, 0, 0, 0, 28, 25, 26, 27, 0, 0, 10, 9, 11, 12, 0, 15, 16, 17, 18, 0, 20, 22, 23, 21}
local common_W = {} -- temporary table shared between all calculations (to avoid creating new temporary table every time)
local K_lo_modulo = 4294967296
-- implementation for Lua 5.1/5.2 (with or without bitwise library available)
function sha256_feed_64(H, str, offs, size)
-- offs >= 0, size >= 0, size is multiple of 64
local W, K = common_W, sha2_K_hi
local h1, h2, h3, h4, h5, h6, h7, h8 = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8]
for pos = offs, offs + size - 1, 64 do
for j = 1, 16 do
pos = pos + 4
local a, b, c, d = byte(str, pos - 3, pos)
W[j] = ((a * 256 + b) * 256 + c) * 256 + d
end
for j = 17, 64 do
local a, b = W[j - 15], W[j - 2]
W[j] =
XOR(ROR(a, 7), ROL(a, 14), SHR(a, 3)) + XOR(ROL(b, 15), ROL(b, 13), SHR(b, 10)) + W[j - 7] + W[j - 16]
end
local a, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8
for j = 1, 64 do
local z = XOR(ROR(e, 6), ROR(e, 11), ROL(e, 7)) + AND(e, f) + AND(-1 - e, g) + h + K[j] + W[j]
h = g
g = f
f = e
e = z + d
d = c
c = b
b = a
a = z + AND(d, c) + AND(a, XOR(d, c)) + XOR(ROR(a, 2), ROR(a, 13), ROL(a, 10))
end
h1, h2, h3, h4 = (a + h1) % 4294967296, (b + h2) % 4294967296, (c + h3) % 4294967296, (d + h4) % 4294967296
h5, h6, h7, h8 = (e + h5) % 4294967296, (f + h6) % 4294967296, (g + h7) % 4294967296, (h + h8) % 4294967296
end
H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8] = h1, h2, h3, h4, h5, h6, h7, h8
end
function sha512_feed_128(H_lo, H_hi, str, offs, size)
-- offs >= 0, size >= 0, size is multiple of 128
-- W1_hi, W1_lo, W2_hi, W2_lo, ... Wk_hi = W[2*k-1], Wk_lo = W[2*k]
local W, K_lo, K_hi = common_W, sha2_K_lo, sha2_K_hi
local h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo =
H_lo[1],
H_lo[2],
H_lo[3],
H_lo[4],
H_lo[5],
H_lo[6],
H_lo[7],
H_lo[8]
local h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi =
H_hi[1],
H_hi[2],
H_hi[3],
H_hi[4],
H_hi[5],
H_hi[6],
H_hi[7],
H_hi[8]
for pos = offs, offs + size - 1, 128 do
for j = 1, 16 * 2 do
pos = pos + 4
local a, b, c, d = byte(str, pos - 3, pos)
W[j] = ((a * 256 + b) * 256 + c) * 256 + d
end
for jj = 17 * 2, 80 * 2, 2 do
local a_lo, a_hi, b_lo, b_hi = W[jj - 30], W[jj - 31], W[jj - 4], W[jj - 5]
local tmp1 =
XOR(SHR(a_lo, 1) + SHL(a_hi, 31), SHR(a_lo, 8) + SHL(a_hi, 24), SHR(a_lo, 7) + SHL(a_hi, 25)) %
4294967296 +
XOR(SHR(b_lo, 19) + SHL(b_hi, 13), SHL(b_lo, 3) + SHR(b_hi, 29), SHR(b_lo, 6) + SHL(b_hi, 26)) %
4294967296 +
W[jj - 14] +
W[jj - 32]
local tmp2 = tmp1 % 4294967296
W[jj - 1] =
XOR(SHR(a_hi, 1) + SHL(a_lo, 31), SHR(a_hi, 8) + SHL(a_lo, 24), SHR(a_hi, 7)) +
XOR(SHR(b_hi, 19) + SHL(b_lo, 13), SHL(b_hi, 3) + SHR(b_lo, 29), SHR(b_hi, 6)) +
W[jj - 15] +
W[jj - 33] +
(tmp1 - tmp2) / 4294967296
W[jj] = tmp2
end
local a_lo, b_lo, c_lo, d_lo, e_lo, f_lo, g_lo, h_lo = h1_lo, h2_lo, h3_lo, h4_lo, h5_lo, h6_lo, h7_lo, h8_lo
local a_hi, b_hi, c_hi, d_hi, e_hi, f_hi, g_hi, h_hi = h1_hi, h2_hi, h3_hi, h4_hi, h5_hi, h6_hi, h7_hi, h8_hi
for j = 1, 80 do
local jj = 2 * j
local tmp1 =
XOR(SHR(e_lo, 14) + SHL(e_hi, 18), SHR(e_lo, 18) + SHL(e_hi, 14), SHL(e_lo, 23) + SHR(e_hi, 9)) %
4294967296 +
(AND(e_lo, f_lo) + AND(-1 - e_lo, g_lo)) % 4294967296 +
h_lo +
K_lo[j] +
W[jj]
local z_lo = tmp1 % 4294967296
local z_hi =
XOR(SHR(e_hi, 14) + SHL(e_lo, 18), SHR(e_hi, 18) + SHL(e_lo, 14), SHL(e_hi, 23) + SHR(e_lo, 9)) +
AND(e_hi, f_hi) +
AND(-1 - e_hi, g_hi) +
h_hi +
K_hi[j] +
W[jj - 1] +
(tmp1 - z_lo) / 4294967296
h_lo = g_lo
h_hi = g_hi
g_lo = f_lo
g_hi = f_hi
f_lo = e_lo
f_hi = e_hi
tmp1 = z_lo + d_lo
e_lo = tmp1 % 4294967296
e_hi = z_hi + d_hi + (tmp1 - e_lo) / 4294967296
d_lo = c_lo
d_hi = c_hi
c_lo = b_lo
c_hi = b_hi
b_lo = a_lo
b_hi = a_hi
tmp1 =
z_lo + (AND(d_lo, c_lo) + AND(b_lo, XOR(d_lo, c_lo))) % 4294967296 +
XOR(SHR(b_lo, 28) + SHL(b_hi, 4), SHL(b_lo, 30) + SHR(b_hi, 2), SHL(b_lo, 25) + SHR(b_hi, 7)) %
4294967296
a_lo = tmp1 % 4294967296
a_hi =
z_hi + (AND(d_hi, c_hi) + AND(b_hi, XOR(d_hi, c_hi))) +
XOR(SHR(b_hi, 28) + SHL(b_lo, 4), SHL(b_hi, 30) + SHR(b_lo, 2), SHL(b_hi, 25) + SHR(b_lo, 7)) +
(tmp1 - a_lo) / 4294967296
end
a_lo = h1_lo + a_lo
h1_lo = a_lo % 4294967296
h1_hi = (h1_hi + a_hi + (a_lo - h1_lo) / 4294967296) % 4294967296
a_lo = h2_lo + b_lo
h2_lo = a_lo % 4294967296
h2_hi = (h2_hi + b_hi + (a_lo - h2_lo) / 4294967296) % 4294967296
a_lo = h3_lo + c_lo
h3_lo = a_lo % 4294967296
h3_hi = (h3_hi + c_hi + (a_lo - h3_lo) / 4294967296) % 4294967296
a_lo = h4_lo + d_lo
h4_lo = a_lo % 4294967296
h4_hi = (h4_hi + d_hi + (a_lo - h4_lo) / 4294967296) % 4294967296
a_lo = h5_lo + e_lo
h5_lo = a_lo % 4294967296
h5_hi = (h5_hi + e_hi + (a_lo - h5_lo) / 4294967296) % 4294967296
a_lo = h6_lo + f_lo
h6_lo = a_lo % 4294967296
h6_hi = (h6_hi + f_hi + (a_lo - h6_lo) / 4294967296) % 4294967296
a_lo = h7_lo + g_lo
h7_lo = a_lo % 4294967296
h7_hi = (h7_hi + g_hi + (a_lo - h7_lo) / 4294967296) % 4294967296
a_lo = h8_lo + h_lo
h8_lo = a_lo % 4294967296
h8_hi = (h8_hi + h_hi + (a_lo - h8_lo) / 4294967296) % 4294967296
end
H_lo[1], H_lo[2], H_lo[3], H_lo[4], H_lo[5], H_lo[6], H_lo[7], H_lo[8] =
h1_lo,
h2_lo,
h3_lo,
h4_lo,
h5_lo,
h6_lo,
h7_lo,
h8_lo
H_hi[1], H_hi[2], H_hi[3], H_hi[4], H_hi[5], H_hi[6], H_hi[7], H_hi[8] =
h1_hi,
h2_hi,
h3_hi,
h4_hi,
h5_hi,
h6_hi,
h7_hi,
h8_hi
end
function md5_feed_64(H, str, offs, size)
-- offs >= 0, size >= 0, size is multiple of 64
local W, K, md5_next_shift = common_W, md5_K, md5_next_shift
local h1, h2, h3, h4 = H[1], H[2], H[3], H[4]
for pos = offs, offs + size - 1, 64 do
for j = 1, 16 do
pos = pos + 4
local a, b, c, d = byte(str, pos - 3, pos)
W[j] = ((d * 256 + c) * 256 + b) * 256 + a
end
local a, b, c, d = h1, h2, h3, h4
local s = 32 - 7
for j = 1, 16 do
local F = ROR(AND(b, c) + AND(-1 - b, d) + a + K[j] + W[j], s) + b
s = md5_next_shift[s]
a = d
d = c
c = b
b = F
end
s = 32 - 5
for j = 17, 32 do
local F = ROR(AND(d, b) + AND(-1 - d, c) + a + K[j] + W[(5 * j - 4) % 16 + 1], s) + b
s = md5_next_shift[s]
a = d
d = c
c = b
b = F
end
s = 32 - 4
for j = 33, 48 do
local F = ROR(XOR(XOR(b, c), d) + a + K[j] + W[(3 * j + 2) % 16 + 1], s) + b
s = md5_next_shift[s]
a = d
d = c
c = b
b = F
end
s = 32 - 6
for j = 49, 64 do
local F = ROR(XOR(c, OR(b, -1 - d)) + a + K[j] + W[(j * 7 - 7) % 16 + 1], s) + b
s = md5_next_shift[s]
a = d
d = c
c = b
b = F
end
h1 = (a + h1) % 4294967296
h2 = (b + h2) % 4294967296
h3 = (c + h3) % 4294967296
h4 = (d + h4) % 4294967296
end
H[1], H[2], H[3], H[4] = h1, h2, h3, h4
end
function sha1_feed_64(H, str, offs, size)
-- offs >= 0, size >= 0, size is multiple of 64
local W = common_W
local h1, h2, h3, h4, h5 = H[1], H[2], H[3], H[4], H[5]
for pos = offs, offs + size - 1, 64 do
for j = 1, 16 do
pos = pos + 4
local a, b, c, d = byte(str, pos - 3, pos)
W[j] = ((a * 256 + b) * 256 + c) * 256 + d
end
for j = 17, 80 do
W[j] = ROL(XOR(W[j - 3], W[j - 8], W[j - 14], W[j - 16]), 1)
end
local a, b, c, d, e = h1, h2, h3, h4, h5
for j = 1, 20 do
local z = ROL(a, 5) + AND(b, c) + AND(-1 - b, d) + 0x5A827999 + W[j] + e -- constant = floor(2^30 * sqrt(2))
e = d
d = c
c = ROR(b, 2)
b = a
a = z
end
for j = 21, 40 do
local z = ROL(a, 5) + XOR(b, c, d) + 0x6ED9EBA1 + W[j] + e -- 2^30 * sqrt(3)
e = d
d = c
c = ROR(b, 2)
b = a
a = z
end
for j = 41, 60 do
local z = ROL(a, 5) + AND(d, c) + AND(b, XOR(d, c)) + 0x8F1BBCDC + W[j] + e -- 2^30 * sqrt(5)
e = d
d = c
c = ROR(b, 2)
b = a
a = z
end
for j = 61, 80 do
local z = ROL(a, 5) + XOR(b, c, d) + 0xCA62C1D6 + W[j] + e -- 2^30 * sqrt(10)
e = d
d = c
c = ROR(b, 2)
b = a
a = z
end
h1 = (a + h1) % 4294967296
h2 = (b + h2) % 4294967296
h3 = (c + h3) % 4294967296
h4 = (d + h4) % 4294967296
h5 = (e + h5) % 4294967296
end
H[1], H[2], H[3], H[4], H[5] = h1, h2, h3, h4, h5
end
function keccak_feed(lanes_lo, lanes_hi, str, offs, size, block_size_in_bytes)
-- This is an example of a Lua function having 79 local variables :-)
-- offs >= 0, size >= 0, size is multiple of block_size_in_bytes, block_size_in_bytes is positive multiple of 8
local RC_lo, RC_hi = sha3_RC_lo, sha3_RC_hi
local qwords_qty = block_size_in_bytes / 8
for pos = offs, offs + size - 1, block_size_in_bytes do
for j = 1, qwords_qty do
local a, b, c, d = byte(str, pos + 1, pos + 4)
lanes_lo[j] = XOR(lanes_lo[j], ((d * 256 + c) * 256 + b) * 256 + a)
pos = pos + 8
a, b, c, d = byte(str, pos - 3, pos)
lanes_hi[j] = XOR(lanes_hi[j], ((d * 256 + c) * 256 + b) * 256 + a)
end
local L01_lo,
L01_hi,
L02_lo,
L02_hi,
L03_lo,
L03_hi,
L04_lo,
L04_hi,
L05_lo,
L05_hi,
L06_lo,
L06_hi,
L07_lo,
L07_hi,
L08_lo,
L08_hi,
L09_lo,
L09_hi,
L10_lo,
L10_hi,
L11_lo,
L11_hi,
L12_lo,
L12_hi,
L13_lo,
L13_hi,
L14_lo,
L14_hi,
L15_lo,
L15_hi,
L16_lo,
L16_hi,
L17_lo,
L17_hi,
L18_lo,
L18_hi,
L19_lo,
L19_hi,
L20_lo,
L20_hi,
L21_lo,
L21_hi,
L22_lo,
L22_hi,
L23_lo,
L23_hi,
L24_lo,
L24_hi,
L25_lo,
L25_hi =
lanes_lo[1],
lanes_hi[1],
lanes_lo[2],
lanes_hi[2],
lanes_lo[3],
lanes_hi[3],
lanes_lo[4],
lanes_hi[4],
lanes_lo[5],
lanes_hi[5],
lanes_lo[6],
lanes_hi[6],
lanes_lo[7],
lanes_hi[7],
lanes_lo[8],
lanes_hi[8],
lanes_lo[9],
lanes_hi[9],
lanes_lo[10],
lanes_hi[10],
lanes_lo[11],
lanes_hi[11],
lanes_lo[12],
lanes_hi[12],
lanes_lo[13],
lanes_hi[13],
lanes_lo[14],
lanes_hi[14],
lanes_lo[15],
lanes_hi[15],
lanes_lo[16],
lanes_hi[16],
lanes_lo[17],
lanes_hi[17],
lanes_lo[18],
lanes_hi[18],
lanes_lo[19],
lanes_hi[19],
lanes_lo[20],
lanes_hi[20],
lanes_lo[21],
lanes_hi[21],
lanes_lo[22],
lanes_hi[22],
lanes_lo[23],
lanes_hi[23],
lanes_lo[24],
lanes_hi[24],
lanes_lo[25],
lanes_hi[25]
for round_idx = 1, 24 do
local C1_lo = XOR(L01_lo, L06_lo, L11_lo, L16_lo, L21_lo)
local C1_hi = XOR(L01_hi, L06_hi, L11_hi, L16_hi, L21_hi)
local C2_lo = XOR(L02_lo, L07_lo, L12_lo, L17_lo, L22_lo)
local C2_hi = XOR(L02_hi, L07_hi, L12_hi, L17_hi, L22_hi)
local C3_lo = XOR(L03_lo, L08_lo, L13_lo, L18_lo, L23_lo)
local C3_hi = XOR(L03_hi, L08_hi, L13_hi, L18_hi, L23_hi)
local C4_lo = XOR(L04_lo, L09_lo, L14_lo, L19_lo, L24_lo)
local C4_hi = XOR(L04_hi, L09_hi, L14_hi, L19_hi, L24_hi)
local C5_lo = XOR(L05_lo, L10_lo, L15_lo, L20_lo, L25_lo)
local C5_hi = XOR(L05_hi, L10_hi, L15_hi, L20_hi, L25_hi)
local D_lo = XOR(C1_lo, C3_lo * 2 + (C3_hi % 2 ^ 32 - C3_hi % 2 ^ 31) / 2 ^ 31)
local D_hi = XOR(C1_hi, C3_hi * 2 + (C3_lo % 2 ^ 32 - C3_lo % 2 ^ 31) / 2 ^ 31)
local T0_lo = XOR(D_lo, L02_lo)
local T0_hi = XOR(D_hi, L02_hi)
local T1_lo = XOR(D_lo, L07_lo)
local T1_hi = XOR(D_hi, L07_hi)
local T2_lo = XOR(D_lo, L12_lo)
local T2_hi = XOR(D_hi, L12_hi)
local T3_lo = XOR(D_lo, L17_lo)
local T3_hi = XOR(D_hi, L17_hi)
local T4_lo = XOR(D_lo, L22_lo)
local T4_hi = XOR(D_hi, L22_hi)
L02_lo = (T1_lo % 2 ^ 32 - T1_lo % 2 ^ 20) / 2 ^ 20 + T1_hi * 2 ^ 12
L02_hi = (T1_hi % 2 ^ 32 - T1_hi % 2 ^ 20) / 2 ^ 20 + T1_lo * 2 ^ 12
L07_lo = (T3_lo % 2 ^ 32 - T3_lo % 2 ^ 19) / 2 ^ 19 + T3_hi * 2 ^ 13
L07_hi = (T3_hi % 2 ^ 32 - T3_hi % 2 ^ 19) / 2 ^ 19 + T3_lo * 2 ^ 13
L12_lo = T0_lo * 2 + (T0_hi % 2 ^ 32 - T0_hi % 2 ^ 31) / 2 ^ 31
L12_hi = T0_hi * 2 + (T0_lo % 2 ^ 32 - T0_lo % 2 ^ 31) / 2 ^ 31
L17_lo = T2_lo * 2 ^ 10 + (T2_hi % 2 ^ 32 - T2_hi % 2 ^ 22) / 2 ^ 22
L17_hi = T2_hi * 2 ^ 10 + (T2_lo % 2 ^ 32 - T2_lo % 2 ^ 22) / 2 ^ 22
L22_lo = T4_lo * 2 ^ 2 + (T4_hi % 2 ^ 32 - T4_hi % 2 ^ 30) / 2 ^ 30
L22_hi = T4_hi * 2 ^ 2 + (T4_lo % 2 ^ 32 - T4_lo % 2 ^ 30) / 2 ^ 30
D_lo = XOR(C2_lo, C4_lo * 2 + (C4_hi % 2 ^ 32 - C4_hi % 2 ^ 31) / 2 ^ 31)
D_hi = XOR(C2_hi, C4_hi * 2 + (C4_lo % 2 ^ 32 - C4_lo % 2 ^ 31) / 2 ^ 31)
T0_lo = XOR(D_lo, L03_lo)
T0_hi = XOR(D_hi, L03_hi)
T1_lo = XOR(D_lo, L08_lo)
T1_hi = XOR(D_hi, L08_hi)
T2_lo = XOR(D_lo, L13_lo)
T2_hi = XOR(D_hi, L13_hi)
T3_lo = XOR(D_lo, L18_lo)
T3_hi = XOR(D_hi, L18_hi)
T4_lo = XOR(D_lo, L23_lo)
T4_hi = XOR(D_hi, L23_hi)
L03_lo = (T2_lo % 2 ^ 32 - T2_lo % 2 ^ 21) / 2 ^ 21 + T2_hi * 2 ^ 11
L03_hi = (T2_hi % 2 ^ 32 - T2_hi % 2 ^ 21) / 2 ^ 21 + T2_lo * 2 ^ 11
L08_lo = (T4_lo % 2 ^ 32 - T4_lo % 2 ^ 3) / 2 ^ 3 + T4_hi * 2 ^ 29 % 2 ^ 32
L08_hi = (T4_hi % 2 ^ 32 - T4_hi % 2 ^ 3) / 2 ^ 3 + T4_lo * 2 ^ 29 % 2 ^ 32
L13_lo = T1_lo * 2 ^ 6 + (T1_hi % 2 ^ 32 - T1_hi % 2 ^ 26) / 2 ^ 26
L13_hi = T1_hi * 2 ^ 6 + (T1_lo % 2 ^ 32 - T1_lo % 2 ^ 26) / 2 ^ 26
L18_lo = T3_lo * 2 ^ 15 + (T3_hi % 2 ^ 32 - T3_hi % 2 ^ 17) / 2 ^ 17
L18_hi = T3_hi * 2 ^ 15 + (T3_lo % 2 ^ 32 - T3_lo % 2 ^ 17) / 2 ^ 17
L23_lo = (T0_lo % 2 ^ 32 - T0_lo % 2 ^ 2) / 2 ^ 2 + T0_hi * 2 ^ 30 % 2 ^ 32
L23_hi = (T0_hi % 2 ^ 32 - T0_hi % 2 ^ 2) / 2 ^ 2 + T0_lo * 2 ^ 30 % 2 ^ 32
D_lo = XOR(C3_lo, C5_lo * 2 + (C5_hi % 2 ^ 32 - C5_hi % 2 ^ 31) / 2 ^ 31)
D_hi = XOR(C3_hi, C5_hi * 2 + (C5_lo % 2 ^ 32 - C5_lo % 2 ^ 31) / 2 ^ 31)
T0_lo = XOR(D_lo, L04_lo)
T0_hi = XOR(D_hi, L04_hi)
T1_lo = XOR(D_lo, L09_lo)
T1_hi = XOR(D_hi, L09_hi)
T2_lo = XOR(D_lo, L14_lo)
T2_hi = XOR(D_hi, L14_hi)
T3_lo = XOR(D_lo, L19_lo)
T3_hi = XOR(D_hi, L19_hi)
T4_lo = XOR(D_lo, L24_lo)
T4_hi = XOR(D_hi, L24_hi)
L04_lo = T3_lo * 2 ^ 21 % 2 ^ 32 + (T3_hi % 2 ^ 32 - T3_hi % 2 ^ 11) / 2 ^ 11
L04_hi = T3_hi * 2 ^ 21 % 2 ^ 32 + (T3_lo % 2 ^ 32 - T3_lo % 2 ^ 11) / 2 ^ 11
L09_lo = T0_lo * 2 ^ 28 % 2 ^ 32 + (T0_hi % 2 ^ 32 - T0_hi % 2 ^ 4) / 2 ^ 4
L09_hi = T0_hi * 2 ^ 28 % 2 ^ 32 + (T0_lo % 2 ^ 32 - T0_lo % 2 ^ 4) / 2 ^ 4
L14_lo = T2_lo * 2 ^ 25 % 2 ^ 32 + (T2_hi % 2 ^ 32 - T2_hi % 2 ^ 7) / 2 ^ 7
L14_hi = T2_hi * 2 ^ 25 % 2 ^ 32 + (T2_lo % 2 ^ 32 - T2_lo % 2 ^ 7) / 2 ^ 7
L19_lo = (T4_lo % 2 ^ 32 - T4_lo % 2 ^ 8) / 2 ^ 8 + T4_hi * 2 ^ 24 % 2 ^ 32
L19_hi = (T4_hi % 2 ^ 32 - T4_hi % 2 ^ 8) / 2 ^ 8 + T4_lo * 2 ^ 24 % 2 ^ 32
L24_lo = (T1_lo % 2 ^ 32 - T1_lo % 2 ^ 9) / 2 ^ 9 + T1_hi * 2 ^ 23 % 2 ^ 32
L24_hi = (T1_hi % 2 ^ 32 - T1_hi % 2 ^ 9) / 2 ^ 9 + T1_lo * 2 ^ 23 % 2 ^ 32
D_lo = XOR(C4_lo, C1_lo * 2 + (C1_hi % 2 ^ 32 - C1_hi % 2 ^ 31) / 2 ^ 31)
D_hi = XOR(C4_hi, C1_hi * 2 + (C1_lo % 2 ^ 32 - C1_lo % 2 ^ 31) / 2 ^ 31)
T0_lo = XOR(D_lo, L05_lo)
T0_hi = XOR(D_hi, L05_hi)
T1_lo = XOR(D_lo, L10_lo)
T1_hi = XOR(D_hi, L10_hi)
T2_lo = XOR(D_lo, L15_lo)
T2_hi = XOR(D_hi, L15_hi)
T3_lo = XOR(D_lo, L20_lo)
T3_hi = XOR(D_hi, L20_hi)
T4_lo = XOR(D_lo, L25_lo)
T4_hi = XOR(D_hi, L25_hi)
L05_lo = T4_lo * 2 ^ 14 + (T4_hi % 2 ^ 32 - T4_hi % 2 ^ 18) / 2 ^ 18
L05_hi = T4_hi * 2 ^ 14 + (T4_lo % 2 ^ 32 - T4_lo % 2 ^ 18) / 2 ^ 18
L10_lo = T1_lo * 2 ^ 20 % 2 ^ 32 + (T1_hi % 2 ^ 32 - T1_hi % 2 ^ 12) / 2 ^ 12
L10_hi = T1_hi * 2 ^ 20 % 2 ^ 32 + (T1_lo % 2 ^ 32 - T1_lo % 2 ^ 12) / 2 ^ 12
L15_lo = T3_lo * 2 ^ 8 + (T3_hi % 2 ^ 32 - T3_hi % 2 ^ 24) / 2 ^ 24
L15_hi = T3_hi * 2 ^ 8 + (T3_lo % 2 ^ 32 - T3_lo % 2 ^ 24) / 2 ^ 24
L20_lo = T0_lo * 2 ^ 27 % 2 ^ 32 + (T0_hi % 2 ^ 32 - T0_hi % 2 ^ 5) / 2 ^ 5
L20_hi = T0_hi * 2 ^ 27 % 2 ^ 32 + (T0_lo % 2 ^ 32 - T0_lo % 2 ^ 5) / 2 ^ 5
L25_lo = (T2_lo % 2 ^ 32 - T2_lo % 2 ^ 25) / 2 ^ 25 + T2_hi * 2 ^ 7
L25_hi = (T2_hi % 2 ^ 32 - T2_hi % 2 ^ 25) / 2 ^ 25 + T2_lo * 2 ^ 7
D_lo = XOR(C5_lo, C2_lo * 2 + (C2_hi % 2 ^ 32 - C2_hi % 2 ^ 31) / 2 ^ 31)
D_hi = XOR(C5_hi, C2_hi * 2 + (C2_lo % 2 ^ 32 - C2_lo % 2 ^ 31) / 2 ^ 31)
T1_lo = XOR(D_lo, L06_lo)
T1_hi = XOR(D_hi, L06_hi)
T2_lo = XOR(D_lo, L11_lo)
T2_hi = XOR(D_hi, L11_hi)
T3_lo = XOR(D_lo, L16_lo)
T3_hi = XOR(D_hi, L16_hi)
T4_lo = XOR(D_lo, L21_lo)
T4_hi = XOR(D_hi, L21_hi)
L06_lo = T2_lo * 2 ^ 3 + (T2_hi % 2 ^ 32 - T2_hi % 2 ^ 29) / 2 ^ 29
L06_hi = T2_hi * 2 ^ 3 + (T2_lo % 2 ^ 32 - T2_lo % 2 ^ 29) / 2 ^ 29
L11_lo = T4_lo * 2 ^ 18 + (T4_hi % 2 ^ 32 - T4_hi % 2 ^ 14) / 2 ^ 14
L11_hi = T4_hi * 2 ^ 18 + (T4_lo % 2 ^ 32 - T4_lo % 2 ^ 14) / 2 ^ 14
L16_lo = (T1_lo % 2 ^ 32 - T1_lo % 2 ^ 28) / 2 ^ 28 + T1_hi * 2 ^ 4
L16_hi = (T1_hi % 2 ^ 32 - T1_hi % 2 ^ 28) / 2 ^ 28 + T1_lo * 2 ^ 4
L21_lo = (T3_lo % 2 ^ 32 - T3_lo % 2 ^ 23) / 2 ^ 23 + T3_hi * 2 ^ 9
L21_hi = (T3_hi % 2 ^ 32 - T3_hi % 2 ^ 23) / 2 ^ 23 + T3_lo * 2 ^ 9
L01_lo = XOR(D_lo, L01_lo)
L01_hi = XOR(D_hi, L01_hi)
L01_lo, L02_lo, L03_lo, L04_lo, L05_lo =
XOR(L01_lo, AND(-1 - L02_lo, L03_lo)),
XOR(L02_lo, AND(-1 - L03_lo, L04_lo)),
XOR(L03_lo, AND(-1 - L04_lo, L05_lo)),
XOR(L04_lo, AND(-1 - L05_lo, L01_lo)),
XOR(L05_lo, AND(-1 - L01_lo, L02_lo))
L01_hi, L02_hi, L03_hi, L04_hi, L05_hi =
XOR(L01_hi, AND(-1 - L02_hi, L03_hi)),
XOR(L02_hi, AND(-1 - L03_hi, L04_hi)),
XOR(L03_hi, AND(-1 - L04_hi, L05_hi)),
XOR(L04_hi, AND(-1 - L05_hi, L01_hi)),
XOR(L05_hi, AND(-1 - L01_hi, L02_hi))
L06_lo, L07_lo, L08_lo, L09_lo, L10_lo =
XOR(L09_lo, AND(-1 - L10_lo, L06_lo)),
XOR(L10_lo, AND(-1 - L06_lo, L07_lo)),
XOR(L06_lo, AND(-1 - L07_lo, L08_lo)),
XOR(L07_lo, AND(-1 - L08_lo, L09_lo)),
XOR(L08_lo, AND(-1 - L09_lo, L10_lo))
L06_hi, L07_hi, L08_hi, L09_hi, L10_hi =
XOR(L09_hi, AND(-1 - L10_hi, L06_hi)),
XOR(L10_hi, AND(-1 - L06_hi, L07_hi)),
XOR(L06_hi, AND(-1 - L07_hi, L08_hi)),
XOR(L07_hi, AND(-1 - L08_hi, L09_hi)),
XOR(L08_hi, AND(-1 - L09_hi, L10_hi))
L11_lo, L12_lo, L13_lo, L14_lo, L15_lo =
XOR(L12_lo, AND(-1 - L13_lo, L14_lo)),
XOR(L13_lo, AND(-1 - L14_lo, L15_lo)),
XOR(L14_lo, AND(-1 - L15_lo, L11_lo)),
XOR(L15_lo, AND(-1 - L11_lo, L12_lo)),
XOR(L11_lo, AND(-1 - L12_lo, L13_lo))
L11_hi, L12_hi, L13_hi, L14_hi, L15_hi =
XOR(L12_hi, AND(-1 - L13_hi, L14_hi)),
XOR(L13_hi, AND(-1 - L14_hi, L15_hi)),
XOR(L14_hi, AND(-1 - L15_hi, L11_hi)),
XOR(L15_hi, AND(-1 - L11_hi, L12_hi)),
XOR(L11_hi, AND(-1 - L12_hi, L13_hi))
L16_lo, L17_lo, L18_lo, L19_lo, L20_lo =
XOR(L20_lo, AND(-1 - L16_lo, L17_lo)),
XOR(L16_lo, AND(-1 - L17_lo, L18_lo)),
XOR(L17_lo, AND(-1 - L18_lo, L19_lo)),
XOR(L18_lo, AND(-1 - L19_lo, L20_lo)),
XOR(L19_lo, AND(-1 - L20_lo, L16_lo))
L16_hi, L17_hi, L18_hi, L19_hi, L20_hi =
XOR(L20_hi, AND(-1 - L16_hi, L17_hi)),
XOR(L16_hi, AND(-1 - L17_hi, L18_hi)),
XOR(L17_hi, AND(-1 - L18_hi, L19_hi)),
XOR(L18_hi, AND(-1 - L19_hi, L20_hi)),
XOR(L19_hi, AND(-1 - L20_hi, L16_hi))
L21_lo, L22_lo, L23_lo, L24_lo, L25_lo =
XOR(L23_lo, AND(-1 - L24_lo, L25_lo)),
XOR(L24_lo, AND(-1 - L25_lo, L21_lo)),
XOR(L25_lo, AND(-1 - L21_lo, L22_lo)),
XOR(L21_lo, AND(-1 - L22_lo, L23_lo)),
XOR(L22_lo, AND(-1 - L23_lo, L24_lo))
L21_hi, L22_hi, L23_hi, L24_hi, L25_hi =
XOR(L23_hi, AND(-1 - L24_hi, L25_hi)),
XOR(L24_hi, AND(-1 - L25_hi, L21_hi)),
XOR(L25_hi, AND(-1 - L21_hi, L22_hi)),
XOR(L21_hi, AND(-1 - L22_hi, L23_hi)),
XOR(L22_hi, AND(-1 - L23_hi, L24_hi))
L01_lo = XOR(L01_lo, RC_lo[round_idx])
L01_hi = L01_hi + RC_hi[round_idx] -- RC_hi[] is either 0 or 0x80000000, so we could use fast addition instead of slow XOR
end
lanes_lo[1] = L01_lo
lanes_hi[1] = L01_hi
lanes_lo[2] = L02_lo
lanes_hi[2] = L02_hi
lanes_lo[3] = L03_lo
lanes_hi[3] = L03_hi
lanes_lo[4] = L04_lo
lanes_hi[4] = L04_hi
lanes_lo[5] = L05_lo
lanes_hi[5] = L05_hi
lanes_lo[6] = L06_lo
lanes_hi[6] = L06_hi
lanes_lo[7] = L07_lo
lanes_hi[7] = L07_hi
lanes_lo[8] = L08_lo
lanes_hi[8] = L08_hi
lanes_lo[9] = L09_lo
lanes_hi[9] = L09_hi
lanes_lo[10] = L10_lo
lanes_hi[10] = L10_hi
lanes_lo[11] = L11_lo
lanes_hi[11] = L11_hi
lanes_lo[12] = L12_lo
lanes_hi[12] = L12_hi
lanes_lo[13] = L13_lo
lanes_hi[13] = L13_hi
lanes_lo[14] = L14_lo
lanes_hi[14] = L14_hi
lanes_lo[15] = L15_lo
lanes_hi[15] = L15_hi
lanes_lo[16] = L16_lo
lanes_hi[16] = L16_hi
lanes_lo[17] = L17_lo
lanes_hi[17] = L17_hi
lanes_lo[18] = L18_lo
lanes_hi[18] = L18_hi
lanes_lo[19] = L19_lo
lanes_hi[19] = L19_hi
lanes_lo[20] = L20_lo
lanes_hi[20] = L20_hi
lanes_lo[21] = L21_lo
lanes_hi[21] = L21_hi
lanes_lo[22] = L22_lo
lanes_hi[22] = L22_hi
lanes_lo[23] = L23_lo
lanes_hi[23] = L23_hi
lanes_lo[24] = L24_lo
lanes_hi[24] = L24_hi
lanes_lo[25] = L25_lo
lanes_hi[25] = L25_hi
end
end
--------------------------------------------------------------------------------
-- MAGIC NUMBERS CALCULATOR
--------------------------------------------------------------------------------
-- Q:
-- Is 53-bit "double" math enough to calculate square roots and cube roots of primes with 64 correct bits after decimal point?
-- A:
-- Yes, 53-bit "double" arithmetic is enough.
-- We could obtain first 40 bits by direct calculation of p^(1/3) and next 40 bits by one step of Newton's method.
do
local function mul(src1, src2, factor, result_length)
-- src1, src2 - long integers (arrays of digits in base 2^24)
-- factor - small integer
-- returns long integer result (src1 * src2 * factor) and its floating point approximation
local result, carry, value, weight = {}, 0.0, 0.0, 1.0
for j = 1, result_length do
for k = math_max(1, j + 1 - #src2), math_min(j, #src1) do
carry = carry + factor * src1[k] * src2[j + 1 - k] -- "int32" is not enough for multiplication result, that's why "factor" must be of type "double"
end
local digit = carry % 2 ^ 24
result[j] = floor(digit)
carry = (carry - digit) / 2 ^ 24
value = value + digit * weight
weight = weight * 2 ^ 24
end
return result, value
end
local idx, step, p, one, sqrt_hi, sqrt_lo = 0, {4, 1, 2, -2, 2}, 4, {1}, sha2_H_hi, sha2_H_lo
repeat
p = p + step[p % 6]
local d = 1
repeat
d = d + step[d % 6]
if d * d > p then -- next prime number is found
local root = p ^ (1 / 3)
local R = root * 2 ^ 40
R = mul({R - R % 1}, one, 1.0, 2)
local _, delta = mul(R, mul(R, R, 1.0, 4), -1.0, 4)
local hi = R[2] % 65536 * 65536 + floor(R[1] / 256)
local lo = R[1] % 256 * 16777216 + floor(delta * (2 ^ -56 / 3) * root / p)
if idx < 16 then
root = p ^ (1 / 2)
R = root * 2 ^ 40
R = mul({R - R % 1}, one, 1.0, 2)
_, delta = mul(R, R, -1.0, 2)
local hi = R[2] % 65536 * 65536 + floor(R[1] / 256)
local lo = R[1] % 256 * 16777216 + floor(delta * 2 ^ -17 / root)
local idx = idx % 8 + 1
sha2_H_ext256[224][idx] = lo
sqrt_hi[idx], sqrt_lo[idx] = hi, lo
if idx > 7 then
sqrt_hi, sqrt_lo = sha2_H_ext512_hi[384], sha2_H_ext512_lo[384]
end
end
idx = idx + 1
sha2_K_hi[idx], sha2_K_lo[idx] = hi, lo % K_lo_modulo
break
end
until p % d == 0
until idx > 79
end
-- Calculating IVs for SHA512/224 and SHA512/256
for width = 224, 256, 32 do
local H_lo, H_hi = {}
H_hi = {}
for j = 1, 8 do
H_lo[j] = XOR32A5(sha2_H_lo[j])
H_hi[j] = XOR32A5(sha2_H_hi[j])
end
sha512_feed_128(H_lo, H_hi, "SHA-512/" .. tostring(width) .. "\128" .. string_rep("\0", 115) .. "\88", 0, 128)
sha2_H_ext512_lo[width] = H_lo
sha2_H_ext512_hi[width] = H_hi
end
-- Constants for MD5
do
local sin, abs, modf = math.sin, math.abs, math.modf
for idx = 1, 64 do
-- we can't use formula floor(abs(sin(idx))*2^32) because its result may be beyond integer range on Lua built with 32-bit integers
local hi, lo = modf(abs(sin(idx)) * 2 ^ 16)
md5_K[idx] = hi * 65536 + floor(lo * 2 ^ 16)
end
end
-- Constants for SHA3
do
local sh_reg = 29
local function next_bit()
local r = sh_reg % 2
sh_reg = XOR_BYTE((sh_reg - r) / 2, 142 * r)
return r
end
for idx = 1, 24 do
local lo, m = 0
for _ = 1, 6 do
m = m and m * m * 2 or 1
lo = lo + next_bit() * m
end
local hi = next_bit() * m
sha3_RC_hi[idx], sha3_RC_lo[idx] = hi, lo
end
end
--------------------------------------------------------------------------------
-- MAIN FUNCTIONS
--------------------------------------------------------------------------------
local function sha256ext(width, message)
-- Create an instance (private objects for current calculation)
local H, length, tail = {unpack(sha2_H_ext256[width])}, 0.0, ""
local function partial(message_part)
if message_part then
if tail then
length = length + #message_part
local offs = 0
if tail ~= "" and #tail + #message_part >= 64 then
offs = 64 - #tail
sha256_feed_64(H, tail .. sub(message_part, 1, offs), 0, 64)
tail = ""
end
local size = #message_part - offs
local size_tail = size % 64
sha256_feed_64(H, message_part, offs, size - size_tail)
tail = tail .. sub(message_part, #message_part + 1 - size_tail)
return partial
else
error("Adding more chunks is not allowed after receiving the result", 2)
end
else
if tail then
local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64 + 1)}
tail = nil
-- Assuming user data length is shorter than (2^53)-9 bytes
-- Anyway, it looks very unrealistic that someone would spend more than a year of calculations to process 2^53 bytes of data by using this Lua script :-)
-- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes
length = length * (8 / 256 ^ 7) -- convert "byte-counter" to "bit-counter" and move decimal point to the left
for j = 4, 10 do
length = length % 1 * 256
final_blocks[j] = char(floor(length))
end
final_blocks = table_concat(final_blocks)
sha256_feed_64(H, final_blocks, 0, #final_blocks)
local max_reg = width / 32
for j = 1, max_reg do
H[j] = HEX(H[j])
end
H = table_concat(H, "", 1, max_reg)
end
return H
end
end
if message then
-- Actually perform calculations and return the SHA256 digest of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading
-- User should feed every chunk of input data as single argument to this function and finally get SHA256 digest by invoking this function without an argument
return partial
end
end
local function sha512ext(width, message)
-- Create an instance (private objects for current calculation)
local length, tail, H_lo, H_hi = 0.0, "", {unpack(sha2_H_ext512_lo[width])}, {unpack(sha2_H_ext512_hi[width])}
local function partial(message_part)
if message_part then
if tail then
length = length + #message_part
local offs = 0
if tail ~= "" and #tail + #message_part >= 128 then
offs = 128 - #tail
sha512_feed_128(H_lo, H_hi, tail .. sub(message_part, 1, offs), 0, 128)
tail = ""
end
local size = #message_part - offs
local size_tail = size % 128
sha512_feed_128(H_lo, H_hi, message_part, offs, size - size_tail)
tail = tail .. sub(message_part, #message_part + 1 - size_tail)
return partial
else
error("Adding more chunks is not allowed after receiving the result", 2)
end
else
if tail then
local final_blocks = {tail, "\128", string_rep("\0", (-17 - length) % 128 + 9)}
tail = nil
-- Assuming user data length is shorter than (2^53)-17 bytes
-- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes
length = length * (8 / 256 ^ 7) -- convert "byte-counter" to "bit-counter" and move floating point to the left
for j = 4, 10 do
length = length % 1 * 256
final_blocks[j] = char(floor(length))
end
final_blocks = table_concat(final_blocks)
sha512_feed_128(H_lo, H_hi, final_blocks, 0, #final_blocks)
local max_reg = ceil(width / 64)
for j = 1, max_reg do
H_lo[j] = HEX(H_hi[j]) .. HEX(H_lo[j])
end
H_hi = nil
H_lo = sub(table_concat(H_lo, "", 1, max_reg), 1, width / 4)
end
return H_lo
end
end
if message then
-- Actually perform calculations and return the SHA512 digest of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading
-- User should feed every chunk of input data as single argument to this function and finally get SHA512 digest by invoking this function without an argument
return partial
end
end
local function md5(message)
-- Create an instance (private objects for current calculation)
local H, length, tail = {unpack(md5_sha1_H, 1, 4)}, 0.0, ""
local function partial(message_part)
if message_part then
if tail then
length = length + #message_part
local offs = 0
if tail ~= "" and #tail + #message_part >= 64 then
offs = 64 - #tail
md5_feed_64(H, tail .. sub(message_part, 1, offs), 0, 64)
tail = ""
end
local size = #message_part - offs
local size_tail = size % 64
md5_feed_64(H, message_part, offs, size - size_tail)
tail = tail .. sub(message_part, #message_part + 1 - size_tail)
return partial
else
error("Adding more chunks is not allowed after receiving the result", 2)
end
else
if tail then
local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64)}
tail = nil
length = length * 8 -- convert "byte-counter" to "bit-counter"
for j = 4, 11 do
local low_byte = length % 256
final_blocks[j] = char(low_byte)
length = (length - low_byte) / 256
end
final_blocks = table_concat(final_blocks)
md5_feed_64(H, final_blocks, 0, #final_blocks)
for j = 1, 4 do
H[j] = HEX(H[j])
end
H = gsub(table_concat(H), "(..)(..)(..)(..)", "%4%3%2%1")
end
return H
end
end
if message then
-- Actually perform calculations and return the MD5 digest of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading
-- User should feed every chunk of input data as single argument to this function and finally get MD5 digest by invoking this function without an argument
return partial
end
end
local function sha1(message)
-- Create an instance (private objects for current calculation)
local H, length, tail = {unpack(md5_sha1_H)}, 0.0, ""
local function partial(message_part)
if message_part then
if tail then
length = length + #message_part
local offs = 0
if tail ~= "" and #tail + #message_part >= 64 then
offs = 64 - #tail
sha1_feed_64(H, tail .. sub(message_part, 1, offs), 0, 64)
tail = ""
end
local size = #message_part - offs
local size_tail = size % 64
sha1_feed_64(H, message_part, offs, size - size_tail)
tail = tail .. sub(message_part, #message_part + 1 - size_tail)
return partial
else
error("Adding more chunks is not allowed after receiving the result", 2)
end
else
if tail then
local final_blocks = {tail, "\128", string_rep("\0", (-9 - length) % 64 + 1)}
tail = nil
-- Assuming user data length is shorter than (2^53)-9 bytes
-- 2^53 bytes = 2^56 bits, so "bit-counter" fits in 7 bytes
length = length * (8 / 256 ^ 7) -- convert "byte-counter" to "bit-counter" and move decimal point to the left
for j = 4, 10 do
length = length % 1 * 256
final_blocks[j] = char(floor(length))
end
final_blocks = table_concat(final_blocks)
sha1_feed_64(H, final_blocks, 0, #final_blocks)
for j = 1, 5 do
H[j] = HEX(H[j])
end
H = table_concat(H)
end
return H
end
end
if message then
-- Actually perform calculations and return the SHA-1 digest of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading
-- User should feed every chunk of input data as single argument to this function and finally get SHA-1 digest by invoking this function without an argument
return partial
end
end
local function keccak(block_size_in_bytes, digest_size_in_bytes, is_SHAKE, message)
-- "block_size_in_bytes" is multiple of 8
if type(digest_size_in_bytes) ~= "number" then
-- arguments in SHAKE are swapped:
-- NIST FIPS 202 defines SHAKE(message,num_bits)
-- this module defines SHAKE(num_bytes,message)
-- it's easy to forget about this swap, hence the check
error("Argument 'digest_size_in_bytes' must be a number", 2)
end
-- Create an instance (private objects for current calculation)
local tail, lanes_lo, lanes_hi = "", create_array_of_lanes(), create_array_of_lanes()
local result
--~ pad the input N using the pad function, yielding a padded bit string P with a length divisible by r (such that n = len(P)/r is integer),
--~ break P into n consecutive r-bit pieces P0, ..., Pn-1 (last is zero-padded)
--~ initialize the state S to a string of b 0 bits.
--~ absorb the input into the state: For each block Pi,
--~ extend Pi at the end by a string of c 0 bits, yielding one of length b,
--~ XOR that with S and
--~ apply the block permutation f to the result, yielding a new state S
--~ initialize Z to be the empty string
--~ while the length of Z is less than d:
--~ append the first r bits of S to Z
--~ if Z is still less than d bits long, apply f to S, yielding a new state S.
--~ truncate Z to d bits
local function partial(message_part)
if message_part then
if tail then
local offs = 0
if tail ~= "" and #tail + #message_part >= block_size_in_bytes then
offs = block_size_in_bytes - #tail
keccak_feed(
lanes_lo,
lanes_hi,
tail .. sub(message_part, 1, offs),
0,
block_size_in_bytes,
block_size_in_bytes
)
tail = ""
end
local size = #message_part - offs
local size_tail = size % block_size_in_bytes
keccak_feed(lanes_lo, lanes_hi, message_part, offs, size - size_tail, block_size_in_bytes)
tail = tail .. sub(message_part, #message_part + 1 - size_tail)
return partial
else
error("Adding more chunks is not allowed after receiving the result", 2)
end
else
if tail then
-- append the following bits to the message: for usual SHA3: 011(0*)1, for SHAKE: 11111(0*)1
local gap_start = is_SHAKE and 31 or 6
tail =
tail ..
(#tail + 1 == block_size_in_bytes and char(gap_start + 128) or
char(gap_start) .. string_rep("\0", (-2 - #tail) % block_size_in_bytes) .. "\128")
keccak_feed(lanes_lo, lanes_hi, tail, 0, #tail, block_size_in_bytes)
tail = nil
local lanes_used = 0
local total_lanes = floor(block_size_in_bytes / 8)
local qwords = {}
local function get_next_qwords_of_digest(qwords_qty)
-- returns not more than 'qwords_qty' qwords ('qwords_qty' might be non-integer)
-- doesn't go across keccak-buffer boundary
-- block_size_in_bytes is a multiple of 8, so, keccak-buffer contains integer number of qwords
if lanes_used >= total_lanes then
keccak_feed(lanes_lo, lanes_hi, "\0\0\0\0\0\0\0\0", 0, 8, 8)
lanes_used = 0
end
qwords_qty = floor(math_min(qwords_qty, total_lanes - lanes_used))
for j = 1, qwords_qty do
qwords[j] = HEX(lanes_hi[lanes_used + j]) .. HEX(lanes_lo[lanes_used + j])
end
lanes_used = lanes_used + qwords_qty
return gsub(
table_concat(qwords, "", 1, qwords_qty),
"(..)(..)(..)(..)(..)(..)(..)(..)",
"%8%7%6%5%4%3%2%1"
), qwords_qty * 8
end
local parts = {} -- digest parts
local last_part, last_part_size = "", 0
local function get_next_part_of_digest(bytes_needed)
-- returns 'bytes_needed' bytes, for arbitrary integer 'bytes_needed'
bytes_needed = bytes_needed or 1
if bytes_needed <= last_part_size then
last_part_size = last_part_size - bytes_needed
local part_size_in_nibbles = bytes_needed * 2
local result = sub(last_part, 1, part_size_in_nibbles)
last_part = sub(last_part, part_size_in_nibbles + 1)
return result
end
local parts_qty = 0
if last_part_size > 0 then
parts_qty = 1
parts[parts_qty] = last_part
bytes_needed = bytes_needed - last_part_size
end
-- repeats until the length is enough
while bytes_needed >= 8 do
local next_part, next_part_size = get_next_qwords_of_digest(bytes_needed / 8)
parts_qty = parts_qty + 1
parts[parts_qty] = next_part
bytes_needed = bytes_needed - next_part_size
end
if bytes_needed > 0 then
last_part, last_part_size = get_next_qwords_of_digest(1)
parts_qty = parts_qty + 1
parts[parts_qty] = get_next_part_of_digest(bytes_needed)
else
last_part, last_part_size = "", 0
end
return table_concat(parts, "", 1, parts_qty)
end
if digest_size_in_bytes < 0 then
result = get_next_part_of_digest
else
result = get_next_part_of_digest(digest_size_in_bytes)
end
end
return result
end
end
if message then
-- Actually perform calculations and return the SHA3 digest of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading
-- User should feed every chunk of input data as single argument to this function and finally get SHA3 digest by invoking this function without an argument
return partial
end
end
local hex2bin, bin2base64, base642bin
do
function hex2bin(hex_string)
return (gsub(
hex_string,
"%x%x",
function(hh)
return char(tonumber(hh, 16))
end
))
end
local base64_symbols = {
["+"] = 62,
["-"] = 62,
[62] = "+",
["/"] = 63,
["_"] = 63,
[63] = "/",
["="] = -1,
["."] = -1,
[-1] = "="
}
local symbol_index = 0
for j, pair in ipairs {"AZ", "az", "09"} do
for ascii = byte(pair), byte(pair, 2) do
local ch = char(ascii)
base64_symbols[ch] = symbol_index
base64_symbols[symbol_index] = ch
symbol_index = symbol_index + 1
end
end
function bin2base64(binary_string)
local result = {}
for pos = 1, #binary_string, 3 do
local c1, c2, c3, c4 = byte(sub(binary_string, pos, pos + 2) .. "\0", 1, -1)
result[#result + 1] =
base64_symbols[floor(c1 / 4)] ..
base64_symbols[c1 % 4 * 16 + floor(c2 / 16)] ..
base64_symbols[c3 and c2 % 16 * 4 + floor(c3 / 64) or -1] .. base64_symbols[c4 and c3 % 64 or -1]
end
return table_concat(result)
end
function base642bin(base64_string)
local result, chars_qty = {}, 3
for pos, ch in gmatch(gsub(base64_string, "%s+", ""), "()(.)") do
local code = base64_symbols[ch]
if code < 0 then
chars_qty = chars_qty - 1
code = 0
end
local idx = pos % 4
if idx > 0 then
result[-idx] = code
else
local c1 = result[-1] * 4 + floor(result[-2] / 16)
local c2 = (result[-2] % 16) * 16 + floor(result[-3] / 4)
local c3 = (result[-3] % 4) * 64 + code
result[#result + 1] = sub(char(c1, c2, c3), 1, chars_qty)
end
end
return table_concat(result)
end
end
local block_size_for_HMAC -- this table will be initialized at the end of the module
local function pad_and_xor(str, result_length, byte_for_xor)
return gsub(
str,
".",
function(c)
return char(XOR_BYTE(byte(c), byte_for_xor))
end
) .. string_rep(char(byte_for_xor), result_length - #str)
end
local function hmac(hash_func, key, message)
-- Create an instance (private objects for current calculation)
local block_size = block_size_for_HMAC[hash_func]
if not block_size then
error("Unknown hash function", 2)
end
if #key > block_size then
key = hex2bin(hash_func(key))
end
local append = hash_func()(pad_and_xor(key, block_size, 0x36))
local result
local function partial(message_part)
if not message_part then
result = result or hash_func(pad_and_xor(key, block_size, 0x5C) .. hex2bin(append()))
return result
elseif result then
error("Adding more chunks is not allowed after receiving the result", 2)
else
append(message_part)
return partial
end
end
if message then
-- Actually perform calculations and return the HMAC of a message
return partial(message)()
else
-- Return function for chunk-by-chunk loading of a message
-- User should feed every chunk of the message as single argument to this function and finally get HMAC by invoking this function without an argument
return partial
end
end
lib.md5 = md5 -- MD5
lib.sha1 = sha1 -- SHA-1
-- SHA2 hash functions:
lib.sha224 = function(message)
return sha256ext(224, message)
end -- SHA-224
lib.sha256 = function(message)
return sha256ext(256, message)
end -- SHA-256
lib.sha512_224 = function(message)
return sha512ext(224, message)
end -- SHA-512/224
lib.sha512_256 = function(message)
return sha512ext(256, message)
end -- SHA-512/256
lib.sha384 = function(message)
return sha512ext(384, message)
end -- SHA-384
lib.sha512 = function(message)
return sha512ext(512, message)
end -- SHA-512
-- SHA3 hash functions:
lib.sha3_224 = function(message)
return keccak((1600 - 2 * 224) / 8, 224 / 8, false, message)
end -- SHA3-224
lib.sha3_256 = function(message)
return keccak((1600 - 2 * 256) / 8, 256 / 8, false, message)
end -- SHA3-256
lib.sha3_384 = function(message)
return keccak((1600 - 2 * 384) / 8, 384 / 8, false, message)
end -- SHA3-384
lib.sha3_512 = function(message)
return keccak((1600 - 2 * 512) / 8, 512 / 8, false, message)
end -- SHA3-512
lib.shake128 = function(digest_size_in_bytes, message)
return keccak((1600 - 2 * 128) / 8, digest_size_in_bytes, true, message)
end -- SHAKE128
lib.shake256 = function(digest_size_in_bytes, message)
return keccak((1600 - 2 * 256) / 8, digest_size_in_bytes, true, message)
end -- SHAKE256
-- misc utilities:
lib.hmac = hmac -- HMAC(hash_func, key, message) is applicable to any hash function from this module except SHAKE*
lib.hex2bin = hex2bin -- converts hexadecimal representation to binary string
lib.base642bin = base642bin -- converts base64 representation to binary string
lib.bin2base64 = bin2base64 -- converts binary string to base64 representation
block_size_for_HMAC = {
[lib.md5] = 64,
[lib.sha1] = 64,
[lib.sha224] = 64,
[lib.sha256] = 64,
[lib.sha512_224] = 128,
[lib.sha512_256] = 128,
[lib.sha384] = 128,
[lib.sha512] = 128,
[lib.sha3_224] = (1600 - 2 * 224) / 8,
[lib.sha3_256] = (1600 - 2 * 256) / 8,
[lib.sha3_384] = (1600 - 2 * 384) / 8,
[lib.sha3_512] = (1600 - 2 * 512) / 8
}
|
local path = (...):gsub("[^%.]*$", "")
local M = require(path .. "master")
M.ImGuiComboFlags_None = 0
M.ImGuiComboFlags_PopupAlignLeft = 1
M.ImGuiComboFlags_HeightSmall = 2
M.ImGuiComboFlags_HeightRegular = 4
M.ImGuiComboFlags_HeightLarge = 8
M.ImGuiComboFlags_HeightLargest = 16
M.ImGuiComboFlags_NoArrowButton = 32
M.ImGuiComboFlags_NoPreview = 64
M.ImGuiComboFlags_HeightMask_ = 30
M.ImGuiTreeNodeFlags_None = 0
M.ImGuiTreeNodeFlags_Selected = 1
M.ImGuiTreeNodeFlags_Framed = 2
M.ImGuiTreeNodeFlags_AllowItemOverlap = 4
M.ImGuiTreeNodeFlags_NoTreePushOnOpen = 8
M.ImGuiTreeNodeFlags_NoAutoOpenOnLog = 16
M.ImGuiTreeNodeFlags_DefaultOpen = 32
M.ImGuiTreeNodeFlags_OpenOnDoubleClick = 64
M.ImGuiTreeNodeFlags_OpenOnArrow = 128
M.ImGuiTreeNodeFlags_Leaf = 256
M.ImGuiTreeNodeFlags_Bullet = 512
M.ImGuiTreeNodeFlags_FramePadding = 1024
M.ImGuiTreeNodeFlags_SpanAvailWidth = 2048
M.ImGuiTreeNodeFlags_SpanFullWidth = 4096
M.ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 8192
M.ImGuiTreeNodeFlags_CollapsingHeader = 26
M.ImGuiTabItemFlags_None = 0
M.ImGuiTabItemFlags_UnsavedDocument = 1
M.ImGuiTabItemFlags_SetSelected = 2
M.ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 4
M.ImGuiTabItemFlags_NoPushId = 8
M.ImGuiTabItemFlags_NoTooltip = 16
M.ImGuiTabItemFlags_NoReorder = 32
M.ImGuiTabItemFlags_Leading = 64
M.ImGuiTabItemFlags_Trailing = 128
M.ImGuiColorEditFlags_None = 0
M.ImGuiColorEditFlags_NoAlpha = 2
M.ImGuiColorEditFlags_NoPicker = 4
M.ImGuiColorEditFlags_NoOptions = 8
M.ImGuiColorEditFlags_NoSmallPreview = 16
M.ImGuiColorEditFlags_NoInputs = 32
M.ImGuiColorEditFlags_NoTooltip = 64
M.ImGuiColorEditFlags_NoLabel = 128
M.ImGuiColorEditFlags_NoSidePreview = 256
M.ImGuiColorEditFlags_NoDragDrop = 512
M.ImGuiColorEditFlags_NoBorder = 1024
M.ImGuiColorEditFlags_AlphaBar = 65536
M.ImGuiColorEditFlags_AlphaPreview = 131072
M.ImGuiColorEditFlags_AlphaPreviewHalf = 262144
M.ImGuiColorEditFlags_HDR = 524288
M.ImGuiColorEditFlags_DisplayRGB = 1048576
M.ImGuiColorEditFlags_DisplayHSV = 2097152
M.ImGuiColorEditFlags_DisplayHex = 4194304
M.ImGuiColorEditFlags_Uint8 = 8388608
M.ImGuiColorEditFlags_Float = 16777216
M.ImGuiColorEditFlags_PickerHueBar = 33554432
M.ImGuiColorEditFlags_PickerHueWheel = 67108864
M.ImGuiColorEditFlags_InputRGB = 134217728
M.ImGuiColorEditFlags_InputHSV = 268435456
M.ImGuiColorEditFlags_DefaultOptions_ = 177209344
M.ImGuiColorEditFlags_DisplayMask_ = 7340032
M.ImGuiColorEditFlags_DataTypeMask_ = 25165824
M.ImGuiColorEditFlags_PickerMask_ = 100663296
M.ImGuiColorEditFlags_InputMask_ = 402653184
M.ImGuiDockNodeFlags_None = 0
M.ImGuiDockNodeFlags_KeepAliveOnly = 1
M.ImGuiDockNodeFlags_NoDockingInCentralNode = 4
M.ImGuiDockNodeFlags_PassthruCentralNode = 8
M.ImGuiDockNodeFlags_NoSplit = 16
M.ImGuiDockNodeFlags_NoResize = 32
M.ImGuiDockNodeFlags_AutoHideTabBar = 64
M.ImGuiWindowFlags_None = 0
M.ImGuiWindowFlags_NoTitleBar = 1
M.ImGuiWindowFlags_NoResize = 2
M.ImGuiWindowFlags_NoMove = 4
M.ImGuiWindowFlags_NoScrollbar = 8
M.ImGuiWindowFlags_NoScrollWithMouse = 16
M.ImGuiWindowFlags_NoCollapse = 32
M.ImGuiWindowFlags_AlwaysAutoResize = 64
M.ImGuiWindowFlags_NoBackground = 128
M.ImGuiWindowFlags_NoSavedSettings = 256
M.ImGuiWindowFlags_NoMouseInputs = 512
M.ImGuiWindowFlags_MenuBar = 1024
M.ImGuiWindowFlags_HorizontalScrollbar = 2048
M.ImGuiWindowFlags_NoFocusOnAppearing = 4096
M.ImGuiWindowFlags_NoBringToFrontOnFocus = 8192
M.ImGuiWindowFlags_AlwaysVerticalScrollbar = 16384
M.ImGuiWindowFlags_AlwaysHorizontalScrollbar = 32768
M.ImGuiWindowFlags_AlwaysUseWindowPadding = 65536
M.ImGuiWindowFlags_NoNavInputs = 262144
M.ImGuiWindowFlags_NoNavFocus = 524288
M.ImGuiWindowFlags_UnsavedDocument = 1048576
M.ImGuiWindowFlags_NoDocking = 2097152
M.ImGuiWindowFlags_NoNav = 786432
M.ImGuiWindowFlags_NoDecoration = 43
M.ImGuiWindowFlags_NoInputs = 786944
M.ImGuiWindowFlags_NavFlattened = 8388608
M.ImGuiWindowFlags_ChildWindow = 16777216
M.ImGuiWindowFlags_Tooltip = 33554432
M.ImGuiWindowFlags_Popup = 67108864
M.ImGuiWindowFlags_Modal = 134217728
M.ImGuiWindowFlags_ChildMenu = 268435456
M.ImGuiWindowFlags_DockNodeHost = 536870912
M.ImGuiTabBarFlags_None = 0
M.ImGuiTabBarFlags_Reorderable = 1
M.ImGuiTabBarFlags_AutoSelectNewTabs = 2
M.ImGuiTabBarFlags_TabListPopupButton = 4
M.ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 8
M.ImGuiTabBarFlags_NoTabListScrollingButtons = 16
M.ImGuiTabBarFlags_NoTooltip = 32
M.ImGuiTabBarFlags_FittingPolicyResizeDown = 64
M.ImGuiTabBarFlags_FittingPolicyScroll = 128
M.ImGuiTabBarFlags_FittingPolicyMask_ = 192
M.ImGuiTabBarFlags_FittingPolicyDefault_ = 64
M.ImGuiCond_None = 0
M.ImGuiCond_Always = 1
M.ImGuiCond_Once = 2
M.ImGuiCond_FirstUseEver = 4
M.ImGuiCond_Appearing = 8
M.ImGuiTableColumnFlags_None = 0
M.ImGuiTableColumnFlags_Disabled = 1
M.ImGuiTableColumnFlags_DefaultHide = 2
M.ImGuiTableColumnFlags_DefaultSort = 4
M.ImGuiTableColumnFlags_WidthStretch = 8
M.ImGuiTableColumnFlags_WidthFixed = 16
M.ImGuiTableColumnFlags_NoResize = 32
M.ImGuiTableColumnFlags_NoReorder = 64
M.ImGuiTableColumnFlags_NoHide = 128
M.ImGuiTableColumnFlags_NoClip = 256
M.ImGuiTableColumnFlags_NoSort = 512
M.ImGuiTableColumnFlags_NoSortAscending = 1024
M.ImGuiTableColumnFlags_NoSortDescending = 2048
M.ImGuiTableColumnFlags_NoHeaderLabel = 4096
M.ImGuiTableColumnFlags_NoHeaderWidth = 8192
M.ImGuiTableColumnFlags_PreferSortAscending = 16384
M.ImGuiTableColumnFlags_PreferSortDescending = 32768
M.ImGuiTableColumnFlags_IndentEnable = 65536
M.ImGuiTableColumnFlags_IndentDisable = 131072
M.ImGuiTableColumnFlags_IsEnabled = 16777216
M.ImGuiTableColumnFlags_IsVisible = 33554432
M.ImGuiTableColumnFlags_IsSorted = 67108864
M.ImGuiTableColumnFlags_IsHovered = 134217728
M.ImGuiTableColumnFlags_WidthMask_ = 24
M.ImGuiTableColumnFlags_IndentMask_ = 196608
M.ImGuiTableColumnFlags_StatusMask_ = 251658240
M.ImGuiTableColumnFlags_NoDirectResize_ = 1073741824
M.ImGuiBackendFlags_None = 0
M.ImGuiBackendFlags_HasGamepad = 1
M.ImGuiBackendFlags_HasMouseCursors = 2
M.ImGuiBackendFlags_HasSetMousePos = 4
M.ImGuiBackendFlags_RendererHasVtxOffset = 8
M.ImGuiBackendFlags_PlatformHasViewports = 1024
M.ImGuiBackendFlags_HasMouseHoveredViewport = 2048
M.ImGuiBackendFlags_RendererHasViewports = 4096
M.ImGuiDragDropFlags_None = 0
M.ImGuiDragDropFlags_SourceNoPreviewTooltip = 1
M.ImGuiDragDropFlags_SourceNoDisableHover = 2
M.ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 4
M.ImGuiDragDropFlags_SourceAllowNullID = 8
M.ImGuiDragDropFlags_SourceExtern = 16
M.ImGuiDragDropFlags_SourceAutoExpirePayload = 32
M.ImGuiDragDropFlags_AcceptBeforeDelivery = 1024
M.ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 2048
M.ImGuiDragDropFlags_AcceptNoPreviewTooltip = 4096
M.ImGuiDragDropFlags_AcceptPeekOnly = 3072
M.ImDrawListFlags_None = 0
M.ImDrawListFlags_AntiAliasedLines = 1
M.ImDrawListFlags_AntiAliasedLinesUseTex = 2
M.ImDrawListFlags_AntiAliasedFill = 4
M.ImDrawListFlags_AllowVtxOffset = 8
M.ImGuiSliderFlags_None = 0
M.ImGuiSliderFlags_AlwaysClamp = 16
M.ImGuiSliderFlags_Logarithmic = 32
M.ImGuiSliderFlags_NoRoundToFormat = 64
M.ImGuiSliderFlags_NoInput = 128
M.ImGuiSliderFlags_InvalidMask_ = 1879048207
M.ImGuiDir_None = -1
M.ImGuiDir_Left = 0
M.ImGuiDir_Right = 1
M.ImGuiDir_Up = 2
M.ImGuiDir_Down = 3
M.ImGuiDir_COUNT = 4
M.ImGuiPopupFlags_None = 0
M.ImGuiPopupFlags_MouseButtonLeft = 0
M.ImGuiPopupFlags_MouseButtonRight = 1
M.ImGuiPopupFlags_MouseButtonMiddle = 2
M.ImGuiPopupFlags_MouseButtonMask_ = 31
M.ImGuiPopupFlags_MouseButtonDefault_ = 1
M.ImGuiPopupFlags_NoOpenOverExistingPopup = 32
M.ImGuiPopupFlags_NoOpenOverItems = 64
M.ImGuiPopupFlags_AnyPopupId = 128
M.ImGuiPopupFlags_AnyPopupLevel = 256
M.ImGuiPopupFlags_AnyPopup = 384
M.ImGuiStyleVar_Alpha = 0
M.ImGuiStyleVar_DisabledAlpha = 1
M.ImGuiStyleVar_WindowPadding = 2
M.ImGuiStyleVar_WindowRounding = 3
M.ImGuiStyleVar_WindowBorderSize = 4
M.ImGuiStyleVar_WindowMinSize = 5
M.ImGuiStyleVar_WindowTitleAlign = 6
M.ImGuiStyleVar_ChildRounding = 7
M.ImGuiStyleVar_ChildBorderSize = 8
M.ImGuiStyleVar_PopupRounding = 9
M.ImGuiStyleVar_PopupBorderSize = 10
M.ImGuiStyleVar_FramePadding = 11
M.ImGuiStyleVar_FrameRounding = 12
M.ImGuiStyleVar_FrameBorderSize = 13
M.ImGuiStyleVar_ItemSpacing = 14
M.ImGuiStyleVar_ItemInnerSpacing = 15
M.ImGuiStyleVar_IndentSpacing = 16
M.ImGuiStyleVar_CellPadding = 17
M.ImGuiStyleVar_ScrollbarSize = 18
M.ImGuiStyleVar_ScrollbarRounding = 19
M.ImGuiStyleVar_GrabMinSize = 20
M.ImGuiStyleVar_GrabRounding = 21
M.ImGuiStyleVar_TabRounding = 22
M.ImGuiStyleVar_ButtonTextAlign = 23
M.ImGuiStyleVar_SelectableTextAlign = 24
M.ImGuiStyleVar_COUNT = 25
M.ImGuiHoveredFlags_None = 0
M.ImGuiHoveredFlags_ChildWindows = 1
M.ImGuiHoveredFlags_RootWindow = 2
M.ImGuiHoveredFlags_AnyWindow = 4
M.ImGuiHoveredFlags_NoPopupHierarchy = 8
M.ImGuiHoveredFlags_DockHierarchy = 16
M.ImGuiHoveredFlags_AllowWhenBlockedByPopup = 32
M.ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 128
M.ImGuiHoveredFlags_AllowWhenOverlapped = 256
M.ImGuiHoveredFlags_AllowWhenDisabled = 512
M.ImGuiHoveredFlags_RectOnly = 416
M.ImGuiHoveredFlags_RootAndChildWindows = 3
M.ImGuiKeyModFlags_None = 0
M.ImGuiKeyModFlags_Ctrl = 1
M.ImGuiKeyModFlags_Shift = 2
M.ImGuiKeyModFlags_Alt = 4
M.ImGuiKeyModFlags_Super = 8
M.ImGuiViewportFlags_None = 0
M.ImGuiViewportFlags_IsPlatformWindow = 1
M.ImGuiViewportFlags_IsPlatformMonitor = 2
M.ImGuiViewportFlags_OwnedByApp = 4
M.ImGuiViewportFlags_NoDecoration = 8
M.ImGuiViewportFlags_NoTaskBarIcon = 16
M.ImGuiViewportFlags_NoFocusOnAppearing = 32
M.ImGuiViewportFlags_NoFocusOnClick = 64
M.ImGuiViewportFlags_NoInputs = 128
M.ImGuiViewportFlags_NoRendererClear = 256
M.ImGuiViewportFlags_TopMost = 512
M.ImGuiViewportFlags_Minimized = 1024
M.ImGuiViewportFlags_NoAutoMerge = 2048
M.ImGuiViewportFlags_CanHostOtherWindows = 4096
M.ImGuiNavInput_Activate = 0
M.ImGuiNavInput_Cancel = 1
M.ImGuiNavInput_Input = 2
M.ImGuiNavInput_Menu = 3
M.ImGuiNavInput_DpadLeft = 4
M.ImGuiNavInput_DpadRight = 5
M.ImGuiNavInput_DpadUp = 6
M.ImGuiNavInput_DpadDown = 7
M.ImGuiNavInput_LStickLeft = 8
M.ImGuiNavInput_LStickRight = 9
M.ImGuiNavInput_LStickUp = 10
M.ImGuiNavInput_LStickDown = 11
M.ImGuiNavInput_FocusPrev = 12
M.ImGuiNavInput_FocusNext = 13
M.ImGuiNavInput_TweakSlow = 14
M.ImGuiNavInput_TweakFast = 15
M.ImGuiNavInput_KeyLeft_ = 16
M.ImGuiNavInput_KeyRight_ = 17
M.ImGuiNavInput_KeyUp_ = 18
M.ImGuiNavInput_KeyDown_ = 19
M.ImGuiNavInput_COUNT = 20
M.ImGuiNavInput_InternalStart_ = 16
M.ImGuiFocusedFlags_None = 0
M.ImGuiFocusedFlags_ChildWindows = 1
M.ImGuiFocusedFlags_RootWindow = 2
M.ImGuiFocusedFlags_AnyWindow = 4
M.ImGuiFocusedFlags_NoPopupHierarchy = 8
M.ImGuiFocusedFlags_DockHierarchy = 16
M.ImGuiFocusedFlags_RootAndChildWindows = 3
M.ImGuiSelectableFlags_None = 0
M.ImGuiSelectableFlags_DontClosePopups = 1
M.ImGuiSelectableFlags_SpanAllColumns = 2
M.ImGuiSelectableFlags_AllowDoubleClick = 4
M.ImGuiSelectableFlags_Disabled = 8
M.ImGuiSelectableFlags_AllowItemOverlap = 16
M.ImGuiKey_Tab = 0
M.ImGuiKey_LeftArrow = 1
M.ImGuiKey_RightArrow = 2
M.ImGuiKey_UpArrow = 3
M.ImGuiKey_DownArrow = 4
M.ImGuiKey_PageUp = 5
M.ImGuiKey_PageDown = 6
M.ImGuiKey_Home = 7
M.ImGuiKey_End = 8
M.ImGuiKey_Insert = 9
M.ImGuiKey_Delete = 10
M.ImGuiKey_Backspace = 11
M.ImGuiKey_Space = 12
M.ImGuiKey_Enter = 13
M.ImGuiKey_Escape = 14
M.ImGuiKey_KeyPadEnter = 15
M.ImGuiKey_A = 16
M.ImGuiKey_C = 17
M.ImGuiKey_V = 18
M.ImGuiKey_X = 19
M.ImGuiKey_Y = 20
M.ImGuiKey_Z = 21
M.ImGuiKey_COUNT = 22
M.ImGuiMouseButton_Left = 0
M.ImGuiMouseButton_Right = 1
M.ImGuiMouseButton_Middle = 2
M.ImGuiMouseButton_COUNT = 5
M.ImDrawFlags_None = 0
M.ImDrawFlags_Closed = 1
M.ImDrawFlags_RoundCornersTopLeft = 16
M.ImDrawFlags_RoundCornersTopRight = 32
M.ImDrawFlags_RoundCornersBottomLeft = 64
M.ImDrawFlags_RoundCornersBottomRight = 128
M.ImDrawFlags_RoundCornersNone = 256
M.ImDrawFlags_RoundCornersTop = 48
M.ImDrawFlags_RoundCornersBottom = 192
M.ImDrawFlags_RoundCornersLeft = 80
M.ImDrawFlags_RoundCornersRight = 160
M.ImDrawFlags_RoundCornersAll = 240
M.ImDrawFlags_RoundCornersDefault_ = 240
M.ImDrawFlags_RoundCornersMask_ = 496
M.ImGuiCol_Text = 0
M.ImGuiCol_TextDisabled = 1
M.ImGuiCol_WindowBg = 2
M.ImGuiCol_ChildBg = 3
M.ImGuiCol_PopupBg = 4
M.ImGuiCol_Border = 5
M.ImGuiCol_BorderShadow = 6
M.ImGuiCol_FrameBg = 7
M.ImGuiCol_FrameBgHovered = 8
M.ImGuiCol_FrameBgActive = 9
M.ImGuiCol_TitleBg = 10
M.ImGuiCol_TitleBgActive = 11
M.ImGuiCol_TitleBgCollapsed = 12
M.ImGuiCol_MenuBarBg = 13
M.ImGuiCol_ScrollbarBg = 14
M.ImGuiCol_ScrollbarGrab = 15
M.ImGuiCol_ScrollbarGrabHovered = 16
M.ImGuiCol_ScrollbarGrabActive = 17
M.ImGuiCol_CheckMark = 18
M.ImGuiCol_SliderGrab = 19
M.ImGuiCol_SliderGrabActive = 20
M.ImGuiCol_Button = 21
M.ImGuiCol_ButtonHovered = 22
M.ImGuiCol_ButtonActive = 23
M.ImGuiCol_Header = 24
M.ImGuiCol_HeaderHovered = 25
M.ImGuiCol_HeaderActive = 26
M.ImGuiCol_Separator = 27
M.ImGuiCol_SeparatorHovered = 28
M.ImGuiCol_SeparatorActive = 29
M.ImGuiCol_ResizeGrip = 30
M.ImGuiCol_ResizeGripHovered = 31
M.ImGuiCol_ResizeGripActive = 32
M.ImGuiCol_Tab = 33
M.ImGuiCol_TabHovered = 34
M.ImGuiCol_TabActive = 35
M.ImGuiCol_TabUnfocused = 36
M.ImGuiCol_TabUnfocusedActive = 37
M.ImGuiCol_DockingPreview = 38
M.ImGuiCol_DockingEmptyBg = 39
M.ImGuiCol_PlotLines = 40
M.ImGuiCol_PlotLinesHovered = 41
M.ImGuiCol_PlotHistogram = 42
M.ImGuiCol_PlotHistogramHovered = 43
M.ImGuiCol_TableHeaderBg = 44
M.ImGuiCol_TableBorderStrong = 45
M.ImGuiCol_TableBorderLight = 46
M.ImGuiCol_TableRowBg = 47
M.ImGuiCol_TableRowBgAlt = 48
M.ImGuiCol_TextSelectedBg = 49
M.ImGuiCol_DragDropTarget = 50
M.ImGuiCol_NavHighlight = 51
M.ImGuiCol_NavWindowingHighlight = 52
M.ImGuiCol_NavWindowingDimBg = 53
M.ImGuiCol_ModalWindowDimBg = 54
M.ImGuiCol_COUNT = 55
M.ImGuiButtonFlags_None = 0
M.ImGuiButtonFlags_MouseButtonLeft = 1
M.ImGuiButtonFlags_MouseButtonRight = 2
M.ImGuiButtonFlags_MouseButtonMiddle = 4
M.ImGuiButtonFlags_MouseButtonMask_ = 7
M.ImGuiButtonFlags_MouseButtonDefault_ = 1
M.ImGuiDataType_S8 = 0
M.ImGuiDataType_U8 = 1
M.ImGuiDataType_S16 = 2
M.ImGuiDataType_U16 = 3
M.ImGuiDataType_S32 = 4
M.ImGuiDataType_U32 = 5
M.ImGuiDataType_S64 = 6
M.ImGuiDataType_U64 = 7
M.ImGuiDataType_Float = 8
M.ImGuiDataType_Double = 9
M.ImGuiDataType_COUNT = 10
M.ImGuiTableFlags_None = 0
M.ImGuiTableFlags_Resizable = 1
M.ImGuiTableFlags_Reorderable = 2
M.ImGuiTableFlags_Hideable = 4
M.ImGuiTableFlags_Sortable = 8
M.ImGuiTableFlags_NoSavedSettings = 16
M.ImGuiTableFlags_ContextMenuInBody = 32
M.ImGuiTableFlags_RowBg = 64
M.ImGuiTableFlags_BordersInnerH = 128
M.ImGuiTableFlags_BordersOuterH = 256
M.ImGuiTableFlags_BordersInnerV = 512
M.ImGuiTableFlags_BordersOuterV = 1024
M.ImGuiTableFlags_BordersH = 384
M.ImGuiTableFlags_BordersV = 1536
M.ImGuiTableFlags_BordersInner = 640
M.ImGuiTableFlags_BordersOuter = 1280
M.ImGuiTableFlags_Borders = 1920
M.ImGuiTableFlags_NoBordersInBody = 2048
M.ImGuiTableFlags_NoBordersInBodyUntilResize = 4096
M.ImGuiTableFlags_SizingFixedFit = 8192
M.ImGuiTableFlags_SizingFixedSame = 16384
M.ImGuiTableFlags_SizingStretchProp = 24576
M.ImGuiTableFlags_SizingStretchSame = 32768
M.ImGuiTableFlags_NoHostExtendX = 65536
M.ImGuiTableFlags_NoHostExtendY = 131072
M.ImGuiTableFlags_NoKeepColumnsVisible = 262144
M.ImGuiTableFlags_PreciseWidths = 524288
M.ImGuiTableFlags_NoClip = 1048576
M.ImGuiTableFlags_PadOuterX = 2097152
M.ImGuiTableFlags_NoPadOuterX = 4194304
M.ImGuiTableFlags_NoPadInnerX = 8388608
M.ImGuiTableFlags_ScrollX = 16777216
M.ImGuiTableFlags_ScrollY = 33554432
M.ImGuiTableFlags_SortMulti = 67108864
M.ImGuiTableFlags_SortTristate = 134217728
M.ImGuiTableFlags_SizingMask_ = 57344
M.ImGuiTableBgTarget_None = 0
M.ImGuiTableBgTarget_RowBg0 = 1
M.ImGuiTableBgTarget_RowBg1 = 2
M.ImGuiTableBgTarget_CellBg = 3
M.ImFontAtlasFlags_None = 0
M.ImFontAtlasFlags_NoPowerOfTwoHeight = 1
M.ImFontAtlasFlags_NoMouseCursors = 2
M.ImFontAtlasFlags_NoBakedLines = 4
M.ImGuiConfigFlags_None = 0
M.ImGuiConfigFlags_NavEnableKeyboard = 1
M.ImGuiConfigFlags_NavEnableGamepad = 2
M.ImGuiConfigFlags_NavEnableSetMousePos = 4
M.ImGuiConfigFlags_NavNoCaptureKeyboard = 8
M.ImGuiConfigFlags_NoMouse = 16
M.ImGuiConfigFlags_NoMouseCursorChange = 32
M.ImGuiConfigFlags_DockingEnable = 64
M.ImGuiConfigFlags_ViewportsEnable = 1024
M.ImGuiConfigFlags_DpiEnableScaleViewports = 16384
M.ImGuiConfigFlags_DpiEnableScaleFonts = 32768
M.ImGuiConfigFlags_IsSRGB = 1048576
M.ImGuiConfigFlags_IsTouchScreen = 2097152
M.ImGuiInputTextFlags_None = 0
M.ImGuiInputTextFlags_CharsDecimal = 1
M.ImGuiInputTextFlags_CharsHexadecimal = 2
M.ImGuiInputTextFlags_CharsUppercase = 4
M.ImGuiInputTextFlags_CharsNoBlank = 8
M.ImGuiInputTextFlags_AutoSelectAll = 16
M.ImGuiInputTextFlags_EnterReturnsTrue = 32
M.ImGuiInputTextFlags_CallbackCompletion = 64
M.ImGuiInputTextFlags_CallbackHistory = 128
M.ImGuiInputTextFlags_CallbackAlways = 256
M.ImGuiInputTextFlags_CallbackCharFilter = 512
M.ImGuiInputTextFlags_AllowTabInput = 1024
M.ImGuiInputTextFlags_CtrlEnterForNewLine = 2048
M.ImGuiInputTextFlags_NoHorizontalScroll = 4096
M.ImGuiInputTextFlags_AlwaysOverwrite = 8192
M.ImGuiInputTextFlags_ReadOnly = 16384
M.ImGuiInputTextFlags_Password = 32768
M.ImGuiInputTextFlags_NoUndoRedo = 65536
M.ImGuiInputTextFlags_CharsScientific = 131072
M.ImGuiInputTextFlags_CallbackResize = 262144
M.ImGuiInputTextFlags_CallbackEdit = 524288
M.ImGuiTableRowFlags_None = 0
M.ImGuiTableRowFlags_Headers = 1
M.ImGuiSortDirection_None = 0
M.ImGuiSortDirection_Ascending = 1
M.ImGuiSortDirection_Descending = 2
M.ImGuiMouseCursor_None = -1
M.ImGuiMouseCursor_Arrow = 0
M.ImGuiMouseCursor_TextInput = 1
M.ImGuiMouseCursor_ResizeAll = 2
M.ImGuiMouseCursor_ResizeNS = 3
M.ImGuiMouseCursor_ResizeEW = 4
M.ImGuiMouseCursor_ResizeNESW = 5
M.ImGuiMouseCursor_ResizeNWSE = 6
M.ImGuiMouseCursor_Hand = 7
M.ImGuiMouseCursor_NotAllowed = 8
M.ImGuiMouseCursor_COUNT = 9 |
-- Connecting to Redis
local redis = require "resty.redis"
local red = redis:new()
-- Divides string into substrings based on a delimiter, returning an array of these substrings.
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- Write data from shared memory to Redis
function write_to_redis(cache, host)
-- Blosking write to Redis
cache:set('block', 1)
-- Set timeoute to Redis
red:set_timeout(1000) -- 1 sec
-- Configure connection to Redis
local redis_host = ngx.var.redis_host
if ngx.var.redis_host == nil then redis_host = 'localhost' end
local redis_port = ngx.var.redis_port
if ngx.var.redis_port == nil then redis_port = 6379 end
local redis_db = ngx.var.redis_db
if ngx.var.redis_db == nil then redis_db = 1 end
-- Trying to sonnect to Redis
local ok, err = red:connect(redis_host, redis_port)
if not ok then
ngx.log(ngx.ERR, "failed to connect: ", err)
return
end
red:select(redis_db)
-- Get list of keys in shared memory (default 1024)
-- This is a blocking operation, so, be careful
local keys = cache:get_keys()
-- Get valuse of keys and write to Redis
for _,value in pairs(keys) do
local k = value:split('/')
if k[2] ~= nil then
local redis_key = k[1]
local record = k[2]
local views = cache:get(value)
-- Write to redis key
red:zincrby(redis_key, views, record)
-- Delete key after write
cache:delete(value)
end
end
-- Remove blocking
cache:delete('block')
end
-- Write data to shared memory
function write_counter(redis_key, record, host)
local locked
local lock_ttl = 3 -- 3 sec
-- Shared memory
local cache = ngx.shared.countercache
-- Record key
local local_key = redis_key..'/'..record
-- Check write to redis
locked = cache:get('block')
-- Get key from shared memory
local chunk = cache:get(local_key)
-- If we have key
if chunk then
-- Increment
cache:incr(local_key, 1)
else
-- Else, set key
cache:set(local_key, 1)
end
-- If write to redis not blocked
if locked == nil then
-- Start write to Redis
write_to_redis(cache, host)
-- After this, lock write to Redis for lock_ttl sec
cache:set('block', 1, lock_ttl)
end
end
-- If request have http_referer, continue
if ngx.var.http_referer then
local uri
local host
-- Get host and path from http_referer
host, uri = ngx.var.http_referer:match('https?://([^/]+)(.*)')
-- If we find host and path, continue
if host ~= nil and uri ~= nil and uri ~= '' then
-- Key for total views
local total = host..':views:total'
-- Key for aggreagte views
local today = host..':views:'..ngx.today()
-- Write views to shared memory
write_counter(today, uri, host)
write_counter(total, uri, host)
-- For low visited host you don't need to use shared memory
-- and can write data directly to Redis
-- red:set_timeout(1000)
-- local redis_host = ngx.var.redis_host
-- if ngx.var.redis_host == nil then redis_host = 'localhost' end
-- local redis_port = ngx.var.redis_port
-- if ngx.var.redis_port == nil then redis_port = 6379 end
-- local redis_db = ngx.var.redis_db
-- if ngx.var.redis_db == nil then redis_db = 1 end
-- local ok, err = red:connect(redis_host, redis_port)
-- if not ok then
-- ngx.log(ngx.ERR, "failed to connect: ", err)
-- return
-- end
-- red:select(redis_db)
-- red:zincrby(total, 1, uri)
-- red:zincrby(today, 1, uri)
end
-- Save conection pool for 10 sec
red:set_keepalive(10000, 128)
end
-- Send 0.gif to client
ngx.say(ngx.decode_base64('R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='))
|
-- The Computer Language Shootout
-- http://shootout.alioth.debian.org/
-- contributed by Mike Pall
local function fannkuch(n)
local p, q, s, odd, check, maxflips = {}, {}, {}, true, 0, 0
for i=1,n do p[i] = i; s[i] = i end
repeat
-- Print max. 30 permutations.
if check < 30 then
if not p[n] then return maxflips end -- Catch n = 0, 1, 2.
for i=1,n do io.write(p[i]) end; io.write("\n")
check = check + 1
end
-- Copy and flip.
local q1 = p[1] -- Cache 1st element.
if p[n] ~= n and q1 ~= 1 then -- Avoid useless work.
for i=2,n do q[i] = p[i] end -- Work on a copy.
for flips=1,1000000 do -- Flip ...
local j = q1 - 1
for i=2,q1/2 do q[i], q[j] = q[j], q[i]; j = j - 1 end
local qq = q[q1]
if qq == 1 then -- ... until 1st element is 1.
if flips > maxflips then maxflips = flips end -- New maximum?
break
end
q[q1] = q1
q1 = qq
end
end
-- Permute.
if odd then
p[2], p[1] = p[1], p[2]; odd = false -- Rotate 1<-2.
else
p[2], p[3] = p[3], p[2]; odd = true -- Rotate 1<-2 and 1<-2<-3.
for i=3,n do
local sx = s[i]
if sx ~= 1 then sx = sx - 1; s[i] = sx; break end
if i == n then return maxflips end -- Out of permutations.
s[i] = i
-- Rotate 1<-...<-i+1.
local t = p[1]; for j=1,i do p[j] = p[j+1] end; p[i+1] = t
end
end
until false
end
local n = tonumber(arg and arg[1]) or 1
io.write("Pfannkuchen(", n, ") = ", fannkuch(n), "\n")
|
class "Player"
function Player:__init(player)
self.player = player
self.playerId = player:GetId()
self.start_pos = player:GetPosition()
self.start_world = player:GetWorld()
self.inventory = player:GetInventory()
self.derbyPosition = nil
self.derbyAngle = nil
self.derbyVehicle = nil
self.hijackCount = 0
end
function Player:Leave()
self.player:SetWorld(self.start_world)
self.player:SetNetworkValue( "GameMode", "FREEROAM" )
self.player:SetPosition(self.start_pos)
self.player:ClearInventory()
for k,v in pairs(self.inventory) do
self.player:GiveWeapon(k, v)
end
end |
--[[exports.scoreboard:addScoreboardColumn('Flag', getRootElement(), 25)
function showcountry()
local flag = exports.admin:getPlayerCountry ( source )
if flag then
setElementData(source,"Flag",":admin/client/images/flags/"..flag..".png")
else
flag = "N/A"
end
end
addEventHandler("onPlayerJoin",getRootElement(),showcountry)
function updateFlags()
for theKey,thePlayer in ipairs(getElementsByType("player")) do
local flag = exports.admin:getPlayerCountry ( thePlayer )
if flag then
setElementData(thePlayer,"Flag",":admin/client/images/flags/"..flag..".png")
else
flag = "N/A"
end
end
end
setTimer(updateFlags, 1000, 1)]]--
|
local kiir = {}
kiir.kiik = {}
kiir.alap = {}
kiir.aktiv = 0
-- létrehozás, törlés | new, del
function kiir:new(szoveg,ido) -- string, time
if not szoveg then return nil end
ido = ido or kiir.alap.ido
table.insert(kiir.kiik,{szoveg=szoveg,ido=ido})
return #kiir
end
function kiir:del()
kiir.kiik={}
end
-- frissítés, kiírás | update, draw
function kiir:update(dt)
kiir.aktiv=0
for id,kii in ipairs(kiir.kiik) do
if kii.ido>0 then
kii.ido = kii.ido-dt
kiir.aktiv=kiir.aktiv+1
end
if kii.ido<0 then
kii.ido = 0
kiir.aktiv=kiir.aktiv-1
end
end
end
function kiir:draw(x,y,felvagyle,osszes,helyköz) -- x,y,upordown,all,linespace
x = x or kiir.alap.x
y = y or kiir.alap.y
helyköz = helyköz or love.graphics.getFont():getHeight()
local pos
if osszes then
pos = #kiir.kiik
else
pos = kiir.aktiv
end
for id,kii in ipairs(kiir.kiik) do
if osszes or kii.ido>0 then
if felvagyle
then
love.graphics.print(kii.szoveg,x,y-(pos*helyköz))
else
love.graphics.print(kii.szoveg,x,y+(pos*helyköz))
end
pos=pos-1
end
end
end
-- beállítás | setting
function kiir:set(x,y,ido,felvagyle,osszes,helyköz)
kiir.alap.x = x or 0
kiir.alap.y = y or 0
kiir.alap.ido = ido or 5 -- time (sec)
kiir.alap.felvagyle = felvagyle or false -- up or down (false=down)
kiir.alap.osszes = osszes or false -- all (false= only the actives)
kiir.alap.helyköz = helyköz or nil -- line space (pixel) (nil = get currently size)
end
kiir:set() -- alap beállítások
return kiir |
local kAlienStructureMoveSound = debug.getupvaluex(UpdateAlienStructureMove, "kAlienStructureMoveSound")
function UpdateAlienStructureMove(self, deltaTime)
if Server then
local currentOrder = self:GetCurrentOrder()
if GetIsUnitActive(self) and currentOrder and currentOrder:GetType() == kTechId.Move and (not HasMixin(self, "TeleportAble") or not self:GetIsTeleporting()) then
local speed = self:GetMaxSpeed()
if self.shiftBoost then
speed = speed * kShiftStructurespeedScalar
end
if not self:GetIsInCombat() then
speed = speed * kAlienStructureOutOfCombatMoveScalar
end
self:MoveToTarget(PhysicsMask.AIMovement, currentOrder:GetLocation(), speed, deltaTime)
if not self.distanceMoved then
self.distanceMoved = 0
end
self.distanceMoved = self.distanceMoved + speed * deltaTime
if self.distanceMoved > 1 then
if HasMixin(self, "StaticTarget") then
self:StaticTargetMoved()
end
self.distanceMoved = 0
end
if self:IsTargetReached(currentOrder:GetLocation(), kAIMoveOrderCompleteDistance) then
self:CompletedCurrentOrder()
self.moving = false
self.distanceMoved = 0
else
self.moving = true
end
else
self.moving = false
self.distanceMoved = 0
end
if HasMixin(self, "Obstacle") then
if currentOrder and currentOrder:GetType() == kTechId.Move then
self:RemoveFromMesh()
if not self.removedMesh then
self.removedMesh = true
self:OnObstacleChanged()
end
elseif self.removedMesh then
self:AddToMesh()
self.removedMesh = false
end
end
elseif Client then
if self.clientMoving ~= self.moving then
if self.moving then
Shared.PlaySound(self, kAlienStructureMoveSound, 1)
else
Shared.StopSound(self, kAlienStructureMoveSound)
end
self.clientMoving = self.moving
end
if self.moving and (not self.timeLastDecalCreated or self.timeLastDecalCreated + 1.1 < Shared.GetTime() ) then
self:TriggerEffects("structure_move")
self.timeLastDecalCreated = Shared.GetTime()
end
end
end |
--[[ SERVER TO REQUEST HANDLER ]]
require "dns"
--[[ RUNNING SERVER ]]
local sockgate
local scmd --scmd = string command
sockgate = lsok.open(lsok.proto.udp)
local bool = lsok.bind(sockgate, conf.dnsIP, conf.dnsPort)
if(bool == false) then
error("Could not bind")
end
while(true) do
local si
local sf
local cmd --command
local service
local ip
local port
local bytes
local recvIP
local recvPORT
--receive the request from a new conection
scmd, recvIP, recvPORT = lsok.recv(sockgate, lsok.proto.udp)
print("command recreived: "..scmd)
--process the request
si = string.find(scmd, "%(")
cmd = string.lower(string.sub(scmd, 1, si-1))
if(cmd == "add") then
local asnwere
sf = string.find(scmd, ",")
service = string.lower(string.sub(scmd, si+1, sf-1))
si = string.find(scmd, ",", sf+1)
ip =string.sub(scmd, sf+1, si-1)
sf = string.find(scmd, ")", si+1)
port = tonumber(string.sub(scmd, si+1, sf-1))
conf.print("processed as: (service, ip, port) ".."-> ("..service..","..ip..","..port..")")
--call the corrent function
asnwere = dns.add(service, ip, port)
--send back the correct asnwere
bytes = lsok.send(sockgate, asnwere, recvIP, recvPORT)
elseif(cmd == "search") then
sf = string.find(scmd, ")")
service = string.lower(string.sub(scmd, si+1, sf-1))
conf.print("processed as: (service)", "("..service..")")
--call the corrent function
ip, port = dns.search(service)
if(ip == nil or port == nil) then
cmd = conf.notFound --reusing variable
else
cmd = "("..ip..","..tostring(port)..")" --reusing variable
end
--send back the correct asnwere
bytes = lsok.send(sockgate, cmd, recvIP, recvPORT)
end
end
--close the current conection
lsok.close(sockgate)
sockgate = nil
|
if (GetLocale() ~= "deDE") then return end
-- Localization for deDE
local PerformanceSlight = "\n|cffFF0000Eine Deaktivierung könnte die Spielperformance leicht erhöhen|r" -- For semi-high CPU options
local ToggleOffReminder = "\n|cffFF0000Schalte diesen Menüpunt aus, um Deine Aktionsleisten manuell zu steuern|r"
-- Actionbar
UIConfigLocal.ActionBarBottomBars = "Anzahl der Leisten am unteren Rand (1, 2 oder 3)"
UIConfigLocal.ActionBarButtonSize = "Buttongröße"
UIConfigLocal.ActionBarButtonSpace = "Buttonabstand"
UIConfigLocal.ActionBarEnable = "Aktivere Aktionsleisten"
UIConfigLocal.ActionBarEquipBorder = "Zeige einen grünen Rand um angelegte Items"
UIConfigLocal.ActionBarGrid = "Zeige leere Aktionleistenplätze an"
UIConfigLocal.ActionBarHideHighlight = "Verstecke Proc Anzeigen"
UIConfigLocal.ActionBarHotkey = "Zeige Hotkey auf den Buttons"
UIConfigLocal.ActionBarMacro = "Zeige Makronamen auf den Buttons"
UIConfigLocal.ActionBarOutOfMana = "Farbe wenn Mana leer"
UIConfigLocal.ActionBarOutOfRange = "Farbe wenn ausser Reichweite"
UIConfigLocal.ActionBarPetBarHide = "Verstecke die Begleiterleiste"
UIConfigLocal.ActionBarPetBarHorizontal = "Aktiviere horizontale Begleiterleiste"
UIConfigLocal.ActionBarPetBarMouseover = "Begleiterleiste bei mouseover (nur für horizontale Begleiterleiste)"
UIConfigLocal.ActionBarRightBars = "Anzahl der Aktionsleisten rechts (0, 1, 2 oder 3)"
UIConfigLocal.ActionBarRightBarsMouseover = "Rechte Leisten bei mouseover"
UIConfigLocal.ActionBarSelfCast = "Immer Selbstzauber bei rechtsklick (ungeachtet des momentanten Ziels)"
UIConfigLocal.ActionBarSplitBars = "Teile die fünfte Aktionsleiste auf zwei Leisten mit 6 Buttons auf"
UIConfigLocal.ActionBarStanceBarHide = "Verstecke die Haltungsleiste"
UIConfigLocal.ActionBarStanceBarHorizontal = "Aktiviere horizontale Haltungsleiste"
UIConfigLocal.ActionBarStanceBarMouseover = "Haltungsleiste bei mouseover"
UIConfigLocal.ActionBarToggleMode = "Aktivere Umschaltmode"..ToggleOffReminder
-- Ankündigungen
UIConfigLocal.Announcements = "Ankündigungen"
UIConfigLocal.AnnouncementsBadGear = "Überprüfe kaputte Ausrüstung in Instanzen"
UIConfigLocal.AnnouncementsInterrupt = "Ankündigungen im Gruppen-/Schlachtzugchat wenn Du jemanden unterbrochen hast."
UIConfigLocal.AnnouncementsPullCountdown = "Simples Script um einen Pulltimer zu starten. Tippe /pc in den Chat."
UIConfigLocal.AnnouncementsSaySapped = "Kopfnussansage wenn die ein |cFFFFF569Schurke|r aus dem Kampf genommen hat."
UIConfigLocal.AnnouncementsSayThanks = "Bedanke dich für einige Zauber"
UIConfigLocal.AnnouncementsSpells = "Ankündigungen im Gruppen-/Schlachtzugchat wenn Du bestimmte Zauber benutzt hast."
UIConfigLocal.AnnouncementsSpellsFromAll = "Überprüfe Zauber von allen Mitspielern."
-- Automatisierung
UIConfigLocal.Automation = "Automatisierung"
UIConfigLocal.AutomationAcceptQuest = "Quests automatisch annehmen"
UIConfigLocal.AutomationAutoCollapse = "Automatisches Einklappen der Questanzeige in Instanzen"
UIConfigLocal.AutomationAutoInvite = "Automatisches Akzeptieren von Einladungen (NUR Freunde/Gildenmitglieder)"
UIConfigLocal.AutomationDeclineDuel = "Automatische Ablehnung von Duellen"
UIConfigLocal.AutomationLoggingCombat = "Automatisches Aktivieren der Kampflogdatei in Schlachtzuginstanzen"
UIConfigLocal.AutomationResurrection = "Automatisches Wiederbeleben auf Schlachtfeldern"
UIConfigLocal.AutomationScreenShot = "Automatisches Bildschirmfoto bei erreichen eines Erfolges"
UIConfigLocal.AutomationTabBinder = "Automatischer Wechsel der Tab-Taste um nur feindliche Ziele anzuvisieren"
-- Taschen
UIConfigLocal.Bags = "Taschen"
UIConfigLocal.BagsButtonSize = "Größe der Taschenplätze"
UIConfigLocal.BagsEnable = "Aktiviere die 'Alles in einer Tasche' Ansicht"
UIConfigLocal.BagsInsertLeftToRight = "Set the loot to the left most bag first"
UIConfigLocal.BagsItemsPerRow = "aschenplatzanzahl pro Reihe"
UIConfigLocal.BagsSortRightToLeft = "Sort bags right to left, bottom to top"
UIConfigLocal.BagsSpacing = "Zwischenraum zwischen den Taschenslots"
-- Blizzard
UIConfigLocal.Blizzard = "Blizzard"
UIConfigLocal.BlizzardClassColor = "Zeige Spielernamen in deren Klassenfarbe an. (Freundesliste, Wer Liste, Gildenliste, etc.)"
UIConfigLocal.BlizzardColorTextures = "Passe von den meisten UI Texturen den Farbton an."
UIConfigLocal.BlizzardHideTalkingHead = "Verstecke das Questdialogfenster"
UIConfigLocal.BlizzardRaidTools = "Raid Hilfsmittel"
UIConfigLocal.BlizzardReplaceBlizzardFonts = "Ersetze die Standard |cff00B4FFBlizzard Schriftarten|r auf vielen UI Elementen der |cff3c9bedKkthnxUI|r."
UIConfigLocal.BlizzardReputationGain = "Zeige eine Nachricht, wenn Du Rufpunkte gesammelt hast"
UIConfigLocal.BlizzardTalkingHeadScale = "Scale the Talking Head Frame"
UIConfigLocal.BlizzardTexturesColor = "UI Texturfarbton. (Standard ist Klassenfarbe)"
UIConfigLocal.BlizzardVehicleMouseover = "Farhzeuganzeige bei 'mouseover'"
-- Datenleisten
UIConfigLocal.DataBars = "Datenleisten"
UIConfigLocal.DataBarsArtifactColor = "Farbe der Artefaktleiste"
UIConfigLocal.DataBarsArtifactEnable = "Aktiviere die Artefaktleiste"
UIConfigLocal.DataBarsArtifactFade = "Verblassen der Artefaktleiste"
UIConfigLocal.DataBarsArtifactHeight = "Höhe der Artefaktleiste"
UIConfigLocal.DataBarsArtifactWidth = "Breite der Artefaktleiste"
UIConfigLocal.DataBarsExperienceColor = "Farbe der Erfahrungsleiste"
UIConfigLocal.DataBarsExperienceEnable = "Aktiviere die Erfahrungsleiste"
UIConfigLocal.DataBarsExperienceFade = "Fade Experience bar"
UIConfigLocal.DataBarsExperienceHeight = "Höhe der Erfahrungsleiste"
UIConfigLocal.DataBarsExperienceRestedColor = "Farbe der Erfahrungsleiste (Erholung)"
UIConfigLocal.DataBarsExperienceWidth = "Breite der Erfahrungsleiste"
UIConfigLocal.DataBarsHonorColor = "Farbe der Ehreleiste"
UIConfigLocal.DataBarsHonorEnable = "Aktiviere die Ehreleiste"
UIConfigLocal.DataBarsHonorFade = "Verblassen der Ehreleiste"
UIConfigLocal.DataBarsHonorHeight = "Höhe der Ehreleiste"
UIConfigLocal.DataBarsHonorWidth = "Breite der Ehreleiste"
UIConfigLocal.DataBarsInfoText = "Display info text on all databars"
UIConfigLocal.DataBarsReputationEnable = "Aktiviere die Rufleiste"
UIConfigLocal.DataBarsReputationFade = "Verblassen der Rufleiste"
UIConfigLocal.DataBarsReputationHeight = "Höhe der Rufleiste"
UIConfigLocal.DataBarsReputationWidth = "Breite der Rufleiste"
-- Auren
UIConfigLocal.Auras = "Auren"
UIConfigLocal.AurasAnimation = "Zeige eine 'pop in' Animation der Auren"..PerformanceSlight
UIConfigLocal.AurasBuffsPerRow = "Anzahl der Stärkungszauber bevor eine neue Zeile angefangen wird"
UIConfigLocal.AurasCastBy = "Zeige von wem eine Aura stammt im Tooltip an"
UIConfigLocal.AurasConsolidate = "Auren einklappen"
UIConfigLocal.AurasEnable = "Aktivere Auren"
UIConfigLocal.AurasFlash = "Aufblitzen der Auren, wenn die Zeit fast abgelaufen ist"..PerformanceSlight
UIConfigLocal.AurasHideBuffs = "Deaktivere die Stärkungszauberanzeige"
UIConfigLocal.AurasHideDebuffs = "Deaktivere die Schwächungszauberanzeige"
-- Chat
UIConfigLocal.ChatBubbleBackdrop = "Entferne den Hintergrund der Sprachblasen."
UIConfigLocal.ChatDamageMeterSpam = "Zeige den 'damage meter spam' zusammengefasst in einem 'line-link' an"
UIConfigLocal.ChatEnable = "Aktiviere Chat"
UIConfigLocal.ChatFading = "Fades out chat messages after a certain period of time."
UIConfigLocal.ChatFadingTimeVisible = "Set how long in seconds the chat messages remain visible before fading out."
UIConfigLocal.ChatFadingTimeFading = "Set how much time the chat messages will spend fading out in seconds."
UIConfigLocal.ChatHeight = "Höhe des Chatfensters"
UIConfigLocal.ChatLinkBrackets = "Zeige URL Links in Klammern"
UIConfigLocal.ChatLinkColor = "Farbe der Links im Chat"
UIConfigLocal.ChatMessageFilter = "Removing some systems spam('Player1' won duel 'Player2')"
UIConfigLocal.ChatOutline = "Verwende einen Umriss um die Schriftart im Chat"
UIConfigLocal.ChatScrollByX = "Setze die Anzahl der Zeile die im Chat gesprungen werden beim scrollen"
UIConfigLocal.ChatSpamFilter = "Removing some players chat spam in trade"
UIConfigLocal.ChatTabsMouseover = "Chattabs bei 'mouseover'"
UIConfigLocal.ChatTabsOutline = "Verwende einen Umriss um die Schritart der Chattabs"
UIConfigLocal.ChatWhispSound = "Spiele einen Sound ab, wenn du eine Flüsternachricht bekommst"
UIConfigLocal.ChatWidth = "Breite des Chatfensters"
-- Datatexte
UIConfigLocal.DataText = "Datatexte"
UIConfigLocal.DataTextBattleground = "Aktiviere die Datatextanzeige auf Schlachtfeldern"
UIConfigLocal.DataTextLocalTime = "Benutze die lokale Zeit bei der Zeitanzeige auf der Minimap, anstatt der Serverzeit"
UIConfigLocal.DataTextSystem = "Aktivere den Datatext unter der Minimap, der Dir Deine FPS & MS anzeigt"
UIConfigLocal.DataTextTime = "Aktiviere den Datatext auf der Minimap, der Dir die Uhrzeit anzeigt"
UIConfigLocal.DataTextTime24Hr = "Stelle die Zeitanzeige in der Minimap auf das 24 Stunden Format um"
-- Fehler
UIConfigLocal.Error = "Fehler"
UIConfigLocal.ErrorBlack = "Verstecke Fehler der Schwarzen Liste"
UIConfigLocal.ErrorWhite = "Zeige Fehler der Weißen Liste"
UIConfigLocal.ErrorCombat = "Verberge alle Fehlermeldungen im Kampf"
-- Abklingzeiten
UIConfigLocal.Cooldown = "Abklingzeiten"
UIConfigLocal.CooldownEnable = "Aktivere das UI Modul für die Abklingzeiten"
UIConfigLocal.CooldownFontSize = "chriftgröße der Abklingzeiten"
UIConfigLocal.CooldownThreshold = "Abklingzeiten Schwellenwert"
-- Filger
UIConfigLocal.Filger = "Zeiten (Filger)"
UIConfigLocal.FilgerBuffsSize = "Größe der Stärkungszauber"
UIConfigLocal.FilgerCooldownSize = "Größe Abklingzeiten"
UIConfigLocal.FilgerDisableCD = "Deaktivere Abklingzeiten"
UIConfigLocal.FilgerEnable = "Aktiviere Filger"
UIConfigLocal.FilgerMaxTestIcon = "Anzahl der Symbole beim Testen"
UIConfigLocal.FilgerPvPSize = "Größe der PvP Schwächungszauber"
UIConfigLocal.FilgerShowTooltip = "Zeige Tooltip"
UIConfigLocal.FilgerTestMode = "Testmodus der Symbole"
-- General
UIConfigLocal.GeneralAutoScale = "AAutomatische UI Skalierung"
UIConfigLocal.GeneralBubbleFontSize = "Schriftgröße in den Sprachblasen"
UIConfigLocal.GeneralCustomLagTolerance = "Automatisches Update der 'Blizzard Custom Lag Tolerance' Option zu Deiner Latenz"
UIConfigLocal.GeneralDisableTutorialButtons = "Disables the tutorial button found on some frames"
UIConfigLocal.GeneralTaintLog = "Log Fehler"
UIConfigLocal.GeneralToggleButton = "Toggle button under minimap (if DataText System is enabled)"
UIConfigLocal.GeneralTranslateMessage = "Popup anzeigen für Hilfe bei der UI Übersetzung."
UIConfigLocal.GeneralUIScale = "UI Skalierung (Wenn automatische Skalierung deaktivert ist)"
UIConfigLocal.GeneralUseBlizzardFonts = "Use the default blizzard font"
UIConfigLocal.GeneralUseFlatTextures = "Use flat statusbar textures"
UIConfigLocal.GeneralWelcomeMessage = "Willkommensnachricht im Chat anzeigen."
-- Loot
UIConfigLocal.LootAutoGreed = "Aktiviere automatisch auf Gier & Entzaubern würfeln bei grünen Gegenständen auf Max Level"
UIConfigLocal.LootConfirmDisenchant = "Auto confirm disenchant"
UIConfigLocal.LootEnable = "ktiviere das Beutefenster"
UIConfigLocal.LootGroupLoot = "Aktivere das Fenster für die Beute der Gruppen"
UIConfigLocal.LootIconSize = "Symbolgröße"
UIConfigLocal.LootLootFilter = "Filter die Gruppen- & Schlachtzugmitglieder Nachrichten, basierend auf den Gegenstandsqualität"
UIConfigLocal.LootWidth = "Größe des Beutefensters"
-- Minimap
UIConfigLocal.Minimap = "Minimap"
UIConfigLocal.MinimapCalendar = "Calendar icon is shown on minimap"
UIConfigLocal.MinimapCollectButtons = "Sammel die Minimapbuttons und zeige sie in einer Leiste an"
UIConfigLocal.MinimapEnable = "Aktiviere die Minimap & zeige sie viereckig"
UIConfigLocal.MinimapFadeButtons = "Fade addon button when collected next to minimap"
UIConfigLocal.MinimapGarrison = "Zeige das Garnisonssymbol an der Minimap"
UIConfigLocal.MinimapPing = "Zeige eine Nachricht, wenn jemand auf der Minimap 'pingt'. |cffff0000*|r |ccfabd473Kkthnx|r |cffff0000*|r"
UIConfigLocal.MinimapSize = "Größe der Minimap - Standard ist 150"
-- Sonstiges
UIConfigLocal.Misc = "Sonstiges"
UIConfigLocal.MiscAFKCamera = "Drehe die Kamera während Du AFK bist"
UIConfigLocal.MiscAlreadyKnown = "Färbe Rezepte, Reittiere & Haustiere die Du bereits kennst"
UIConfigLocal.MiscArmory = "Zeige einen Link zur Armory an, wenn Du die Einstellungen eines Einheitenfensters aufrufst"
UIConfigLocal.MiscAutoRepair = "Repariere automatisch Deine Ausrüstung beim Händler"
UIConfigLocal.MiscAutoSellGrays = "Verkaufe automatisch graue Gegenstände beim Händler"
UIConfigLocal.MiscBGSpam = "Lösche 'Boss Emote spam' während du auf dem Schlachtfeld bist"
UIConfigLocal.MiscColorPicker = "Verbesserte Farbauswahl"
UIConfigLocal.MiscCombatState = "Display a message when you enter/leave combat at the top of the screen"
UIConfigLocal.MiscEnhancedMail = "Fügt einen 'Öffne Alles' Button deinem Briefkasten hinzu."
UIConfigLocal.MiscEnhancedPvpMessages = "Zeigt Schlachtfeld Nachrichten in der Mitte des Bildschirms."
UIConfigLocal.MiscInviteKeyword = "Schlüsselwort zum einladen (/ainv)"
UIConfigLocal.MiscItemLevel = "Zeige den Itemlevel auf Deinen Gegenständen in der Charakterübersicht an"
UIConfigLocal.MiscMerchantItemLevel = "Zeige Itemlevel für Waffen & Rüstung bei Händler"
UIConfigLocal.MiscMoveBlizzard = "Verschiebe einige Blizzard Fenster"
UIConfigLocal.MiscNoBanner = "Autoverstecken des Boss Loot Frame"
UIConfigLocal.MiscPvPEmote = "Does a random emote on a player that you get a killing blow on"
UIConfigLocal.MiscSellMisc = "Automatisches Verkaufen von unnützen Gegenständen die nicht grauer Qualität sind"
UIConfigLocal.MiscSlotDurability = "Zeige die Haltbarkeit auf Deinen Gegenständen in der Charakterübersicht an"
UIConfigLocal.MiscUseGuildRepair = "Bei Benutzung von 'Automatisches Reparieren', benutzte die Gildenbank"
-- Namensplaketten
UIConfigLocal.Nameplates = "Namensplaketten"
UIConfigLocal.NameplatesAdditionalHeight = "Zusätzliche Höhe für die ausgewählte Namenplakette"
UIConfigLocal.NameplatesAdditionalWidth = "Zusätzliche Breite für die ausgewählte Namenplakette"
UIConfigLocal.NameplatesAurasSize = "Größe der Schwächungszauber"
UIConfigLocal.NameplatesBadColor = "Farbe wenn die Bedrohung NICHT ok ist, variert je nach Rolle die Du spielst ->dps/heal"
UIConfigLocal.NameplatesCastbarName = "Zeige namen des Zaubers"
UIConfigLocal.NameplatesCastUnitReaction = "Color castbars by the reaction type of non-player units"
UIConfigLocal.NameplatesClamp = "Setze die Namensplaketten an den oberen Bildschrimrand fest, wenn die ausser Sicht wären"
UIConfigLocal.NameplatesClassIcons = "Symbole nach Klasse im PvP"
UIConfigLocal.NameplatesCombat = "Automatisches Anzeigen der Namensplaketten im Kampf"
UIConfigLocal.NameplatesDistance = "Zeige Namensplaketten für Einheiten im Sichtbereich"
UIConfigLocal.NameplatesEnable = "Aktiviere die Namensplaketten"
UIConfigLocal.NameplatesEnhancedThreat = "Aktiviere das Bedrohungsfeature. Wechselt automatisch je nach Deiner Rolle"
UIConfigLocal.NameplatesGoodColor = "Farbe wenn die Bedrohung ok ist, variert je nach Rolle die Du spielst ->dps/heal"
UIConfigLocal.NameplatesHealerIcon = "Zeige Symbole über den Namensplaketten an, wenn der Spieler ein Heiler ist"
UIConfigLocal.NameplatesHealthValue = "Zeige die Lebenswerte auf den Plaketten an"
UIConfigLocal.NameplatesHeight = "Höhe der Namensplaketten"
UIConfigLocal.NameplatesNameAbbreviate = "Kürze den Namen wenn er länger als 18 Zeichen ist"
UIConfigLocal.NameplatesNearColor = "Verliere/Gewinne Bedrohungsfarbe"
UIConfigLocal.NameplatesOffTankColor = "Offtank threat color"
UIConfigLocal.NameplatesSmooth = "Bars will transition smoothly"
UIConfigLocal.NameplatesTotemIcons = "Show icon above enemy totems nameplate" -- Needs Translation
UIConfigLocal.NameplatesTrackAuras = "Zeige Schwächungszauber"
UIConfigLocal.NameplatesWidth = "Breite der Namensplaketten"
-- Pulsieren
UIConfigLocal.PulseCD = "Pulsieren"
UIConfigLocal.PulseCDAnimationScale = "Animationsskalierung"
UIConfigLocal.PulseCDEnable = "Zeige pulsierende Abklingzeiten"
UIConfigLocal.PulseCDHoldTime = "Maximal anhaltende Effektdauer"
UIConfigLocal.PulseCDSize = "Symbolgröße der pulsierende Abklingzeiten"
UIConfigLocal.PulseCDSound = "Soundwarnung"
UIConfigLocal.PulseCDThreshold = "Minimaler Schwellwert"
-- RaidCD
UIConfigLocal.RaidCD = "Schlachtzugs Cooldowns"
UIConfigLocal.RaidCDEnable = "Abklingzeiten des Raids aktivieren"
UIConfigLocal.RaidCDExpiration = "Sortieren nach Abklingzeit"
UIConfigLocal.RaidCDHeight = "Leistenhöhe für Raidabklingzeiten"
UIConfigLocal.RaidCDShowIcon = "Symbole für Raidabklingzeiten"
UIConfigLocal.RaidCDShowInArena = "Zeige Raidabklingzeiten in der Arena"
UIConfigLocal.RaidCDShowInParty = "Zeige Raidabklingzeiten in Gruppengebieten"
UIConfigLocal.RaidCDShowInRaid = "Zeige Raidabklingzeiten in Raidgebieten"
UIConfigLocal.RaidCDShowSelf = "Zeige deine Cooldowns"
UIConfigLocal.RaidCDUpWards = "Leisten für Raidabklingzeiten wachsen nach oben"
UIConfigLocal.RaidCDWidth = "Leistenbreite der Raidabklingzeiten(Wenn das Symbol aktiviert ist, Breite+28)"
-- Config GUI Buttons
UIConfigLocal.ConfigApplyButton = "Apply"
UIConfigLocal.ConfigButtonReset = "UI zurücksetzen"
UIConfigLocal.ConfigCloseButton = "Close"
-- Config Static Popups
UIConfigLocal.ConfigPerChar = "Bist Du sicher, dass Du auf 'Einstellungen für jeden Charakter einzeln' wechseln willst?"
UIConfigLocal.ConfigResetAll = "Bist Du sicher, dass Du alle Einstellungen für das |cff3c9bedKkthnxUI|r zurücksetzen willst?"
UIConfigLocal.ConfigResetChar = "Bist Du sicher, dass Du die Einstellungen für jeden Deiner Charaktere zurücksetzen willst|r?"
UIConfigLocal.ConfigSetSavedSettings = "Setze Einstellungen für jeden Charakter einzeln"
-- Skins
UIConfigLocal.Skins = "AddOn Skins" -- Needs Translation
UIConfigLocal.SkinsBigWigs = "BigWigs" -- Needs Translation
UIConfigLocal.SkinsChatBubble = "Blizzard Sprachblasen"
UIConfigLocal.SkinsDBM = "DeadlyBossMods" -- Needs Translation
UIConfigLocal.SkinsDBMMove = "Erlaube das Bewegen der DBM Leisten"
UIConfigLocal.SkinsMinimapButtons = "Minimap buttons" -- Needs Translation
UIConfigLocal.SkinsRecount = "Recount" -- Needs Translation
UIConfigLocal.SkinsSkada = "Skada" -- Needs Translation
UIConfigLocal.SkinsSpy = "Spy" -- Needs Translation
UIConfigLocal.SkinsWeakAuras = "WeakAuras" -- Needs Translation
-- Tooltip
UIConfigLocal.Tooltip = "Tooltip" -- Needs Translation
UIConfigLocal.TooltipAchievements = "Vergleiche Erfolge per Tooltip"
UIConfigLocal.TooltipCursor = "Tooltip über dem Cursor"
UIConfigLocal.TooltipEnable = "Aktiviere Tooltip"
UIConfigLocal.TooltipHealthValue = "Lebensanzeige über dem Tooltip"
UIConfigLocal.TooltipHyperLink = "Zeige den Hyperlinktooltip während du it der Maus über einen Hyperlink gehst."
UIConfigLocal.TooltipInstanceLock = "Deine Instantensperrungen im Tooltip anzeigen"
UIConfigLocal.TooltipItemCount = "Gegenstandsmenge anzeigen"
UIConfigLocal.TooltipItemIcon = "Item icon in tooltip"
UIConfigLocal.TooltipRank = "Display targets guild rank on tooltip when shift is held down"
UIConfigLocal.TooltipSpellID = "Zauber-ID anzeigen"
UIConfigLocal.TooltipTalents = "Zeigt die Spieler Spezialisierung und die Gegenstandstufe im Tooltip an"
-- Einheitenfenster
UIConfigLocal.Unitframe = "Einheitenfenster"
UIConfigLocal.UnitframeCastbarHeight = "Height of the unitframe castbars"
UIConfigLocal.UnitframeCastbarIcon = "Show castbar icons"
UIConfigLocal.UnitframeCastbarLatency = "Show Castbar latency when casting (Player only)"
UIConfigLocal.UnitframeCastbars = "Aktiviere die Zauberleiste"
UIConfigLocal.UnitframeCastbarTicks = "Display tick marks on the castbar for channelled spells."
UIConfigLocal.UnitframeCastbarWidth = "Width of the unitframe castbars"
UIConfigLocal.UnitframeCastClassColor = "Color castbars by the class of player units"
UIConfigLocal.UnitframeCastUnitReaction = "Color castbars by the reaction type of non-player units"
UIConfigLocal.UnitframeClassColor = "Lebensleisten in Klassenfarbe anzeigen."
UIConfigLocal.UnitframeClassPortraits = "Aktiviere alten Klassenportraits"
UIConfigLocal.UnitframeCombatText = "Zeige KampfFeedback auf den Einheitenfenstern an"
UIConfigLocal.UnitframeEnable = "Aktiviere die Einheitenfenster"
UIConfigLocal.UnitframeGCDBar = "Blitz für globalen Cooldown"
UIConfigLocal.UnitframeParty = "Aktiviere die Gruppenfenster."
UIConfigLocal.UnitframePlayerDebuffsOnly = "Färbe nur Spieler Schwächungszauber"
UIConfigLocal.UnitframePortraitTimer = "Zeige Portrait Zeiten"
UIConfigLocal.UnitframePowerPredictionBar = "Power prediction bar (Zeigt die wahrscheinlichen Kosten des Zaubers in der Leiste an)"
UIConfigLocal.UnitframeScale = "Skalierung einiger Einheitenfenster."
UIConfigLocal.UnitframeShowArena = "Aktiviere die Arenafenster"
UIConfigLocal.UnitframeShowBoss = "Aktiviere die Bossfenster"
UIConfigLocal.UnitframeShowPlayer = "Zeige dich selbst in der Gruppe an"
UIConfigLocal.UnitframeSmooth = "Bars will transition smoothly"
UIConfigLocal.UnitframeStyle = "Style den Look der Einheitenfenster 'fat oder normal'"
UIConfigLocal.UnitframeSwingBar = "Swingleiste"
UIConfigLocal.UnitframeThreatGlow = "Aktiviere das Bedrohungsleuchten um die Einheitenfenster"
UIConfigLocal.UnitframeThreatValue = "Visueller Bedrohungstext auf dem Spielerfenster"
-- Schlachtzug
UIConfigLocal.Raidframe = "Raid Frames" -- Needs Translation
UIConfigLocal.RaidframeAuraWatch = "Zeige die Timer für Klassenspezifische Buffs in den Ecken des Schlachtzugsfenster an"
UIConfigLocal.RaidframeDeficitThreshold = "Heilung Schwellenwert"
UIConfigLocal.RaidframeEnable = "Aktiviere Schlachtzugsfenster"
UIConfigLocal.RaidframeHeight = "Höhe der Schlachtzugsfenster"
UIConfigLocal.RaidframeHorizontalHealthBars = "Zeige die Lebensbalken horizontal an"
UIConfigLocal.RaidframeIconSize = "Größe der Schwächungszaubersymbole auf den Schlachtzugsfenstern."
UIConfigLocal.RaidframeMainTankFrames = "Aktiviere die Anzeige von Haupttank/assist Fenstern im Schlachtzug."
UIConfigLocal.RaidframeManabarHorizontal = "Zeige die Manaleiste horizontal an"
UIConfigLocal.RaidframeManabarShow = "Zeige die Manaleiste"
UIConfigLocal.RaidframeMaxUnitPerColumn = "Wieviele Einheitenfenster pro Schlachtzugsreihe"
UIConfigLocal.RaidframeRaidAsParty = "Zeige die Schlachtzugsfenster, anstatt der Gruppenfenster."
UIConfigLocal.RaidframeScale = "Skalierung der Schlachtzugsfenster"
UIConfigLocal.RaidframeShowMouseoverHighlight = "SHebe die Einheitenfenster per 'mouseover' hevor"
UIConfigLocal.RaidframeShowNotHereTimer = "Zeige AFK/Offline Zeit an"
UIConfigLocal.RaidframeShowResurrectText = "DZeige Wiederbelebungstext an"
UIConfigLocal.RaidframeShowRolePrefix = "Zeige Rollenpräfixe '> + -'"
UIConfigLocal.RaidframeShowThreatText = "Zeige Bedrohungstext 'AGGRO'"
UIConfigLocal.RaidframeSmooth = "Bars will transition smoothly."
UIConfigLocal.RaidframeWidth = "Breite der Schlachtzugsfenster"
-- Weltkarte
UIConfigLocal.WorldMap = "Weltkarte"
UIConfigLocal.WorldMapAlphaWhenMoving = "Alphawert der Weltkarte wenn Du Dich bewegst."
UIConfigLocal.WorldMapCoordinates = "Zeige Koordinaten auf der Weltkarte an."
UIConfigLocal.WorldMapFadeWhenMoving = "Verblassen der Weltkarte wenn Du Dich bewegst."
UIConfigLocal.WorldMapFogOfWar = "Entferne den Nebel des Krieges auf der Weltkarte."
UIConfigLocal.WorldMapSmallWorldMap = "Kleine Weltkarte anzeigen." |
IncludeFile("Lib\\TOIR_SDK.lua")
Olaf = class()
function OnLoad()
if GetChampName(GetMyChamp()) == "Olaf" then
Olaf:__init()
end
end
function Olaf:__init()
W_SPELLS = { -- Yea boiz and grillz its all right here.......
["FizzMarinerDoom"] = {Spellname ="FizzMarinerDoom",Name = "Fizz", Spellslot =_R},
["AatroxE"] = {Spellname ="AatroxE",Name= "Aatrox", Spellslot =_E},
["AhriOrbofDeception"] = {Spellname ="AhriOrbofDeception",Name = "Ahri", Spellslot =_Q},
["AhriFoxFire"] = {Spellname ="AhriFoxFire",Name = "Ahri", Spellslot =_W},
["AhriSeduce"] = {Spellname ="AhriSeduce",Name = "Ahri", Spellslot =_E},
["AhriTumble"] = {Spellname ="AhriTumble",Name = "Ahri", Spellslot =_R},
["FlashFrost"] = {Spellname ="FlashFrost",Name = "Anivia", Spellslot =_Q},
["Anivia2"] = {Spellname ="Frostbite",Name = "Anivia", Spellslot =_E},
["Disintegrate"] = {Spellname ="Disintegrate",Name = "Annie", Spellslot =_Q},
["Volley"] = {Spellname ="Volley",Name ="Ashe", Spellslot =_W},
["EnchantedCrystalArrow"] = {Spellname ="EnchantedCrystalArrow",Name ="Ashe", Spellslot =_R},
["BandageToss"] = {Spellname ="BandageToss",Name ="Amumu",Spellslot =_Q},
["RocketGrabMissile"] = {Spellname ="RocketGrabMissile",Name ="Blitzcrank",Spellslot =_Q},
["BrandBlaze"] = {Spellname ="BrandBlaze",Name ="Brand", Spellslot =_Q},
["BrandWildfire"] = {Spellname ="BrandWildfire",Name ="Brand", Spellslot =_R},
["BraumQ"] = {Spellname ="BraumQ",Name ="Braum",Spellslot =_Q},
["BraumRWapper"] = {Spellname ="BraumRWapper",Name ="Braum",Spellslot =_R},
["CaitlynPiltoverPeacemaker"] = {Spellname ="CaitlynPiltoverPeacemaker",Name ="Caitlyn",Spellslot =_Q},
["CaitlynEntrapment"] = {Spellname ="CaitlynEntrapment",Name ="Caitlyn",Spellslot =_E},
["CaitlynAceintheHole"] = {Spellname ="CaitlynAceintheHole",Name ="Caitlyn",Spellslot =_R},
["CassiopeiaMiasma"] = {Spellname ="CassiopeiaMiasma",Name ="Cassiopiea",Spellslot =_W},
["CassiopeiaTwinFang"] = {Spellname ="CassiopeiaTwinFang",Name ="Cassiopiea",Spellslot =_E},
["PhosphorusBomb"] = {Spellname ="PhosphorusBomb",Name ="Corki",Spellslot =_Q},
["MissileBarrage"] = {Spellname ="MissileBarrage",Name ="Corki",Spellslot =_R},
["DianaArc"] = {Spellname ="DianaArc",Name ="Diana",Spellslot =_Q},
["InfectedCleaverMissileCast"] = {Spellname ="InfectedCleaverMissileCast",Name ="DrMundo",Spellslot =_Q},
["dravenspinning"] = {Spellname ="dravenspinning",Name ="Draven",Spellslot =_Q},
["DravenDoubleShot"] = {Spellname ="DravenDoubleShot",Name ="Draven",Spellslot =_E},
["DravenRCast"] = {Spellname ="DravenRCast",Name ="Draven",Spellslot =_R},
["EliseHumanQ"] = {Spellname ="EliseHumanQ",Name ="Elise",Spellslot =_Q},
["EliseHumanE"] = {Spellname ="EliseHumanE",Name ="Elise",Spellslot =_E},
["EvelynnQ"] = {Spellname ="EvelynnQ",Name ="Evelynn",Spellslot =_Q},
["EzrealMysticShot"] = {Spellname ="EzrealMysticShot",Name ="Ezreal",Spellslot =_Q,},
["EzrealEssenceFlux"] = {Spellname ="EzrealEssenceFlux",Name ="Ezreal",Spellslot =_W},
["EzrealArcaneShift"] = {Spellname ="EzrealArcaneShift",Name ="Ezreal",Spellslot =_R},
["GalioRighteousGust"] = {Spellname ="GalioRighteousGust",Name ="Galio",Spellslot =_E},
["GalioResoluteSmite"] = {Spellname ="GalioResoluteSmite",Name ="Galio",Spellslot =_Q},
["Parley"] = {Spellname ="Parley",Name ="Gangplank",Spellslot =_Q},
["GnarQ"] = {Spellname ="GnarQ",Name ="Gnar",Spellslot =_Q},
["GravesClusterShot"] = {Spellname ="GravesClusterShot",Name ="Graves",Spellslot =_Q},
["GravesChargeShot"] = {Spellname ="GravesChargeShot",Name ="Graves",Spellslot =_R},
["HeimerdingerW"] = {Spellname ="HeimerdingerW",Name ="Heimerdinger",Spellslot =_W},
["IreliaTranscendentBlades"] = {Spellname ="IreliaTranscendentBlades",Name ="Irelia",Spellslot =_R},
["HowlingGale"] = {Spellname ="HowlingGale",Name ="Janna",Spellslot =_Q},
["JayceToTheSkies"] = {Spellname ="JayceToTheSkies" or "jayceshockblast",Name ="Jayce",Spellslot =_Q},
["jayceshockblast"] = {Spellname ="JayceToTheSkies" or "jayceshockblast",Name ="Jayce",Spellslot =_Q},
["JinxW"] = {Spellname ="JinxW",Name ="Jinx",Spellslot =_W},
["JinxR"] = {Spellname ="JinxR",Name ="Jinx",Spellslot =_R},
["KalistaMysticShot"] = {Spellname ="KalistaMysticShot",Name ="Kalista",Spellslot =_Q},
["KarmaQ"] = {Spellname ="KarmaQ",Name ="Karma",Spellslot =_Q},
["NullLance"] = {Spellname ="NullLance",Name ="Kassidan",Spellslot =_Q},
["KatarinaR"] = {Spellname ="KatarinaR",Name ="Katarina",Spellslot =_R},
["LeblancChaosOrb"] = {Spellname ="LeblancChaosOrb",Name ="Leblanc",Spellslot =_Q},
["LeblancSoulShackle"] = {Spellname ="LeblancSoulShackle" or "LeblancSoulShackleM",Name ="Leblanc",Spellslot =_E},
["LeblancSoulShackleM"] = {Spellname ="LeblancSoulShackle" or "LeblancSoulShackleM",Name ="Leblanc",Spellslot =_E},
["BlindMonkQOne"] = {Spellname ="BlindMonkQOne",Name ="Leesin",Spellslot =_Q},
["LeonaZenithBladeMissle"] = {Spellname ="LeonaZenithBladeMissle",Name ="Leona",Spellslot =_E},
["LissandraE"] = {Spellname ="LissandraE",Name ="Lissandra",Spellslot =_E},
["LucianR"] = {Spellname ="LucianR",Name ="Lucian",Spellslot =_R},
["LuxLightBinding"] = {Spellname ="LuxLightBinding",Name ="Lux",Spellslot =_Q},
["LuxLightStrikeKugel"] = {Spellname ="LuxLightStrikeKugel",Name ="Lux",Spellslot =_E},
["MissFortuneBulletTime"] = {Spellname ="MissFortuneBulletTime",Name ="Missfortune",Spellslot =_R},
["DarkBindingMissile"] = {Spellname ="DarkBindingMissile",Name ="Morgana",Spellslot =_Q},
["NamiR"] = {Spellname ="NamiR",Name ="Nami",Spellslot =_R},
["JavelinToss"] = {Spellname ="JavelinToss",Name ="Nidalee",Spellslot =_Q},
["NocturneDuskbringer"] = {Spellname ="NocturneDuskbringer",Name ="Nocturne",Spellslot =_Q},
["Pantheon_Throw"] = {Spellname ="Pantheon_Throw",Name ="Pantheon",Spellslot =_Q},
["QuinnQ"] = {Spellname ="QuinnQ",Name ="Quinn",Spellslot =_Q},
["RengarE"] = {Spellname ="RengarE",Name ="Rengar",Spellslot =_E},
["rivenizunablade"] = {Spellname ="rivenizunablade",Name ="Riven",Spellslot =_R},
["Overload"] = {Spellname ="Overload",Name ="Ryze",Spellslot =_Q},
["SpellFlux"] = {Spellname ="SpellFlux",Name ="Ryze",Spellslot =_E},
["SejuaniGlacialPrisonStart"] = {Spellname ="SejuaniGlacialPrisonStart",Name ="Sejuani",Spellslot =_R},
["SivirQ"] = {Spellname ="SivirQ",Name ="Sivir",Spellslot =_Q},
["SivirE"] = {Spellname ="SivirE",Name ="Sivir",Spellslot =_E},
["SkarnerFractureMissileSpell"] = {Spellname ="SkarnerFractureMissileSpell",Name ="Skarner",Spellslot =_E},
["SonaCrescendo"] = {Spellname ="SonaCrescendo",Name ="Sona",Spellslot =_R},
["SwainDecrepify"] = {Spellname ="SwainDecrepify",Name ="Swain",Spellslot =_Q},
["SwainMetamorphism"] = {Spellname ="SwainMetamorphism",Name ="Swain",Spellslot =_R},
["SyndraE"] = {Spellname ="SyndraE",Name ="Syndra",Spellslot =_E},
["SyndraR"] = {Spellname ="SyndraR",Name ="Syndra",Spellslot =_R},
["TalonRake"] = {Spellname ="TalonRake",Name ="Talon",Spellslot =_W},
["TalonShadowAssault"] = {Spellname ="TalonShadowAssault",Name ="Talon",Spellslot =_R},
["BlindingDart"] = {Spellname ="BlindingDart",Name ="Teemo",Spellslot =_Q},
["Thresh"] = {Spellname ="ThreshQ",Name ="Thresh",Spellslot =_Q},
["BusterShot"] = {Spellname ="BusterShot",Name ="Tristana",Spellslot =_R},
["VarusQ"] = {Spellname ="VarusQ",Name ="Varus",Spellslot =_Q},
["VarusR"] = {Spellname ="VarusR",Name ="Varus",Spellslot =_R},
["VayneCondemm"] = {Spellname ="VayneCondemm",Name ="Vayne",Spellslot =_E},
["VeigarPrimordialBurst"] = {Spellname ="VeigarPrimordialBurst",Name ="Veigar",Spellslot =_R},
["WildCards"] = {Spellname ="WildCards",Name ="Twistedfate",Spellslot =_Q},
["VelkozQ"] = {Spellname ="VelkozQ",Name ="Velkoz",Spellslot =_Q},
["VelkozW"] = {Spellname ="VelkozW",Name ="Velkoz",Spellslot =_W},
["ViktorDeathRay"] = {Spellname ="ViktorDeathRay",Name ="Viktor",Spellslot =_E},
["XerathArcanoPulseChargeUp"] = {Spellname ="XerathArcanoPulseChargeUp",Name ="Xerath",Spellslot =_Q},
["ZedShuriken"] = {Spellname ="ZedShuriken",Name ="Zed",Spellslot =_Q},
["ZiggsR"] = {Spellname ="ZiggsR",Name ="Ziggs",Spellslot =_R},
["ZiggsQ"] = {Spellname ="ZiggsQ",Name ="Ziggs",Spellslot =_Q},
["ZyraGraspingRoots"] = {Spellname ="ZyraGraspingRoots",Name ="Zyra",Spellslot =_E}
}
self.JungleMinions = minionManager(MINION_JUNGLE, 2000, myHero, MINION_SORT_HEALTH_ASC)
--Target
self.menu_ts = TargetSelector(1750, 0, myHero, true, true, true)
self:MenuOlaf()
self.Machados = false
vpred = VPrediction(true)
--Spells
self.Q = Spell(_Q, 1000)
self.W = Spell(_W, GetTrueAttackRange())
self.E = Spell(_E, 325)
self.R = Spell(_R, 1200)
self.Q:SetSkillShot(0.25, 1200, 90, false)
self.W:SetActive()
self.E:SetTargetted()
self.R:SetActive()
Callback.Add("Tick", function() self:OnTick() end) --Call Back Olaf <3 by: DevkAT
Callback.Add("Draw", function(...) self:OnDraw(...) end)
Callback.Add("DrawMenu", function(...) self:OnDrawMenu(...) end)
end
function Olaf:MenuOlaf()
self.menu = "Olaf"
self.Use_Combo_Q = self:MenuBool("Use Combo Q", true)
self.Use_Combo_W = self:MenuBool("Use W", true)
self.Enable_E = self:MenuBool("Enable E", true)
self.Enable_R = self:MenuBool("Enable R", true)
self.DrawW = self:MenuBool("Draw {W}", true)
self.DrawR = self:MenuBool("Draw {R}", true)
self.Life = self:MenuSliderInt("Hero Life Utimate", 50)
self.Lifetarget = self:MenuSliderInt("Hero Enemy Life Utimate", 50)
self.MinInimigo = self:MenuSliderInt("Range Heros {R}", 2)
self.UseQClear = self:MenuBool("Use Q LaneClear", true)
self.UseWClear = self:MenuBool("Use W LaneClear", true)
self.UseEClear = self:MenuBool("Use E LaneClear", true)
self.ManaJungle = self:MenuSliderInt("Mana Jungle", 45)
self.menu_key_combo = self:MenuKeyBinding("Combo", 32)
self.Lane_Clear = self:MenuKeyBinding("Lane Clear", 86)
self.Harass = self:MenuKeyBinding("Harass", 67)
end
function Olaf:OnDrawMenu()
if Menu_Begin(self.menu) then
if Menu_Begin("Combo") then
self.Use_Combo_Q = Menu_Bool("Use Combo Q", self.Use_Combo_Q, self.menu)
self.Use_Combo_W = Menu_Bool("Use Combo W", self.Use_Combo_W, self.menu)
self.Enable_E = Menu_Bool("Use Combo E", self.Enable_E, self.menu)
Menu_End()
end
if Menu_Begin("Logic {R}") then
self.Enable_R = Menu_Bool("Use R Logic?", self.Enable_R, self.menu)
self.Life = Menu_SliderInt("Hero Life Utimate", self.Life, 0, 100, self.menu)
self.Lifetarget = Menu_SliderInt("Hero Enemy Life Utimate", self.Lifetarget, 0, 100, self.menu)
self.MinInimigo = Menu_SliderInt("Range Heros {R}", self.MinInimigo, 0, 5, self.menu)
Menu_End()
end
if Menu_Begin("JungleClear") then
self.UseQClear = Menu_Bool("Use Q Clear", self.UseQClear, self.menu)
self.UseWClear = Menu_Bool("Use W Clear", self.UseQClear, self.menu)
self.UseEClear = Menu_Bool("Use E Clear", self.UseEClear, self.menu)
self.ManaJungle = Menu_SliderInt("Mana Jungle", self.ManaJungle, 0, 100, self.menu)
Menu_End()
end
if Menu_Begin("Drawings") then
self.DrawW = Menu_Bool("Draw {Q}", self.DrawW, self.menu)
self.DrawR = Menu_Bool("Draw {E}", self.DrawR, self.menu)
Menu_End()
end
if Menu_Begin("Keys Olaf") then
self.menu_key_combo = Menu_KeyBinding("Combo", self.menu_key_combo, self.menu)
self.Lane_Clear = Menu_KeyBinding("Lane Clear", self.Lane_Clear, self.menu)
self.Harass = Menu_KeyBinding("Harass", self.Harass, self.menu)
Menu_End()
end
Menu_End()
end
end
function Olaf:MenuBool(stringKey, bool)
return ReadIniBoolean(self.menu, stringKey, bool)
end
function Olaf:MenuKeyBinding(stringKey, valueDefault)
return ReadIniInteger(self.menu, stringKey, valueDefault)
end
function Olaf:MenuSliderInt(stringKey, valueDefault)
return ReadIniInteger(self.menu, stringKey, valueDefault)
end
function Olaf:OnDraw()
if self.Q:IsReady() and self.DrawW then
DrawCircleGame(myHero.x , myHero.y, myHero.z, self.Q.range, Lua_ARGB(255,255,0,0))
end
if self.E:IsReady() and self.DrawR then
DrawCircleGame(myHero.x , myHero.y, myHero.z, self.E.range, Lua_ARGB(255,0,0,255))
end
end
function Olaf:IsAfterAttack()
if CanMove() and not CanAttack() then
return true
else
return false
end
end
function Olaf:JungleClear()
GetAllUnitAroundAnObject(myHero.Addr, 2000)
local result = {}
for i, minions in pairs(pUnit) do
if minions ~= 0 and not IsDead(minions) and not IsInFog(minions) and GetType(minions) == 3 then
table.insert(result, minions)
end
end
return result
end
function Olaf:FarmJungle(target)
for i, minions in ipairs(self:JungleClear()) do
if minions ~= 0 then
local jungle = GetUnit(minions)
if GetPercentMP(myHero.Addr) >= self.ManaJungle then
if CanCast(_Q) then
if jungle ~= nil and GetDistance(jungle) < self.Q.range and self.UseQClear then
self.Q:Cast(jungle.Addr)
end
end
if CanCast(_W) then
if jungle ~= nil and GetDistance(jungle) < self.W.range and self.UseWClear then
self.W:Cast(myHero.Addr)
end
end
if CanCast(_E) then
if jungle ~= nil and GetDistance(jungle) < self.E.range and self.UseEClear then
self.E:Cast(jungle.Addr)
end
end
end
end
end
end
function Olaf:OnTick()
if IsDead(myHero.Addr) or IsTyping() or IsDodging() then return end
if GetKeyPress(self.Lane_Clear) > 0 then
self:FarmJungle()
end
if GetKeyPress(self.menu_key_combo) > 0 then
self:LogicQ()
self:LogicE()
self:LogicW()
self:LogicR()
end
end
function Olaf:LogicQ()
local TargetQ = GetTargetSelector(self.Q.range)
if CanCast(_Q) and CanMove() and self.Use_Combo_Q and TargetQ ~= 0 then
target = GetAIHero(TargetQ)
local CastPosition, HitChance, Position = vpred:GetLineCastPosition(target, self.Q.delay, self.Q.width, self.Q.range, self.Q.speed, myHero, false)
--local Collision = CountObjectCollision(0, target.Addr, myHero.x, myHero.z, CastPosition.x, CastPosition.z, self.Q.width, self.Q.range, 65)
if HitChance >= 2 then
CastSpellToPos(CastPosition.x, CastPosition.z, _Q)
end
end
end
function Olaf:LogicW()
local target = self.menu_ts:GetTarget()
if target ~= 0 and self.Use_Combo_W then
if self.W:IsReady() and IsValidTarget(target, GetTrueAttackRange()) then
self.W:Cast()
end
end
end
function Olaf:LogicE()
local TargetE = GetTargetSelector(self.E.range)
if CanCast(_E) and CanMove() and self.Enable_E and TargetE ~= 0 then
target = GetAIHero(TargetE)
CastSpellTarget(target.Addr, _E)
end
end
function Olaf:LogicR()
local target = self.menu_ts:GetTarget()
if target ~= 0 and IsEnemy(target) then
local hero = GetAIHero(target)
if self.R:IsReady() and self.Enable_R and IsValidTarget(target, self.R.range) and CountEnemyChampAroundObject(target, self.R.range) <= self.MinInimigo and hero.HP*100/hero.MaxHP < self.Lifetarget and GetPercentHP(myHero.Addr) < self.Life then --solo
self.R:Cast(target)
end
end
end
|
function mmpkg.isAlive()
mmpkg.updateMaxStats()
mmpkg.updateVitals()
mmpkg.myAffects = mmpkg.myAffects or {}
mmpkg.myAffects.affects = {}
end
|
workspace ("InsightECS")
architecture ("x86_64")
configurations
{
"Develop-Exe",
"Develop-Exe-Debug",
"Develop-Exe-Release",
"Develop-Exe-Distribution",
}
buildFolder = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
project ("Develop")
kind "ConsoleApp"
location ("") -- Root Directory
language ("C++")
cppdialect ("C++17")
targetname ("Develop-Target")
targetdir("Binaries/" .. buildFolder)
objdir("Binaries/Intermediates/" .. buildFolder)
files
{
"Include/**.h",
"Development/**.h",
"Development/**.cpp",
}
includedirs
{
"Include/",
}
filter "configurations:Develop-Exe"
defines {"ECS_DEBUG", "ECS_DEVELOPMENT" }
runtime "Debug"
symbols "On"
filter "configurations:Develop-Exe-Debug"
defines {"ECS_DEBUG" }
runtime "Debug"
symbols "On"
filter "configurations:Develop-Exe-Release"
defines "ECS_RELEASE"
runtime "Release"
optimize "On"
symbols "On"
filter "configurations:Develop-Exe-Distribution"
defines "ECS_DISTRIBUTION"
runtime "Release"
optimize "On"
symbols "Off" |
----------------------------------------------------------
-- kev-gore by: Kevin0M16
----------------------------------------------------------
fx_version 'cerulean'
games { 'gta5' }
author 'Kevin_M16'
description 'kevs-gore - a FiveM gore enhancement'
version '1.0.0'
replace_level_meta 'meta/gta5'
files {
'peddamage.xml',
'meta/gta5.meta',
'data/effects/bloodfx.dat',
'data/effects/decals.dat',
'data/effects/liquidfx.dat'
}
data_file 'PED_DAMAGE_OVERRIDE_FILE' 'peddamage.xml' |
TOOL.Category = "Wire Extras/Visuals"
TOOL.Name = "Painter"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool.wire_painter.name", "Painter Tool (Wire)" )
language.Add( "Tool.wire_painter.desc", "Spawns a decal painter for use with the wire system." )
language.Add( "Tool.wire_painter.0", "Primary: Create/Update Painter" )
language.Add( "WirePainterTool_painter", "Painter:" )
language.Add( "WirePainterTool_playsnd", "Play Sound:" )
language.Add( "WirePainterTool_paintrate", "Paint Rate:" )
language.Add( "WirePainterTool_decal", "Decal:" )
language.Add( "WirePainterTool_Range", "Max Range:" )
language.Add( "WirePainterTool_Model", "Choose a Model:")
language.Add( "sboxlimit_wire_painters", "You've hit painters limit!" )
language.Add( "undone_Wire Painter", "Undone Wire Painter" )
end
if (SERVER) then
CreateConVar('sbox_maxwire_painters', 20)
CreateConVar('sbox_wire_painters_maxlen', 30)
CreateConVar('sbox_wire_painters_allowtrgply',1)
end
TOOL.ClientConVar[ "playsnd" ] = "1"
TOOL.ClientConVar[ "paintrate" ] = "0"
TOOL.ClientConVar[ "decal" ] = "Blood"
TOOL.ClientConVar[ "Range" ] = 2048
TOOL.ClientConVar[ "Model" ] = "models/jaanus/wiretool/wiretool_siren.mdl"
local paintermodels = {
["models/jaanus/wiretool/wiretool_beamcaster.mdl"] = {},
["models/jaanus/wiretool/wiretool_siren.mdl"] = {}};
cleanup.Register( "wire_painters" )
function TOOL:LeftClick( trace )
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if ( CLIENT ) then return true end
local ply = self:GetOwner()
local playsnd = (self:GetClientNumber( "playsnd" ) ~= 0)
local paintrate = self:GetClientNumber("paintrate")
local decal = self:GetClientInfo("decal")
local Range = self:GetClientNumber("Range")
local model = self:GetClientInfo("Model")
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_painter" && trace.Entity:GetTable().pl == ply ) then
trace.Entity:Setup(Range, decal, playsnd, paintrate)
return true
end
if ( !self:GetSWEP():CheckLimit( "wire_painters" ) ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local wire_painter = MakeWirePainter( ply, trace.HitPos, Range, decal, playsnd, paintrate, model, Ang )
local min = wire_painter:OBBMins()
wire_painter:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_painter, trace.Entity, trace.PhysicsBone, true)
undo.Create("Wire Painter")
undo.AddEntity( wire_painter )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_painters", wire_painter )
return true
end
if (SERVER) then
function MakeWirePainter( pl, Pos, Range, decal, playsnd, paintrate, Model, Ang )
if ( !pl:CheckLimit( "wire_painters" ) ) then return false end
local wire_painter = ents.Create( "gmod_wire_painter" )
if (!wire_painter:IsValid()) then return false end
wire_painter:SetAngles( Ang )
wire_painter:SetPos( Pos )
wire_painter:SetModel( Model )
wire_painter:Spawn()
wire_painter:Setup(Range, decal, playsnd, paintrate)
wire_painter:SetPlayer( pl )
local ttable = {
Range = Range,
Decal = decal,
PlaySound = playsnd,
PaintRate = paintrate,
pl = pl
}
table.Merge(wire_painter:GetTable(), ttable )
pl:AddCount( "wire_painters", wire_painter )
return wire_painter
end
duplicator.RegisterEntityClass("gmod_wire_painter", MakeWirePainter, "Pos", "Range", "Decal", "PlaySound", "PaintRate", "Model", "Ang", "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostWirePainter( ent, player )
if ( !ent || !ent:IsValid() ) then return end
local tr = util.GetPlayerTrace( player, player:GetAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_painter" ) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self:GetClientInfo("Model") ) then
self:MakeGhostEntity( self:GetClientInfo("Model"), Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostWirePainter( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_painter.name", Description = "#Tool.wire_painter.desc" })
panel:AddControl( "PropSelect", { Label = "#WirePainterTool_Model",
ConVar = "wire_painter_Model",
Category = "Wire Painter",
Models = paintermodels } )
local Options = list.Get( "PaintMaterials" )
table.sort( Options )
local RealOptions = {}
for k, decal in pairs( Options ) do
RealOptions[ decal ] = { wire_painter_decal = decal }
end
panel:AddControl( "ListBox", {
Label = "#WirePainterTool_decal",
Height = "300",
Options = RealOptions
} )
panel:AddControl("CheckBox", {
Label = "#WirePainterTool_playsnd",
Command = "wire_painter_playsnd"
})
panel:AddControl("Slider", {
Label = "#WirePainterTool_paintrate",
Type = "Float",
Min = "0",
Max = "2",
Command = "wire_painter_paintrate"
})
panel:AddControl("Slider", {
Label = "#WirePainterTool_Range",
Type = "Float",
Min = "1",
Max = "10000",
Command = "wire_painter_Range"
})
end
|
local Assert = require(script.Parent._Util.Assert)
local assertTypeOf = Assert.prepTypeOf("GetContrastRatio")
local GetLuminance = require(script.Parent.GetLuminance)
local max = math.max
local min = math.min
return function(foreground: Color3, background: Color3): number
assertTypeOf("foreground", "Color3", foreground)
assertTypeOf("background", "Color3", background)
local lumA = GetLuminance(foreground)
local lumB = GetLuminance(background)
return (max(lumA, lumB) + .05) / (min(lumA, lumB) + .05)
end
|
local fs = {}
local lfs = nil
local separator = package.config:match("^([^\n]*)")
if love ~= nil then
elseif pcall(function () lfs = require('lfs') end) then
else
error("LFS or Love are required to access the filesystem.")
end
function fs.currentDir ()
if love ~= nil then
return "/"
elseif lfs ~= nil then
return lfs.currentdir()
end
end
local function normalizePath (path)
if love ~= nil then
local normalizedPath = path:gsub("\\", "/")
return normalizedPath
end
return path
end
function fs.isDirectory (path)
if love ~= nil then
return love.filesystem.isDirectory(normalizePath(path))
elseif lfs ~= nil then
local stat = lfs.attributes(path)
if stat ~= nil then
return stat.mode == "directory"
end
return false
end
end
function fs.isFile (path)
if love ~= nil then
return love.filesystem.isFile(normalizePath(path))
elseif lfs ~= nil then
local stat = lfs.attributes(path)
if stat ~= nil then
return stat.mode == "file"
end
return false
end
end
function fs.read (path)
if love ~= nil then
return love.filesystem.read(normalizePath(path))
else
local file = io.open(path, "rb")
if file then
return file:read("*a")
end
end
end
function fs.load (path)
if love ~= nil then
return love.filesystem.load(normalizePath(path))
else
if loadstring ~= nil then
--Lua 5.1
return assert(loadstring(assert(fs.read(path)), path))
elseif load ~= nil then
--Lua 5.2+
return assert(load(assert(fs.read(path)), path))
end
end
end
return fs
|
local ip_country = require "bw.util.ip_country"
return function()
local cn = '113.111.109.39'
local c = ip_country.get_country(cn)
assert(c == "China", c)
assert(ip_country.is_china(cn))
local us = '95.163.203.38'
c = ip_country.get_country(us)
assert(c == "United States", c)
assert(not ip_country.is_china(us))
c = ip_country.get_country('127.0.0.1')
assert(c == "local", c)
assert(ip_country.is_china('127.0.0.1'))
c = ip_country.get_country('localhost')
assert(c == "local", c)
assert(ip_country.is_china('localhost'))
return true
end
|
-- Module luaven provides functions generating Lua string patterns for matching
-- fuzzy/similar strings with small Levenshtein-Damerau distance.
local luaven = {}
-- luaven.all iterates over all patterns similar to s with Levenshtein-Damerau
-- distance 1. Only ANSI strings are handled properly.
--
-- IMPORTANT NOTE: create patterns are *not* Lua gsub patterns. To convert a
-- created pattern to Lua gsub pattern, for default UTF-8, replace every "?"
-- with ".?".
--
-- Example:
-- for s in luaven.all "hi" do io.write(s.." ") end
-- -- ?i h? .hi h.i hi. ih
function luaven.all(s)
return coroutine.wrap(function()
-- patterns with distance 1 by replacement/deletion:
-- build by replacing s[i] with '?'
for i = 1,#s do
local pre, suf = s:sub(1,i-1), s:sub(i+1)
coroutine.yield(pre .. '?' .. suf)
end
-- patterns with distance 1 by insertion:
-- build by inserting '.' between s[i-1] and s[i]
for i = 1,#s+1 do
local pre, suf = s:sub(1,i-1), s:sub(i)
coroutine.yield(pre .. '.' .. suf)
end
-- patterns with distance 1 by swapping (Damerau)
for i = 1,#s-1 do
local first, second = s:sub(i,i), s:sub(i+1,i+1)
local pre, suf = s:sub(1,i-1), s:sub(i+2)
coroutine.yield(pre..second..first..suf)
end
end)
end
-- luaven.all_utf8 is an experimental variant of luaven.all, trying to handle
-- UTF-8 strings appropriately.
function luaven.all_utf8(s)
-- regexp: ([0x00-0x7f]|[0xc0-0xff][0x80-0xbf]*)
local utf8_char = '[^\128-\191][\128-\191]*'
local offs = {} -- n-th character start offsets
s:gsub('()'..utf8_char, function(i, c) offs[#offs+1] = i end)
offs[#offs+1] = #s+1 -- first offset out of string bounds
-- for _,v in ipairs(offs) do print(v) end
return coroutine.wrap(function()
-- patterns with distance 1 by replacement/deletion:
-- build by replacing s[i] with '?'
for i = 1,#offs-1 do
local pre, suf = s:sub(1,offs[i]-1), s:sub(offs[i+1])
coroutine.yield(pre .. '?' .. suf)
end
-- patterns with distance 1 by insertion:
-- build by inserting '.' between s[i-1] and s[i]
for i = 1,#offs do
local pre, suf = s:sub(1,offs[i]-1), s:sub(offs[i])
coroutine.yield(pre .. '.' .. suf)
end
-- patterns with distance 1 by swapping (Damerau)
for i = 1,#offs-2 do
local first, second = s:sub(offs[i],offs[i+1]-1), s:sub(offs[i+1],offs[i+2]-1)
local pre, suf = s:sub(1,offs[i]-1), s:sub(offs[i+2])
coroutine.yield(pre..second..first..suf)
end
end)
end
---- DEMO/TEST ----
if not ... then
-- local word = 'hello'
local word = 'hi'
-- luaven.all
local expect = {'?i', 'h?', '.hi', 'h.i', 'hi.', 'ih'}
local i = 1
for s in luaven.all(word) do
print(s)
if s ~= expect[i] then print(' FAIL: wanted '..expect[i]) end
i = i+1
end
-- luaven.all_utf8 on ANSI string
print()
local i = 1
for s in luaven.all(word) do
print(s)
if s ~= expect[i] then print(' FAIL: wanted '..expect[i]) end
i = i+1
end
-- luaven.all + luaven.all
local dist2 = {}
for s in luaven.all(word) do
for s2 in luaven.all(s) do
dist2[s2] = true
end
end
print()
local dist2sort = {}
for k in pairs(dist2) do
dist2sort[#dist2sort+1] = k
end
table.sort(dist2sort)
for _, v in ipairs(dist2sort) do
print(v)
end
-- luaven.all_utf8
print()
local expect = {'?ż', 'ł?', '.łż', 'ł.ż', 'łż.', 'żł'}
local i = 1
for s in luaven.all_utf8 'łż' do
print(s)
if s ~= expect[i] then print(' FAIL: wanted '..expect[i]) end
i = i+1
end
end
return luaven
|
--------------------------------------------------------------------------------
----------------------------------- DevDokus -----------------------------------
--------------------------------------------------------------------------------
if (((Plugins.BountyHunter) and not (_StartError_) and (Framework.Vorp) and not (Framework.RedEmRP))) then
local VorpCore = {}
TriggerEvent("getCore", function(core) VorpCore = core end)
function Wait(args) Citizen.Wait(args) end
function Invoke(args, bool) Citizen.InvokeNative(args, bool) end
--------------------------------------------------------------------------------
-- Event Register
RegisterServerEvent('DevDokus:BountyHunter:S:CheckJob')
RegisterServerEvent('DevDokus:BountyHunter:S:PayDay')
--------------------------------------------------------------------------------
-- Core
--------------------------------------------------------------------------------
-- Variables
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
AddEventHandler('DevDokus:BountyHunter:S:PayDay', function(KillCount)
local BPK = BountyHunter.Payment.Money.BPK
local XPK = BountyHunter.Payment.XP.XPK
local mMin = BountyHunter.Payment.Money.Min
local mMax = BountyHunter.Payment.Money.Max
local xMin = BountyHunter.Payment.XP.Min
local xMax = BountyHunter.Payment.XP.Max
local vMoney = BountyHunter.Payment.Money.Static
local vEXP = BountyHunter.Payment.XP.Static
local Char = VorpCore.getUser(source).getUsedCharacter
local mPay = nil
local xPay = nil
if BPK then
local PayDay = (math.floor(math.random(mMin, mMax) * KillCount))
Char.addCurrency(0, PayDay)
mPay = PayDay
else
Char.addCurrency(0, vMoney)
mPay = vMoney
end
if XPK then
local rEXP = (math.floor(math.random(xMin, xMax) * KillCount))
Char.addXp(rEXP)
xPay = rEXP
else
Char.addXp(vEXP)
xPay = vEXP
end
TriggerClientEvent('DevDokus:BountyHunter:C:ResetTotalKills', source)
TriggerClientEvent("vorp:TipRight", source, _('BountyHunter_Payment1')..mPay.._('BountyHunter_Payment2')..xPay.._('BountyHunter_Payment3'), 5000)
end)
AddEventHandler('DevDokus:BountyHunter:S:CheckJob', function()
local User = VorpCore.getUser(source)
if User ~= nil then
local Character = User.getUsedCharacter
local _Job = Character.job
TriggerClientEvent('DevDokus:BountyHunter:C:SetUpMission', source, _Job)
end
end)
end
--------------------------------------------------------------------------------
|
id = 'V-38474'
severity = 'low'
weight = 10.0
title = 'The system must allow locking of graphical desktop sessions.'
description = 'The ability to lock graphical desktop sessions manually allows users to easily secure their accounts should they need to depart from their workstations temporarily.'
fixtext = [=[Run the following command to set the Gnome desktop keybinding for locking the screen:
# gconftool-2
--direct \
--config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory \
--type string \
--set /apps/gnome_settings_daemon/keybindings/screensaver "<Control><Alt>l"
Another keyboard sequence may be substituted for "<Control><Alt>l", which is the default for the Gnome desktop.]=]
checktext = [=[If the GConf2 package is not installed, this is not applicable.
Verify the keybindings for the Gnome screensaver:
# gconftool-2 --direct --config-source xml:readwrite:/etc/gconf/gconf.xml.mandatory --get /apps/gnome_settings_daemon/keybindings/screensaver
If no output is visible, this is a finding.]=]
function test()
end
function fix()
end
|
describe("Simple factory", function()
local factory = {};
setup(function()
factory = require("../simpleFactory");
end)
it("should generate addition operation", function()
local operation = factory:CreateOperation("+");
operation.numberA = 10;
operation.numberB = 5;
assert.is.equal(10 + 5, operation:GetResult());
end)
it("should generate subtraction operation", function()
local operation = factory:CreateOperation("-");
operation.numberA = 10;
operation.numberB = 5;
assert.is.equal(10 - 5, operation:GetResult());
end)
it("should generate multiplication operation", function()
local operation = factory:CreateOperation("*");
operation.numberA = 10;
operation.numberB = 5;
assert.is.equal(10 * 5, operation:GetResult());
end)
it("should generate division operation", function()
local operation = factory:CreateOperation("/");
operation.numberA = 10;
operation.numberB = 5;
assert.is.equal(10 / 5, operation:GetResult());
end)
end)
|
MxM = {}MxM.S_projectCallback = {}MxM.C_projectCallback = {} MxM.ProjectId = 0 RegisterNetEvent('MxM:T_C_projectCallback') AddEventHandler('MxM:T_C_projectCallback', function(name, requestId, ...) local playerId = source MxM.T_C_projectCallback(name, requestID, playerId, function(...) TriggerServerEvent('MxM:clientCallback', requestId, ...) end, ...)end)MxM.T_S_projectCallback = function(name, PJ, ...) MxM.S_projectCallback[MxM.ProjectId] = PJ TriggerServerEvent('MxM:T_S_projectCallback', name, MxM.ProjectId, ...) if MxM.ProjectId < 99999 then MxM.ProjectId = MxM.ProjectId + 1 else MxM.ProjectId = 0 end end MxM.R_C_projectCallback = function(name, PJ) MxM.C_projectCallback[name] = PJ end MxM.T_C_projectCallback = function(name, requestId, source, PJ, ...) if MxM.C_projectCallback[name] ~= nil then MxM.C_projectCallback[name](PJ, ...) end end RegisterNetEvent('MxM:serverCallback') AddEventHandler('MxM:serverCallback', function(requestId, ...) MxM.S_projectCallback[requestId](...) MxM.S_projectCallback[requestId] = nil end)
-- Dont' Edit my code, grz :) |
local operate = require('rx.operator')
local observer = require('rx.observer')
return function(count)
return operate(function(source, destination)
if (not count) then
return source.subscribe(destination)
end
local seen = 0
local next
if (count <= 0) then
next = function()
destination.complete()
end
else
next = function(...)
destination.next(...)
seen = seen + 1
if (seen >= count) then
destination.complete()
end
end
end
source.subscribe(observer(destination, next))
end)
end
|
Locales['en'] = {
['vehicle_shop'] = 'Dealership',
['open_vehicle_shop'] = 'Press ~INPUT_PICKUP~ to enter dealership menu',
['open_vehicle_sell'] = 'Press ~INPUT_PICKUP~ to sell your vehicle for ~o~%s~s~',
['shop_menu_item'] = '<strong>%s<strong> <span style="color: darkred;">%s</span>',
['wait_vehicle'] = 'Just waiting for the vehicle to load...',
['confirm_title'] = 'Do you want to buy a %s for %s?',
['confirm_vehicle_sell'] = 'Would you like to sell your vehicle for %s?',
['yes'] = 'Yes',
['no'] = 'No',
['error_invalid_vehicle'] = 'You are trying to buy a vehicle that is not for sale in the dealership',
['error_invalid_price'] = 'You are trying to buy a vehicle for 0 euros, unfortunately this is not possible',
['error_no_money'] = 'You don\'t have enough money on your bank to buy this vehicle',
['error_not_your_vehicle'] = 'This vehicle is not yours',
['error_hash_mismatch'] = 'Vehicle model does not match',
['vehicle_purched'] = 'You have bought a vehicle with license plate %s, have fun with your new vehicle',
['vehicle_sold'] = 'You have sold your vehicle for ~o~%s~s~ to the dealership',
['must_driver'] = 'You must be the driver of this vehicle',
-- Commands
['command_shopvehicle'] = 'Customize vehicles from the dealership',
['command_shopcategory'] = 'Customize categories of the dealership',
['command_shopvehicle_action'] = 'Action you want to do: add, remove or update',
['command_shopvehicle_vehicle'] = 'Spawncode of vehicle, e.g: adder, dubsta3, f620 etc.',
['command_shopvehicle_price'] = 'Price for vehicle in dealership',
['command_shopvehicle_category'] = 'Category of vehicle',
['command_shopvehicle_name'] = 'Name of category',
['command_shopvehicle_label'] = 'Label of category',
['invalid_action'] = 'Your action is invalid, may be: add, remove or update',
['invalid_vehicle_model'] = 'Vehicle you specified is not loaded or does not exist',
['invalid_vehicle_price'] = 'Price of vehicle must be higher than 0 euro',
['invalid_category'] = 'You have given a non-existent category',
['vehicle_added'] = 'Vehicle %s has been added to the dealership for %s',
['vehicle_removed'] = 'Vehicle %s have been removed from the dealership',
['vehicle_updated'] = 'Vehicle %s has been updated in the dealership and price is set to %s',
['category_added'] = 'Category %s has been added to the dealership',
['category_removed'] = 'Category %s has been removed from the dealership',
['category_updated'] = 'Category %s has been updated in the dealership',
['vehicle_already_exists'] = 'Vehicle %s had already been added to the dealership',
['vehicle_doesnt_exists'] = 'Vehicle %s does not exist or has already been removed',
['category_already_exists'] = 'Category %s had already been added to the dealership',
['category_doesnt_exists'] = 'Category %s does not exist or has already been removed',
['empty_parameter'] = 'Parameter [ %s ] must be specified',
['empty_number'] = 'Parameter [ %s ] must be a number'
} |
local root = script.Parent
local Behaviors = require(root.Behaviors)
local function getReal(self)
return select(2, next(self))
end
local Contexts = {
Global = {
[newproxy()] = {
Keys = {},
Values = { "transform", "reconcile", "replace" },
Meta = {},
},
},
}
Contexts.Enum = {}
local enumString = {}
for context in pairs(getReal(Contexts.Global)) do
Contexts.Enum[context] = true
table.insert(enumString, context)
end
enumString = table.concat(enumString, ", ")
local function errorUnknownContext(context)
error(
string.format("Unknown context (%s) found. The only allowed contexts are %s.", tostring(context), enumString),
2
)
end
function Contexts.Assert(context)
if Contexts.Enum[context] then
return context
else
errorUnknownContext(context)
end
end
local globalMt = {}
function globalMt:__index(context)
Contexts.Assert(context)
return getReal(self)[context]
end
function globalMt:__newindex(context, behaviors)
Contexts.Assert(context)
behaviors = Behaviors.Convert(behaviors)
getReal(self)[context] = behaviors
end
setmetatable(Contexts.Global, globalMt)
return Contexts
|
-- This module cache value to local map
-- To be usefull this function requires the solution to enable the HotVM setting
local cache = {}
function cache.get(key, getter, timeout)
local now = os.time();
if not cache[key] or cache[key].ts < now + (timeout or 30) then
local value;
if getter then
value = getter(key)
else
value = Keystore.get({ key = key })
end
if value == nil or value.error then
return nil
end
cache[key] = {
ts = now,
value = value
}
end
return cache[key].value
end
function cache.set(key, value, setter)
if cache[key] == value then
return
end
local result
if setter then
result = setter(key, value)
else
result = Keystore.set({ key = key, value = value})
end
if result and result.error then
return nil
end
cache[key] = {
ts = os.time(),
value = value
}
return value
end
return cache
|
local skynet = require "skynet"
local snax = require "skynet.snax"
skynet.start(function()
local ps = snax.uniqueservice ("pingserver", "test queue")
for i=1, 10 do
ps.post.sleep(true,i*10)
ps.post.hello()
end
for i=1, 10 do
ps.post.sleep(false,i*10)
ps.post.hello()
end
skynet.exit()
end)
|
local ItemName2Type= GetFileConfig(OUTPUTBASE.."server/setting/item/name2type.lua")
return function (Data)
local Tbl = Split(Data, ",")
local Ret = {}
for _, Name in ipairs(Tbl) do
assert(ItemName2Type[Name],Name.."没有该物品类型,请确认相关物品表")
table.insert(Ret, ItemName2Type[Name])
end
return Ret
end |
local PANEL = {}
local COLOR_PRICE = Color(255, 255, 255, 75)
local COLOR_CANNOT_AFFORD = Color(255, 100, 100, 75)
local function ignore() end
function PANEL:Init()
self:Dock(TOP)
self:SetTall(64)
self:SetDrawBackground(false)
self.suffix = ""
self.icon = self:Add("nutItemIcon")
self.icon:SetSize(64, 64)
self.icon.PaintBehind = ignore
self.icon.OnCursorEntered = function(icon)
self:OnCursorEntered()
end
self.name = self:Add("DLabel")
self.name:SetPos(self.icon:GetWide() + 8, 8)
self.name:SetTextColor(color_white)
self.name:SetExpensiveShadow(1, color_black)
self.name:SetFont("nutVendorSmallFont")
self.name:SizeToContents()
self.price = self:Add("DLabel")
self.price:SetPos(self.icon:GetWide() + 8, 8 + self.name:GetTall())
self.price:SetTextColor(Color(255, 255, 255, 75))
self.price:SetExpensiveShadow(1, color_black)
self.price:SetFont("nutVendorLightFont")
self.price:SetText(nut.currency.get(0))
self.price:SizeToContents()
self:SetCursor("hand")
self.isSelling = false
end
function PANEL:updatePrice()
local price = nutVendorEnt:getPrice(self.item.uniqueID, self.isSelling)
self.price:SetText(nut.currency.get(price))
self.price:SizeToContents()
end
function PANEL:setIsSelling(isSelling)
self.isSelling = isSelling
self:updatePrice()
end
local function clickEffects()
LocalPlayer():EmitSound(unpack(SOUND_VENDOR_CLICK))
end
local function sellItemToVendor(panel)
local item = panel.item
if (not item) then return end
if (IsValid(nut.gui.vendor)) then
nut.gui.vendor:sellItemToVendor(item.uniqueID)
clickEffects()
end
end
local function buyItemFromVendor(panel)
local item = panel.item
if (not item) then return end
if (IsValid(nut.gui.vendor)) then
nut.gui.vendor:buyItemFromVendor(item.uniqueID)
clickEffects()
end
end
function PANEL:showAction()
if (IsValid(self.action)) then return end
self.action = self:Add("DButton")
self.action:Dock(FILL)
self.action:SetFont("nutVendorSmallFont")
self.action:SetTextColor(color_white)
self.action:SetAlpha(0)
self.action:AlphaTo(255, 0.2, 0)
self.action.OnCursorExited = function(button)
button:Remove()
end
self.action.Paint = function(button, w, h)
surface.SetDrawColor(0, 0, 0, 220)
surface.DrawRect(0, 0, w, h)
end
self.action:SetText(L(self.isSelling and "sell" or "buy"):upper())
self.action.nutToolTip = true
self.action:SetToolTip(
"<font=nutItemDescFont>"..self.item:getDesc()
)
self.action.item = self.item
self.action.DoClick = self.isSelling
and sellItemToVendor
or buyItemFromVendor
LocalPlayer():EmitSound("buttons/button15.wav", 25, 200)
end
function PANEL:OnCursorEntered()
self:showAction()
end
function PANEL:setQuantity(quantity)
if (not self.item) then return end
if (quantity) then
if (quantity <= 0) then
self:Remove()
return
end
self.suffix = " ("..tostring(quantity)..")"
else
self.suffix = ""
end
self.name:SetText(self.item:getName()..self.suffix)
self.name:SizeToContents()
end
function PANEL:setItemType(itemType)
local item = nut.item.list[itemType]
assert(item, tostring(itemType).." is not a valid item")
self.item = item
self.icon:setItemType(itemType)
self.name:SetText(item:getName()..self.suffix)
self.name:SizeToContents()
self:updatePrice()
end
vgui.Register("nutVendorItem", PANEL, "DPanel")
|
return {
name = "kaitain.restena.lu",
label = _("Restena DNS - LU"),
resolver_url = "https://kaitain.restena.lu/dns-query",
bootstrap_dns = "1.1.1.1,1.0.0.1,2606:4700:4700::1111,2606:4700:4700::1001,8.8.8.8,8.8.4.4,2001:4860:4860::8888,2001:4860:4860::8844",
help_link = "https://www.restena.lu/en/service/public-dns-resolver",
help_link_text = "Restena.lu"
}
|
BaseDialog_SetQuestValue({{Tale_Action_Quest_Value_Id}}, "{{Tale_Action_ValueName}}", {{Tale_Action_OperatorIsNotSetTo_Start}}BaseDialog_GetQuestValue({{Tale_Action_Quest_Value_Id}}, "{{Tale_Action_ValueName}}") {{Tale_Action_ValueOperator}}{{Tale_Action_OperatorIsNotSetTo_End}} {{Tale_Action_ValueIsString_Start}}"{{Tale_Action_ValueIsString_End}}{{Tale_Action_ValueChange}}{{Tale_Action_ValueIsString_Start}}"{{Tale_Action_ValueIsString_End}})
|
require( "iuplua" )
require( "iupluacontrols" )
result, text = iup.GetParam( "Hello", nil, "Enter a string: %s\n", "[str]" )
result, number = iup.GetParam( "Hello again", nil, "Enter a number: %i\n", 42 )
-- Note: Choice selection is 0-indexed, not 1-indexed.
result, choice = iup.GetParam( "Pick", nil, "Choose: %l|A|B|C|\n", 1 )
iup.Message( "Results", "Got:\nStr: " .. text .. "\nInt: " .. number .. "\nChoice #: " .. choice )
|
local M = {}
local version = require('tn.version')
local usage_str = [[
Usage: tn edit <note-name>
tn list
tn file <note-name>
tn remove <note-name>
tn show <note-name>
tn (-h | --help)
tn --version
tn --bash-completion
tn --commands
Options:
-h --help Show this screen.
--version Show version.
--bash-completion Prints out bash completion script.
--commands List supported commands.
]]
local compl_commands = {
"edit",
"list",
"file",
"remove",
"show",
"--help",
"--version",
"--bash-completion",
"--commands"
}
local compl_bash_script = [=[
_tn_complete() {
local IFS=$'\n'
local cur prev opts
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
opts=()
if [[ "$prev" == "$1" ]]; then
opts=($(tn --commands))
else
case "$prev" in
edit|file|remove|show)
opts=("$(tn list)")
;;
esac
fi
CANDIDATES=($(compgen -W "${opts[*]}" -- ${cur}))
if [ ${#CANDIDATES[*]} -eq 0 ]; then
COMPREPLY=()
else
COMPREPLY=($(printf '%q\n' "${CANDIDATES[@]}"))
fi
}
complete -F _tn_complete tn
]=]
local function write_message(fileh, msg)
fileh:write(msg)
fileh:flush()
end
local function write_usage(fileh)
fileh:write(usage_str)
fileh:write("\n")
fileh:flush()
end
local function write_version(fileh)
fileh:write(tostring(version))
fileh:write("\n")
fileh:flush()
end
local function write_bash_compl(fileh)
fileh:write(compl_bash_script)
fileh:flush()
end
local function write_commands_compl(fileh)
fileh:write(table.concat(compl_commands, "\n"))
fileh:write("\n")
fileh:flush()
end
--- parses arg list into table
---@param args any
local function parse_args(args)
local data = {}
local singleArgCmds = {
edit=true,
file=true,
remove=true,
show=true
}
local zeroArgCmds = {
list=true
}
local helpOpt = "help"
local versionOpt = "version"
local bashCompOpt = "bash-completion"
local commandsOpt = "commands"
local zeroArgOptions = {
["-h"] = helpOpt,
["--help"] = helpOpt,
["--version"] = versionOpt,
["--bash-completion"] = bashCompOpt,
["--commands"] = commandsOpt,
}
if #args == 0 then
data.options = data.options or {}
data.options[helpOpt] = true
return data
end
if zeroArgCmds[args[1]] then
data.subcmd = args[1]
if #args ~= 1 then
error("invalid number of arguments for " .. data.subcmd)
end
return data
end
if singleArgCmds[args[1]] then
data.subcmd = args[1]
if #args == 2 then
data.args = {args[2]}
else
error("invalid number of arguments to " .. data.subcmd)
end
return data
end
local opt = zeroArgOptions[args[1]]
if opt then
if #args == 1 then
data.options = data.options or {}
data.options[opt] = true
return data
else
error("invalid number of option arguments for " .. opt)
end
end
local validCmd = (data.subcmd == "list" and #data.args == 0 and not data.options) or
((data.subcmd == "show" or data.subcmd == "edit" or data.subcmd == "remove" or data.subcmd == "file") and
data.args and #data.args == 1 and not data.options) or
(not data.subcmd and data.options and #data.options == 1 and
(data.options[1] == "bash-completion" or data.options[1] == "help" or data.options[1] == "commands"))
assert(validCmd, "invalid command")
end
M.write_message = write_message
M.write_usage = write_usage
M.write_version = write_version
M.write_bash_compl = write_bash_compl
M.write_commands_compl = write_commands_compl
M.parse_args = parse_args
return M |
function Queue()
local elems = {}
local head = 1
local tail = 1
local function push(x)
elems[tail] = x
tail = tail + 1
end
local function pop()
local value = elems[head]
elems[head] = nil -- help the garbage collector
head = head + 1
return value
end
local function size()
return tail - head
end
return {
push = push,
pop = pop,
size = size
}
end
|
local util = require "util"
-- Define generic mocks of any `hs` functions used in Ki
local mocks = {
appfinder = {
appFromName = function()
return nil
end
},
application = {
get = function()
return nil
end,
enableSpotlightForNameSearches = function()
return nil
end,
infoForBundlePath = function()
return nil
end,
launchOrFocus = function()
return nil
end,
},
canvas = {
new = function()
return {
appendElements = function()
return {
show = function()
return nil
end,
}
end,
}
end,
},
chooser = {
new = function()
return nil
end,
},
dialog = function()
return nil
end,
dir = function()
return nil
end,
displayName = function()
return nil
end,
dockicon = {
hide = function()
return nil
end
},
drawing = {
windowLevels = {
modalPanel = nil,
},
},
execute = function()
return nil
end,
focus = function()
return nil
end,
fs = {
attributes = function()
return nil
end,
fileUTI = function()
return nil
end,
pathToAbsolute = function()
return nil
end,
},
image = {
iconForFileType = function()
return nil
end,
imageFromAppBundle = function()
return {
encodeAsURLString = function()
return nil
end
}
end
},
keycodes = { map = {} },
event = {
getKeyCode = function()
return ""
end,
getFlags = function()
return {
containExactly = function()
return true
end
}
end,
},
eventtap = {
new = function()
return {
start = function()
return nil
end,
isEnabled = function()
return nil
end,
stop = function()
return nil
end,
}
end,
event = {
types = {
keyDown = nil,
},
},
},
notify = {
show = function()
return nil
end,
},
open = function() return nil end,
osascript = {
applescript = function()
return nil
end,
},
screen = {
mainScreen = function()
return {
fullFrame = function()
return { x = 0, y = 0, h = 0, w = 0 }
end,
frame = function()
return { x = 0, y = 0, h = 0, w = 0 }
end,
}
end
},
showError = function()
return nil
end,
sound = {
getByName = function()
return {
volume = function()
return {
play = function()
return nil
end,
}
end,
}
end,
},
styledtext = {
new = function()
return nil
end,
},
timer = {
doAfter = function()
return nil
end,
},
webview = {
new = function()
return {
windowStyle = function() return nil end,
level = function() return nil end,
darkMode = function() return nil end,
shadow = function() return nil end,
}
end,
},
window = function()
return {
focus = function() return nil end,
focusTab = function() return nil end,
}
end,
}
-- Init function that returns the `hs` mock object initializer and its default mocked fields
return function()
-- Mock the Hammerspoon's `hs` environment object with either provided or pre-defined mocks
local hsMocks = util:clone(mocks)
local function mockHammerspoon(data)
data = data or {}
local hs = {}
for name, mock in pairs(hsMocks) do
hs[name] = data[name] or mock
end
return hs
end
-- Return primary mock object and expose mocked fields for granular composition in test files
return mockHammerspoon, hsMocks
end
|
ITEM.name = "«Каменный цветок»"
ITEM.desc = "Артефакт представляет собой камень, близкий по своим характеристикам к гранитам. Возникает внутри гравитационных полей огромной интенсивности. Способен полностью или частично защищать рассудок владельца от пси-воздействия. \n\nХАРАКТЕРИСТИКИ: \n-артефакт \n\nРадиация +3 / сек"
ITEM.price = 23910
ITEM.isAnomaly = true
ITEM.weight = 0.85
ITEM.model = "models/kek1ch/crystal_flower.mdl"
ITEM.width = 1
ITEM.height = 1
ITEM.iconCam = {
pos = Vector(0, 0, 200),
ang = Angle(90, 0, 0),
fov = 6.3057324840764
}
ITEM.functions.Use = {
name = "положить в СИМК",
onRun = function(item)
local client = item.player
if (IsValid(client) && client:Alive()) then
if not client:getChar():getInv():hasItem("simkemp") then
client:notify("Вам нужны СИМК (пустой).")
return false
end
client:EmitSound( Sound( "interface/inv_iam_close.ogg" ), Entity( 1 ):GetPos(), 1, CHAN_AUTO, 1, 20, 0, 100 )
client:getChar():getInv():add("simk_cvetok")
client:getChar():getInv():remove(client:getChar():getInv():hasItem("simkemp"):getID())
client:ScreenFade( SCREENFADE.OUT, Color( 0, 0, 0 ), 1, 3 )
timer.Simple(1,function()
client:ScreenFade( SCREENFADE.IN, Color( 0, 0, 0 ), 1, 3 )
end)
end
end,
onCanRun = function(item)
return (!IsValid(item.entity))
end
} |
resultado = 4 - 10 --A Lua reconhece os numeros negativos
print(resultado)
numeroReal = 45.5 --Numeros Reais
print(numeroReal )
pi = 3.141592737373733849384081 -- Numeros Reais com muitas casas
print("PI "..pi)
|
--[[
Play back the recorded message, and offer a menu of message actions.
]]
operator_extension = storage("mailbox_settings", "operator_extension")
recording_name = storage("record", "last_recording_name")
playback_keys = {
["1"] = "caller_save_recorded_message exit",
["2"] = "caller_playback_recorded_message",
["3"] = "caller_rerecord_message",
}
-- If there's an available operator extension, then include it in the options
-- and pass that data along to the review sequence.
operator_on_review = ""
if operator_extension ~= "" then
playback_keys["0"] = "transfer_to_operator"
operator_on_review = "operator"
end
return
{
{
action = "play",
file = profile.temp_recording_dir .. "/" .. recording_name,
keys = playback_keys,
},
{
action = "call_sequence",
sequence = "review_message " .. operator_on_review,
},
}
|
package.loaded['config.routes'] = { }
package.loaded['config.application'] = {}
_G['ngx'] = {
HTTP_NOT_FOUND = 404,
exit = function(code) return end,
print = function(print) return end,
status = 200,
location = {},
say = print,
eof = os.exit,
header = {},
req = {
read_body = function() return end,
get_body_data = function() return end,
get_headers = function() return end,
get_uri_args = function() return {} end,
get_post_args = function() return {busted = 'busted'} end,
},
var = {
uri = "/users",
request_method = 'GET'
}
}
local config={}
config.name = 'bluebird'
config.route='vanilla.v.routes.simple'
config.bootstrap='application.bootstrap'
config.app={}
config.app.root='./'
config.controller={}
config.controller.path=config.app.root .. 'application/controllers/'
config.view={}
config.view.path=config.app.root .. 'application/views/'
config.view.suffix='.html'
config.view.auto_render=true
_G['config'] = config
require 'vanilla.spec.runner' |
object_tangible_item_beast_converted_kima_decoration = object_tangible_item_beast_shared_converted_kima_decoration:new {
}
ObjectTemplates:addTemplate(object_tangible_item_beast_converted_kima_decoration, "object/tangible/item/beast/converted_kima_decoration.iff")
|
local mod = DBM:NewMod(1774, "DBM-BrokenIsles", nil, 822)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 14958 $"):sub(12, -3))
mod:SetCreatureID(109331)
mod:SetEncounterID(1952)
mod:SetReCombatTime(20)
mod:SetZone()
--mod:SetMinSyncRevision(11969)
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_CAST_START 217966 217986",
"SPELL_CAST_SUCCESS 217877",
"SPELL_AURA_APPLIED 217563 217877 217831 217834",
"SPELL_AURA_REMOVED 217877",
"SPELL_PERIODIC_DAMAGE 217907",
"SPELL_PERIODIC_MISSED 217907"
)
--TODO, cast id for icy commet. It's one of the scripts
--TODO< cast id for Arcanopulse. It's one of the scripts.
--TODO, promote howling gale to special warn if it is at all threatening
local warnAncientRageFire = mod:NewTargetAnnounce(217563, 2)
local warnBurningBomb = mod:NewTargetAnnounce(217877, 3)
local warnAncientRageFrost = mod:NewTargetAnnounce(217831, 2)
local warnHowlingGale = mod:NewSpellAnnounce(217966, 2)
local warnAncientRageArcane = mod:NewTargetAnnounce(217834, 2)
local specBurningBomb = mod:NewSpecialWarningYou(217877, nil, nil, nil, 1, 2)--You warning because you don't have to run out unless healer is afk. However still warn in case they are
local yellBurningBomb = mod:NewFadesYell(217877)
local specBurningBombDispel = mod:NewSpecialWarningDispel(217877, "Healer", nil, nil, 1, 2)
local specWrathfulFlamesGTFO = mod:NewSpecialWarningMove(217907, nil, nil, nil, 1, 2)
local specArcaneDesolation = mod:NewSpecialWarningSpell(217986, nil, nil, nil, 2, 2)
local timerBurningBombCD = mod:NewAITimer(16, 217877, nil, nil, nil, 3)
local timerHowlingGaleCD = mod:NewAITimer(16, 217966, nil, nil, nil, 2)
local timerArcaneDesolationCD = mod:NewAITimer(16, 217986, nil, nil, nil, 2)
local voiceBurningBomb = mod:NewVoice(217877)--targetyou/helpdispel
local voiceWrathfulFlames = mod:NewVoice(217907)--runaway
local voiceArcaneDesolation = mod:NewVoice(217986)--carefly
--mod:AddReadyCheckOption(37460, false)
mod:AddRangeFrameOption(10, 217877)
function mod:OnCombatStart(delay, yellTriggered)
if yellTriggered then
end
end
function mod:OnCombatEnd()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
end
function mod:SPELL_CAST_START(args)
local spellId = args.spellId
if spellId == 217966 then
warnHowlingGale:Show()
timerHowlingGaleCD:Start()
elseif spellId == 217986 then
specArcaneDesolation:Show()
voiceArcaneDesolation:Play("carefly")
timerArcaneDesolationCD:Start()
end
end
function mod:SPELL_CAST_SUCCESS(args)
local spellId = args.spellId
if spellId == 217877 then
timerBurningBombCD:Start()
end
end
function mod:SPELL_AURA_APPLIED(args)
local spellId = args.spellId
if spellId == 217563 then--Fire Phase
warnAncientRageFire:Show(args.destName)
timerHowlingGaleCD:Stop()
timerArcaneDesolationCD:Stop()
timerBurningBombCD:Start(1)
elseif spellId == 217877 then
if self.Options.SpecWarn217877dispel then
specBurningBombDispel:CombinedShow(0.3, args.destName)
if self:AntiSpam(3, 1) then
voiceBurningBomb:Play("helpdispel")
end
else
warnBurningBomb:CombinedShow(0.3, args.destName)
end
if args:IsPlayer() then
specBurningBomb:Show()
voiceBurningBomb:Play("targetyou")
yellBurningBomb:Schedule(7, 1)
yellBurningBomb:Schedule(6, 2)
yellBurningBomb:Schedule(5, 3)
if self.Options.RangeFrame then
DBM.RangeCheck:Show(10)
end
end
elseif spellId == 217831 then--Frost Phase
warnAncientRageFrost:Show(args.destName)
timerBurningBombCD:Stop()
timerArcaneDesolationCD:Stop()
timerHowlingGaleCD:Start(1)
elseif spellId == 217834 then--Arcane Phase
warnAncientRageArcane:Show(args.destName)
timerHowlingGaleCD:Stop()
timerBurningBombCD:Stop()
timerArcaneDesolationCD:Start(1)
end
end
function mod:SPELL_AURA_REMOVED(args)
local spellId = args.spellId
if spellId == 217877 then
if args:IsPlayer() then
yellBurningBomb:Cancel()
if self.Options.RangeFrame then
DBM.RangeCheck:Hide()
end
end
end
end
function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId)
if spellId == 217907 and destGUID == UnitGUID("player") and self:AntiSpam(2, 2) then
specWrathfulFlamesGTFO:Show()
voiceWrathfulFlames:Play("runaway")
end
end
mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE
|
-- NOTE: we heavily suggest using Packer's lazy loading (with the 'event' field)
-- see: https://github.com/wbthomason/packer.nvim
-- https://nvchad.github.io/config/walkthrough
-- source a vimscript file for clipboard support
vim.cmd('source ~/.config/nvim/vimrc')
-----------------------------------------------------------
-- Neovim provider
-----------------------------------------------------------
vim.g.loaded_python_provider = 0 -- disable python 2 provider
vim.g.loaded_python3_provider = 1 -- disable python 3 provider
vim.g.loaded_ruby_provider = 0 -- disable ruby provider
vim.g.loaded_perl_provider = 0 -- disable perl provider
vim.g.python3_host_prog = '/usr/bin/python3'
-- Stop sourcing filetype.vim
-- https://nvchad.github.io/Extras
-- https://github.com/nathom/filetype.nvim
vim.g.did_load_filetypes = 1
-- 500 is suggest by WhichKey.nvim
-- https://github.com/folke/which-key.nvim
vim.o.timeoutlen = 300
|
local ITEM = Clockwork.item:New();
ITEM.name = "Bottle";
ITEM.model = "models/props_junk/GlassBottle01a.mdl";
ITEM.weight = 0.2;
ITEM.category = "Junk";
ITEM.description = "A round glass bottle";
-- Called when a player drops the item.
function ITEM:OnDrop(player, position) end;
ITEM:Register();
|
-------------
-- GLOBALS --
-------------
assert(DynamicCam);
------------
-- LOCALS --
------------
local presets = {
["Classic"] = {
author = "dernPerkins",
description = "No situations enabled, just ActionCam",
importString = "dKdxpaGEc2fKQSniLMPusLzRKBsi3wLdJANQQ9k2nj)wYpPsv)LkACuPY0uidfQQVbPQy4sLoOuLttvhJkCoPQAHeQLkLuAXsXYj1dHu5PuEmrpxrtukXuvQjRGPJCrOOUkKQsptH66sP2iKSvQu2mKITdfULusgMQ8zi(UuvmsPQ0YGsJMkz8sfNekYzLskUgu58qvUmyTsjv9AivvhhzhRRUqJFbzhBaqd3ErOddwpZogbtYPKpqZBwJaeQs2EIjfbAwsywXnliFhXiysoL8bAUVapiQWaoqrgPbfc5kFhXiysoL8bAEZAeGqvY2tmRGdpmR4MfKVJyemjNs(anVzncqOkz7jMvWHNrAqHqUW3tsxbfUrVrJD0poCyD3Or46hTbnTchUyemjNs(an3cEk(8s89K0v(oIrWKCk5d08M1iaHQKTNysrGMLKrAqHqUW3tsxbfUrVrJD0poCyD3Or46hTbnTchUyemjNs(an3cEk(8s89K0LyEcOkmWNhck0o(H7nU)rOpUBSd3H2(Xf00kCJIrWKCk5d08M1iaHQKTNysrGMLKrAqHqUAnCFckCJEJg7OFC4W6UrJW1pAdAAfoCXiysoL8bAEZAeGqvY2tmRGdpJ0GcHC1A4(eu4g9gn2r)4WH1DJgHRF0g00kC4cfddqp9LkFSXqJxpPwBBvAIPbwsEmGwFvx2Xaf3SGHiogpmGjLudhOOzVvFy8M5)qpCHInaOHBVi3a90xQ8DeB6P2m5l1m7yVXJZogO4MfmKMys(an3ts(snZoMqvhkpTleKf85d6UycI4ycvDI4o5J9fkuSh2XzhduCZcgstmjFGM7jjFPMzhtOQdLN2fcYc(8bDxmbrCmHQorCN8X(cfk27H2SJbkUzbdPjMKpqZ9KKVuZSJju1zarEfsSjqHcfB8dB2Xaf3SGH0etYhOz05gRNzhJGj5uYhO5wWtXNxIVNKUeZtavHb(8q(p075igbtYPKpqZTGNIpVeFpjDLVJyemjNs(an7EmaT5QAVgaD(TYb6HlgbtYPKpqZTGNIpVeFpjDjMNaQcd85HwQ(OmjVG8FO3yCHIj5d0Cpj5l1m7ycvDUXR2q(4Iju1HYt7cbzbF(GUlMGioMqvNiUt(yFXWJ7tlaIgGz(TYXlMUiMadiYRqInaiAaMXeQ6mGiVcj2eOy6IyceZs0FehkumSphzhduCZcgstmjFGMrNBSEMDmcMKtjFGMBbpfFEj(Es6k)xmcMKtjFGM7lWdIkmGduKrAqHqUY)fJGj5uYhOz3JbOnxv71aOZ)fkMKpqZ9KKVuZSJju1HYt7cbzbF(GUlMGioMqvNiUt(yFHcf79WMDmqXnlyinXK8bAUNK8LAMDmHQo34vBiF3ftOQdLN2fcYc(8bDxmbrCmHQodiYRqI5vXeQ6eXDYh7luOyoEoYoMKpqZOZnwpZogbtYPKpqZ9f4brfgWbkYinOqix5)IrWKCk5d0S7Xa0MRQ9Aa05)cfduCZcgstmjFGM7jjFPMzhtOQZnE1gYFC)XeQ6q5PDHGSGpFq3ftqehtOQZaI8kKytGIju1jI7Kp2xOqXC8EzhtYhOz05gRNzhJGj5uYhO5wWtXNxIVNKUY)fJGj5uYhO5(c8GOcd4afzKguiKR8FXiysoL8bA29yaAZv1Ena68FHIbkUzbdPjMKpqZ9KKVuZSJju15gVAd5pgxmHQouEAxiil4Zh0DXeeXXeQ6mGiVcjw1MIju1jI7Kp2xOqXC8WMDmjFGMrNBSEMDmcMKtjFGMDpgG2CvTxdGo)xmcMKtjFGM7lWdIkmGduKrAqHqUY)fJGj5uYhO5wWtXNxIVNKUY)fkMKpqZ9KKVuZSJju1HYt7cbzbF(GUlMGioMqvNiUt(yFHcf7H7LDmqXnlyinXK8bAUNK8LAMDmHQouEAxiil4Zh0DXeeXXeQ6eXDYh7luOyyFVSJj5d0m6CJ1ZSJrWKCk5d0Cl4P4ZlX3tsx5)IrWKCk5d0CFbEquHbCGImsdkeYv(VyemjNs(an7EmaT5QAVgaD(VqXK8bAUNK8LAMDmHQorCN8X(Iju15gVAd5pkgPz10t(sT9hKVJxmDrmbgqKxHeBaq0amJju1zarEfsmVkgECFAbq0amZFmAFX0fXeeXXi)byAkI7KMycvDO80UqqwWNpO7IjiIdfd6qAEMDmx(ba9ftrCOyGIBwWqAcfB8Zr2Xaf3SGH0etYhO5EsYxQz2XeQ6CJxTH8hftOQdLN2fcYc(8bDxmbrCmHQodiYRqI5vXeQ6eXDYh7luOyVhUSJbkUzbdPjMKpqZ9KKVuZSJju1HYt7cbzbF(GUlMGioMqvNbe5viX8QycvDI4o5J9fkuS34rzhduCZcgstmjFGM7jjFPMzhtOQdLN2fcYc(8bDxmbrCmHQorCN8X(cfk2dRJSJbkUzbdPjMKpqZ9KKVuZSJju1HYt7cbzbF(GUlMGioMqvNiUt(yFHcf7HwhzhduCZcgstmjFGM7jjFPMzhtOQdLN2fcYc(8bDxmbrCmHQorCN8X(cfk275i7yGIBwWqAIj5d0Cpj5l1m7ycvDO80UqqwWNpO7IjiIJju1jYRY3XlMqvNbe5viX0ScbIju1jI7Kp2xOqXEyhLDmqXnlyinXK8bAUNK8LAMDmHQouEAxiil4Zh0DXeeXXeQ6eXDYh7luOypCoYogO4MfmKMys(an3ts(snZoMqvhkpTleKf85d6UycI4ycvDI4o5J9fkuS3Bu2Xaf3SGH0etYhO5EsYxQz2XeQ6q5PDHGSGpFq3ftqehtOQtKxLVdCXeQ6mGiVcjMMviqmHQorCN8X(cfk243l7yGIBwWqAIj5d0m6CJ1ZSJrWKCk5d0Cl4P4ZlX3tsx57igbtYPKpqZBwJaeQs2EIjfbAwsywXnliFhXiysoL8bAEZAeGqvY2tmRGdpmR4MfKVJqXK8bAUNK8LAMDmHQouEctkPgoqrZ8FOhUycvDO80UqqwWNpO7IjiIJju1jI7K)4xmHQouEc)A6jFPYV)xmHQorEv(JJju15gVAd5pkMqvNbe5viXqJNcfk2d7l7yGIBwWqAIj5d0Cpj5l1m7ycvDO80UqqwWNpO7IjiIJju1jI7Kp2xOqXEJFzhduCZcgstmjFGM7jjFPMzhtOQdLN2fcYc(8bDxmbrCmHQorCN8X(cfk2BSJSJbkUzbdPjMKpqZ9KKVuZSJju1HYt7cbzbF(GUlMGioMqvNiUt(yFHcf7H2x2Xaf3SGH0etYhO5EsYxQz2XeQ6q5PDHGSGpFq3ftqehtOQte3jFSVqHcfJhWGvsyiIdfJWRleRf05e)wR7rHPwhMJP4dIHUfpNEzmUn5Q0XgaTcFqJ(9QzOea",
},
}
function DynamicCam:LoadPreset(defaultName)
-- if there is a preset with this name, then load it into the current profile
if (presets[defaultName]) then
self:ImportIntoCurrentProfile(presets[defaultName].importString);
end
end
function DynamicCam:GetPresets()
local presetList = {};
-- load a table full of the name (the key) and what we want the entry to read
for name, tbl in pairs(presets) do
local entry = string.format("%s (%s)", name, tbl.author);
presetList[name] = entry;
end
return presetList;
end
function DynamicCam:GetPresetDescriptions()
local descriptions = "";
local sep = "";
-- load a table full of the name (the key) and what we want the entry to read
for name, tbl in pairs(presets) do
local entry = string.format("%s|cFFFFFF00%s (%s):|r\n %s", sep, name, tbl.author, tbl.description);
descriptions = descriptions..entry;
sep = "\n\n";
end
return descriptions;
end
|
local sStage = GAMESTATE:GetCurrentStage();
local tRemap = {
Stage_1st = 1,
Stage_2nd = 2,
Stage_3rd = 3,
Stage_4th = 4,
Stage_5th = 5,
Stage_6th = 6,
};
if tRemap[sStage] == PREFSMAN:GetPreference("SongsPerPlay") then
sStage = "Stage_Final";
else
sStage = sStage;
end;
----------------------------------------------------------------------------
return Def.ActorFrame {
Def.Sprite{
InitCommand=cmd(x,SCREEN_CENTER_X;y,SCREEN_CENTER_Y);
OnCommand=function(self)
if GAMESTATE:GetPlayMode() == 'PlayMode_Regular' or GAMESTATE:GetPlayMode() == 'PlayMode_Battle' or GAMESTATE:GetPlayMode() == 'PlayMode_Rave' then
self:Load(THEME:GetPathG("_Stages/ScreenStageInformation", "Stage " .. ToEnumShortString(sStage) ));
elseif GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then
self:Load(THEME:GetPathG("_Stages/ScreenStageInformation", "Stage oni"));
elseif GAMESTATE:GetPlayMode() == 'PlayMode_Nonstop' then
self:Load(THEME:GetPathG("_Stages/ScreenStageInformation", "Stage Nonstop"));
elseif (GAMESTATE:Env()).EndlessState then
self:Load(THEME:GetPathG("_Stages/ScreenStageInformation", "Stage endless"));
end;
self:diffusealpha(0):sleep(0.132)
:linear(0.264):diffusealpha(1);
end;
};
};
|
local keymap = vim.api.nvim_set_keymap
keymap('n', '<leader>gf', '<cmd>lua require"telescope.builtin".find_files()<CR>', {noremap = true})
keymap('n', '<leader>gg', '<cmd>lua require"telescope.builtin".live_grep()<CR>', {noremap = true})
keymap('n', '<leader>gb', '<cmd>lua require"telescope.builtin".buffers()<CR>', {noremap = true})
keymap('n', '<leader>gh', '<cmd>lua require"telescope.builtin".help_tags()<CR>', {noremap = true})
keymap('n', '<leader>gr', '<cmd>lua require"telescope.builtin".registers()<CR>', {noremap = true})
keymap('n', '<leader>gm', '<cmd>lua require"telescope.builtin".man_pages()<CR>', {noremap = true})
keymap('n', '<leader>gk', '<cmd>lua require"telescope.builtin".keymaps()<CR>', {noremap = true})
local actions = require"telescope.actions"
local sorters = require"telescope.sorters"
local previewers = require"telescope.previewers"
require"telescope".setup {
defaults = {
find_command = {"rg", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case" },
prompt_position = "top",
prompt_prefix = " ",
selection_caret = " ",
entry_prefix = " ",
initial_mode = "insert",
selection_strategy = "reset",
sorting_strategy = "descending",
layout_strategy = "horizontal",
layout_defaults = {horizontal = {mirror = false}, vertical = {mirror = false}},
file_sorter = sorters.get_fuzzy_file,
file_ignore_patterns = {},
generic_sorter = sorters.get_generic_fuzzy_sorters,
shortern_path = true,
winbled = 0,
width = 0.75,
preview_cutoff = 120,
result_height = 1,
result_width = 0.8,
border = {},
borderchars = {"─", "│", "─", "│", "┌", "┐", "┘", "└"},
color_devicon = true,
use_less = true,
file_previewer = previewers.vim_buffer_cat.new,
grep_previewer = previewers.vim_buffer_vimgrep.new,
qflist_previewer = previewers.vim_buffer_qflist.new,
mappings = {
i = {
-- replace Ctrl+x to Ctrl+s for split
["<C-x>"] = false,
["<C-s>"] = actions.file_split,
},
n = {
-- replace Ctrl+x to Ctrl+s for split
["<C-x>"] = false,
["<C-s>"] = actions.file_split,
}
}
}
}
|
TOOL.Category = "Wire Extras/RFID"
TOOL.Name = "Reader"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool.wire_rfid_reader_prox.name", "RFID Reader Tool (Wire)" )
language.Add( "Tool.wire_rfid_reader_prox.desc", "Spawns a RFID reader for use with the wire system." )
language.Add( "Tool.wire_rfid_reader_prox.0", "Primary: Create/Update Proximity Reader" )
language.Add( "WireReaderTool_reader_prox", "RFID Reader:" )
language.Add( "WireReaderTool_Range", "Max Range:" )
language.Add( "WireReaderTool_NoColorChg", "Don't change colour on state changed" )
language.Add( "sboxlimit_wire_rfid_reader_proxs", "You've hit readers limit!" )
language.Add( "undone_Wire Reader", "Undone Wire Reader" )
end
if (SERVER) then
CreateConVar('sbox_maxwire_rfid_reader_proxs', 20)
CreateConVar('sbox_wire_rfid_reader_proxs_maxlen', 30)
end
TOOL.ClientConVar[ "Range" ] = 100
TOOL.ClientConVar[ "NoColorChg" ] = 0
TOOL.Model = "models/jaanus/wiretool/wiretool_input.mdl"
cleanup.Register( "wire_rfid_reader_proxs" )
function TOOL:LeftClick( trace )
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if ( CLIENT ) then return true end
local ply = self:GetOwner()
local Range = self:GetClientNumber("Range")
local NoColorChg = (self:GetClientNumber("NoColorChg")!=0)
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_rfid_reader_prox" && trace.Entity:GetTable().pl == ply ) then
trace.Entity:Setup( Range, NoColorChg )
return true
end
if ( !self:GetSWEP():CheckLimit( "wire_rfid_reader_proxs" ) ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local wire_rfid_reader_prox = MakeWireReader( ply, trace.HitPos, Range, NoColorChg, Ang )
local min = wire_rfid_reader_prox:OBBMins()
wire_rfid_reader_prox:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_rfid_reader_prox, trace.Entity, trace.PhysicsBone, true)
undo.Create("Wire Reader")
undo.AddEntity( wire_rfid_reader_prox )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_rfid_reader_proxs", wire_rfid_reader_prox )
return true
end
function TOOL:RightClick( trace )
return false
end
if (SERVER) then
function MakeWireReader( pl, Pos, Range, NoColorChg, Ang )
if ( !pl:CheckLimit( "wire_rfid_reader_proxs" ) ) then return false end
local wire_rfid_reader_prox = ents.Create( "gmod_wire_rfid_reader_prox" )
if (!wire_rfid_reader_prox:IsValid()) then return false end
wire_rfid_reader_prox:SetAngles( Ang )
wire_rfid_reader_prox:SetPos( Pos )
wire_rfid_reader_prox:SetModel( Model("models/jaanus/wiretool/wiretool_input.mdl") )
wire_rfid_reader_prox:Spawn()
wire_rfid_reader_prox:Setup(Range,NoColorChg)
wire_rfid_reader_prox:SetPlayer( pl )
local ttable = {
Range = Range,
NoColorChg = NoColorChg,
pl = pl
}
table.Merge(wire_rfid_reader_prox:GetTable(), ttable )
pl:AddCount( "wire_rfid_reader_proxs", wire_rfid_reader_prox )
return wire_rfid_reader_prox
end
duplicator.RegisterEntityClass("gmod_wire_rfid_reader_prox", MakeWireReader, "Pos", "Range", "NoColorChg", "Ang", "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostWireReader( ent, player )
if ( !ent || !ent:IsValid() ) then return end
local tr = util.GetPlayerTrace( player, player:GetAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_rfid_reader_prox" ) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then
self:MakeGhostEntity( self.Model, Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostWireReader( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_rfid_reader_prox.name", Description = "#Tool.wire_rfid_reader_prox.desc" })
panel:AddControl("ComboBox", {
Label = "#Presets",
MenuButton = "1",
Folder = "wire_rfid_reader_prox",
Options = {
Default = {
wire_rfid_reader_prox_reader_prox = "0",
}
},
CVars = {
}
})
panel:AddControl("Slider", {
Label = "#WireReaderTool_Range",
Type = "Float",
Min = "1",
Max = "10000",
Command = "wire_rfid_reader_prox_Range"
})
panel:AddControl("CheckBox", {
Label = "#WireReaderTool_NoColorChg",
Command = "wire_rfid_reader_prox_NoColorChg"
})
end
|
local config = {
profile = {
logo = "logo",
name = "Simon Weizman",
headline = "Computer Science Student at University of Central Florida | SWE Intern at SavvySuit",
email = "contact@simon.weizman.us",
website = "simon.weizman.dev",
git = "gitlab.com/torrentofshame",
location = "Orlando, Florida, US"
},
summary = [[
I'm a passionate, resourceful, and self-taught developer and an undergraduate student of Computer Science at UCF.
I decided to take on freelance development as a way to further my abilities and solve niche problems that I wouldn't be able to find elsewhere.
]], -- nil causes lipsum[1][1-2]
experience = {
{
jobTitle = "Software Engineering Intern",
organization = "SavvySuit",
startDate = "Mar 2021",
endDate = nil,
location = "Orlando, FL",
description = {
"Work on an offline-first, ADA compliant progressive web app that assists disabilities living in locations with poor internet.",
"Architected a dynamic form configuration system using yaml, Formik, and React that allows for the easy configuration of forms that validate user input and automatically add more fields depending on user input.",
"Manipulate local data, enable offline and cloud synchronization using Amplify DataStore in the frontend",
"Implement data conflict resolution, versioning and journaling using AWS AppSync with DynamoDB in the backend"
}
},
{
jobTitle = "Freelance Developer",
organization = "Upwork",
startDate = "Mar 2021",
endDate = nil,
location = "Remote/Virtual",
description = {
"Working closely with clients to create custom scripts and modify pre-existing code."
}
},
{
jobTitle = "DevOps Lead",
organization = "Knight Hacks",
startDate = "Aug 2021",
endDate = "Nov 2021",
location = "Remote/Virtual",
description = {
"Deployed and managed our applications running on a combination of Kubernetes, Azure, and Cloudflare.",
"Built, maintained, and scaled infrastructure for production and staging environments.",
"Used GitHub Actions to automate testing and deployment to production and staging environments.",
"Oversaw the implementation of automated performance measurement reporting and error monitoring.",
"Developed automated pipelines for creating and deploying new releases using semver and GitHub Actions."
}
},
{
jobTitle = "Back End Developer",
organization = "Knight Hacks",
startDate = "Feb 2021",
endDate = "Nov 2021",
location = "Remote/Virtual",
description = {
"Worked in a team of 6 people using Flask and MongoDB to create tools for student hackathons.",
"Used Agile Methodology in the team.",
"Collaborated with front end and mobile teams to ensure the quality of the final product.",
"Designed and maintained unit tests in collaboration with team members to ensure code quality.",
"Architected the initial boilerplate code.",
"Assisted in deployment using GitHub Actions, Kubernetes, and Nginx.",
"Built and deployed various hotfixes and last-minute changes to the backend."
}
},
{
jobTitle = "Volunteer Lua Developer",
organization = "Innovative Gamers",
startDate = "Mar 2019",
endDate = "Feb 2020",
location = "Remote/Virtual",
description = {
"Developed a player management system utilizing an SQL database which enhanced the player experience and assisted in managing the player hierarchy.",
"Designed custom UI that integrated existing features to assist players and staff in managing characters and the server.",
"Cooperated with staff and players to increase player retention during down-time by 50\\%.",
"Documented the steps necessary to configure the different features on the server.",
"Maintained and managed the server's code and database."
}
},
{
jobTitle = "Summer Camp Counselor",
organization = "Peg Camp",
startDate = "Jul 2019",
endDate = "Aug 2019",
location = "South Broward High School",
description = {
"Part of a team of counselors, whose goal was to create a safe and fun environment where kids can learn about up-to-date technology in video game design, engineering, coding, and computer graphics.",
"Taught multiple computer programs to children at the beginning, intermediate, and advanced levels, including: Python and Tinker CAD.",
"Supported campers through the learning process ensuring a fun and successful experience."
}
}
},
projects = {
{
name = "LuaLaTeX Resume",
startDate = "Nov 2020",
endDate = nil,
shortDescription = "My resume that I made in LuaLaTeX, that is generated from information saved in a config file."
},
{
name = "Personal Website",
startDate = "Nov 2018",
endDate = nil,
shortDescription = "Created using Node.js with React and React-Bootstrap."
},
{
name = "Web Email Client",
startDate = "Jul 2020",
endDate = nil,
shortDescription = "A custom Webmail client created with Node.js, Express.js, and Pug.js"
},
{
name = "Back-end for Knight Hacks",
startDate = "Feb 2021",
endDate = "Nov 2021",
shortDescription = "The back-end for Knight Hacks, built with Flask and deployed on AKS."
},
{
name = "Personal Homelab Server",
startDate = "Mar 2018",
endDate = "Jul 2020",
shortDescription = "I owned, maintained, and administered an old Dell Poweredge R710 that I used to learn about virtualization, DevOps and server management"
},
{
name = "Why don't people format their numbers browser extension",
startDate = "Sep 2020",
endDate = "Sep 2020",
shortDescription = "A very small and simple Google Chrome browser extension using JavaScript to help me read large, especially unformatted numbers."
},
},
skills = {
{
categoryName = "Programming Languages",
items = {
"HTML",
"CSS",
"SASS",
"LESS",
"JavaScript",
"TypeScript",
"Python",
"Lua",
"LaTeX",
"C",
"Java"
}
},
{
categoryName = "Frontend",
items = {
"React.js",
"React Native",
"Bootstrap",
"jQuery",
"Webpack",
"Next.js",
"PWAs"
}
},
{
categoryName = "Backend",
items = {
"Node.js",
"REST API",
"JWT",
"OAuth",
"CDN",
"Flask",
"Express.js",
"Celery"
}
},
{
categoryName = "Databases",
items = {
"MongoDB",
"PostgreSQL",
"MariaDB",
"MySQL",
"SQLite",
"DynamoDB"
}
},
{
categoryName = "Tools & Technologies",
items = {
"MERN",
"Git",
"Nginx",
"Docker",
"CI/CD",
"DNS",
"Prometheus",
"Grafana",
"Digital Ocean",
"Kubernetes",
"AWS",
"Linux",
"Vim"
}
}
},
education = {
{
degree = "Computer Science BS",
institution = "University of Central Florida",
startDate = "Jul 2020",
endDate = "Dec 2023"
},
{
degree = "High School Diploma",
institution = "South Broward High School",
startDate = "Aug 2016",
endDate = "May 2020"
}
},
certifications = {
{
name = "CompTIA Security+ ce",
issuer = "CompTIA",
issueDate = "Dec 2021",
expireDate = "Dec 2024",
logo = "comptia-security-ce-certification"
},
{
name = "Autodesk Inventor Certified User",
issuer = "Autodesk",
issueDate = "May 2020",
expireDate = nil,
logo = "autodesk-inventor-certified-user"
},
{
name = "Autodesk AutoCAD Certified User",
issuer = "Autodesk",
issueDate = "Feb 2020",
expireDate = nil,
logo = "autodesk-autocad-certified-user"
},
{
name = "AutoCAD Certified Professional",
issuer = "Autodesk",
issueDate = "Jun 2020",
expireDate = "Jun 2023",
logo = "autocad-certified-professional"
}
},
languages = nil
}
return config
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "RFID Reader"
local MODEL = Model("models/jaanus/wiretool/wiretool_input.mdl")
function ENT:Initialize()
self:SetModel( MODEL )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Outputs = Wire_CreateOutputs(self, { "State", "A", "B", "C", "D" })
self.MaxRange=100
self.A=0
self.B=0
self.C=0
self.D=0
self.State=0
self.NoColorChg=false
Wire_TriggerOutput(self,"State",0)
Wire_TriggerOutput(self,"A",0)
Wire_TriggerOutput(self,"B",0)
Wire_TriggerOutput(self,"C",0)
Wire_TriggerOutput(self,"D",0)
self:ShowOutput(0,0,0,0,0)
end
function ENT:OnRemove()
Wire_Remove(self)
end
function ENT:Setup(Range,col)
self.MaxRange=Range
self.NoColorChg=col
end
function ENT:Think()
self.BaseClass.Think(self)
local ent = nil
local mypos = self:GetPos()
local mindist = -1
for _,contact in pairs(ents.FindInSphere(self:GetPos(), self.MaxRange or 10)) do
if contact.__RFID_HASRFID then
ent=contact;
local dist = (contact:GetPos() - mypos):Length()
if (mindist<0 or dist<mindist) then
mindist = dist
ent=contact
end
end
end
if (!ent) then
if(self.State!=0)then
if !self.NoColorChg then self:SetColor(Color(255, 255, 255, 255)) end
Wire_TriggerOutput(self,"State",0) self.State=0
Wire_TriggerOutput(self,"A",0) self.A=0
Wire_TriggerOutput(self,"B",0) self.B=0
Wire_TriggerOutput(self,"C",0) self.C=0
Wire_TriggerOutput(self,"D",0) self.D=0
self:ShowOutput(0,0,0,0,0)
end
return false
end
if !self.NoColorChg then self:SetColor(Color(0, 255, 0, 255)) end
Wire_TriggerOutput(self,"State",1) self.State=1
Wire_TriggerOutput(self,"A",ent.__RFID_A) self.A=ent.__RFID_A
Wire_TriggerOutput(self,"B",ent.__RFID_B) self.B=ent.__RFID_B
Wire_TriggerOutput(self,"C",ent.__RFID_C) self.C=ent.__RFID_C
Wire_TriggerOutput(self,"D",ent.__RFID_D) self.D=ent.__RFID_D
self:ShowOutput(self.State, self.A, self.B, self.C, self.D)
self:NextThink(CurTime()+0.125)
end
function ENT:ShowOutput(s,a,b,c,d)
txt = "RFID Reader\n"
if s==0 then
txt=txt.."No object found"
else
txt=txt.."Reading\nA="..a..";B="..b..";C="..c..";D="..d
end
self:SetOverlayText( txt )
end
function ENT:OnRestore()
Wire_Restored(self)
end |
function openURL(w, h, title, url)
Frame = vgui.Create( "DFrame" );
Frame:SetTitle( title );
Frame:SetSize( w, h + 24 );
Panel = vgui.Create( "DPanel", Frame );
Panel:SetPos( 0, 24 );
Panel:SetSize( w, h + 24 );
HTML = vgui.Create( "HTML", Panel );
HTML:SetPos( 0, 0 );
HTML:SetSize( w, h );
HTML:OpenURL( url );
Frame:Center();
Frame:MakePopup();
end
--Receive MSS.GUI and display the URL provided by the server
net.Receive( "mss.url", function()
print("[MSS URL] Data recieved!")
local w = net.ReadInt(16)
local h = net.ReadInt(16)
local title = net.ReadString()
local url = net.ReadString()
openURL(w, h, title, url)
end )
|
require('nn')
require('rnn')
----------------------------------------------------------------------
-- parse command line arguments
if not opt then
print '==> processing options'
cmd = torch.CmdLine()
cmd:text()
cmd:text('Bi-Directional LSTM')
cmd:text()
cmd:text('Options:')
cmd:option('-model_type', 'bi-lstm', 'the type of model: bi-lm | bi-lstm | lstm')
cmd:option('-input_dim', 9, 'the input size')
cmd:option('-output_dim', 2, 'the output size')
cmd:option('-hidden_size', 100, 'the hidden size')
cmd:option('-dropout', 0.3, 'dropout rate')
cmd:text()
opt = cmd:parse(arg or {})
end
----------------------------------------------------------------------
if opt.model_type == 'bi-lm' then
-- forward rnn
-- build simple recurrent neural network
fwd = nn.Recurrent(
opt.hidden_size, nn.LookupTable(opt.input_dim, opt.hidden_size),
nn.Linear(opt.hidden_size, opt.hidden_size), nn.Tanh(),
rho
)
-- backward rnn (will be applied in reverse order of input sequence)
bwd = fwd:clone()
bwd:reset() -- reinitializes parameters
-- merges the output of one time-step of fwd and bwd rnns.
-- You could also try nn.AddTable(), nn.Identity(), etc.
merge = nn.JoinTable(1, 1)
-- we use BiSequencerLM because this is a language model (previous and next words to predict current word).
-- If we used BiSequencer, x[t] would be used to predict y[t] = x[t] (which is cheating).
-- Note that bwd and merge argument are optional and will default to the above.
brnn = nn.BiSequencerLM(fwd, bwd, merge)
rnn = nn.Sequential()
:add(brnn)
:add(nn.Sequencer(nn.Linear(2*opt.hidden_size, opt.output_dim))) -- times two due to JoinTable
:add(nn.Sequencer(nn.LogSoftMax()))
elseif opt.model_type == 'bi-lstm' then
-- forward rnn
-- build LSTM based rnn
fwd = nn.FastLSTM(opt.input_dim, opt.hidden_size)
-- backward rnn (will be applied in reverse order of input sequence)
bwd = fwd:clone()
bwd:reset() -- reinitializes parameters
-- merges the output of one time-step of fwd and bwd rnns.
-- You could also try nn.AddTable(), nn.Identity(), etc.
merge = nn.JoinTable(1, 1)
-- merge = nn.CSubTable()
-- build the bidirectional lstm
brnn = nn.BiSequencer(fwd, bwd, merge)
rnn = nn.Sequential()
:add(brnn)
:add(nn.Sequencer(nn.Dropout(opt.dropout)))
:add(nn.Sequencer(nn.Linear(2*opt.hidden_size, opt.output_dim))) -- times two due to JoinTable
--:add(nn.Sequencer(nn.Linear(opt.hidden_size, opt.output_dim))) -- 1 time due to CSubTable
:add(nn.Sequencer(nn.LogSoftMax()))
elseif opt.model_type == 'lstm' then
--- SINGLE LAYER ---
-- forward rnn
-- build simple recurrent neural network
--[[fwd_1 = nn.FastLSTM(opt.input_dim, opt.hidden_size)
s_rnn_1 = nn.Sequencer(fwd_1)
rnn = nn.Sequential()
:add(s_rnn_1)
:add(nn.Sequencer(nn.Dropout(opt.dropout)))
:add(nn.Sequencer(nn.Linear(opt.hidden_size, opt.output_dim)))
:add(nn.Sequencer(nn.LogSoftMax()))]]--
--- TWO LAYERS ---
-- forward rnn
-- build simple recurrent neural network
fwd_1 = nn.FastLSTM(opt.input_dim, opt.hidden_size)
fwd_2 = nn.FastLSTM(opt.hidden_size, opt.hidden_size)
s_rnn_1 = nn.Sequencer(fwd_1)
s_rnn_2 = nn.Sequencer(fwd_2)
rnn = nn.Sequential()
:add(s_rnn_1)
:add(nn.Sequencer(nn.Dropout(opt.dropout)))
:add(s_rnn_2)
:add(nn.Sequencer(nn.Dropout(opt.dropout)))
:add(nn.Sequencer(nn.Linear(opt.hidden_size, opt.output_dim)))
:add(nn.Sequencer(nn.LogSoftMax()))
end
-- print the model
print(rnn) |
local M = {}
function M.get_file_name()
return vim.api.nvim_buf_get_name(0)
end
function M.table_contains(table, key)
return table[key] ~= nil
end
return M
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
|
LoginWechatCcsView = class("LoginWechatCcsView")
LoginWechatCcsView.onCreationComplete = function (slot0)
ClassUtil.extends(slot0, ZoomPopUpChildView, true, slot0, slot0.bg, slot0.view)
slot0._inputWxGzh = CCSUtil.changeUITextFeildWithCcsTextInput(slot0.view.inputWechat)
end
LoginWechatCcsView.onZoomShowTweenComplete = function (slot0)
ZoomPopUpChildView.onZoomShowTweenComplete(slot0)
slot0._inputWxGzh:show()
end
LoginWechatCcsView.hide = function (slot0, slot1, slot2)
ZoomPopUpChildView.hide(slot0, slot1, slot2)
slot0.model:setValidateSmsCode("")
slot0._inputWxGzh:setText("")
slot0._inputWxGzh:hide()
end
LoginWechatCcsView.onBtnClick = function (slot0, slot1, slot2)
if slot1 == slot0.view.btnClose then
slot0.model:setIsLoginWechatShowing(false)
elseif slot1 == slot0.view.btnConfirm then
slot0.controller:requestValidateWechat(slot0._inputWxGzh:getText())
end
end
LoginWechatCcsView.destroy = function (slot0)
destroySomeObj(slot0._inputWxGzh)
destroySomeObj(slot0.view.btnClose)
ZoomPopUpChildView.destroy(slot0)
end
return
|
--- Turbo.lua Github Feed
--
-- Copyright 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- This implementation uses the Github REST API to pull current amount of
-- watchers for the Turbo.lua repository.
TURBO_SSL = true -- Enable SSL as Github API requires HTTPS.
local turbo = require "turbo"
local yield = coroutine.yield
local GithubFeed = class("GithubFeed", turbo.web.RequestHandler)
function GithubFeed:get(search)
local res = yield(
turbo.async.HTTPClient():fetch("https://api.github.com/repos/kernelsauce/turbo"))
if res.error or res.headers:get_status_code() ~= 200 then
-- Check for errors.
-- If data could not be fetched a 500 error is sent as response.
error(turbo.web.HTTPError:new(500, res.error.message))
end
local json = turbo.escape.json_decode(res.body)
-- Ugly inlining of HTML code. You get the point!
self:write([[<html><head></head><body>]])
self:write(string.format(
[[
<h1>Turbo.lua Github feed<h1>
<p>Current watchers %d</p>
]],
json.watchers_count
))
self:write([[</body></html>]])
end
local application = turbo.web.Application:new({
{"^/$", GithubFeed}
})
application:listen(8888)
turbo.ioloop.instance():start()
|
SB.Include(SB_VIEW_FIELDS_DIR .. "field.lua")
FunctionField = Field:extends{}
-- FIXME: sources is ignored
function FunctionField:init(field)
self:__SetDefault("width", 200)
Field.init(self, field)
self.btnFunction = Button:New {
caption = "Function",
width = self.width,
height = self.height,
OnClick = {
function()
local mode = 'add'
if self.value then
mode = 'edit'
end
local functionWindow = FunctionWindow({
mode = mode,
dataType = self.dataType,
element = self.value,
trigger = self.trigger,
params = self.params,
OnConfirm = {
function(element)
self:Set(element)
end
},
})
--SB.MakeWindowModal(customWindow.window, self.parent.parent.parent)
-- SB.MakeWindowModal(functionWindow.window, self.parent)
end
},
}
self.components = {
self.btnFunction
}
end
-- Function window class
FunctionWindow = AbstractTriggerElementWindow:extends{}
function FunctionWindow:init(opts)
self.dataType = opts.dataType
AbstractTriggerElementWindow.init(self, opts)
end
-- TODO: Checking if input types are equivalent should be removed to a
-- meta-programming utility file.
local function isMatch(inputTypes1, inputTypes2)
if #inputTypes1 ~= #inputTypes2 then
return false
end
local isMatched2 = {} -- index mapping of inputs already used in the matching
for _, inputType1 in pairs(inputTypes1) do
local matched1 = true
for i, inputType2 in pairs(inputTypes2) do
if not isMatched2[i] then
if inputType1.type == inputType2.type then
isMatched2[i] = true
matched1 = true
break
end
end
end
if not matched1 then
return false
end
end
return false
end
function FunctionWindow:GetValidElementTypes()
local validFunctionTypes = {}
local functionTypes
if self.dataType.type == "function" then
-- If specified, Filter based on matching output data types.
if self.dataType.output then
functionTypes = SB.metaModel.functionTypesByOutput[self.dataType.output]
else
functionTypes = SB.metaModel.functionTypes
end
-- FIXME: things might need cleanup for well designed action support
elseif self.dataType.type == "action" then
functionTypes = SB.metaModel.actionTypes
else
Log.Error("Unexeptected data type: " .. tostring(self.dataType.type))
end
-- If specified, Filter based on matching input data types.
if self.dataType.input ~= nil then
for _, functionType in pairs(functionTypes) do
if isMatch(functionType.input, self.dataType.input) then
table.insert(validFunctionTypes, functionType)
end
end
else
validFunctionTypes = functionTypes
end
return validFunctionTypes
end
function FunctionWindow:GetWindowCaption()
-- FIXME: better function display if possible
if self.mode == 'add' then
return "New function"
elseif self.mode == 'edit' then
return "Edit function"
end
end
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BossInfo_pb', package.seeall)
local POINT = protobuf.Descriptor();
local POINT_X_FIELD = protobuf.FieldDescriptor();
local POINT_Y_FIELD = protobuf.FieldDescriptor();
local BOSSREWARD = protobuf.Descriptor();
local BOSSREWARD_HARDMODE_FIELD = protobuf.FieldDescriptor();
local BOSSREWARD_GIFTS_FIELD = protobuf.FieldDescriptor();
local BOSSINFO = protobuf.Descriptor();
local BOSSINFO_ID_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_BOSSID_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_NAME_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_TITLE_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_TARGET_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_MAPID_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_DESC_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_LEVEL_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_ATTACK_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_DEFEND_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_AGILITY_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_LUCKY_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_THEW_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_BLOOD_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_DAMAGE_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_SKIN_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_POWER_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_BOSSTYPE_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_TOTALROUND_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_GIFTS_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_WIDTH_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_HEIGHT_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_BEGINTIME_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_ENDTIME_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_STATUS_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_CHALLCOUNT_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_TOTALUSER_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_PROGRESS_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_TOTALPROGRESS_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_CONDITION_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_MEETCOND_FIELD = protobuf.FieldDescriptor();
local BOSSINFO_REWARD_FIELD = protobuf.FieldDescriptor();
POINT_X_FIELD.name = "x"
POINT_X_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Point.x"
POINT_X_FIELD.number = 1
POINT_X_FIELD.index = 0
POINT_X_FIELD.label = 2
POINT_X_FIELD.has_default_value = false
POINT_X_FIELD.default_value = 0
POINT_X_FIELD.type = 13
POINT_X_FIELD.cpp_type = 3
POINT_Y_FIELD.name = "y"
POINT_Y_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.Point.y"
POINT_Y_FIELD.number = 2
POINT_Y_FIELD.index = 1
POINT_Y_FIELD.label = 2
POINT_Y_FIELD.has_default_value = false
POINT_Y_FIELD.default_value = 0
POINT_Y_FIELD.type = 13
POINT_Y_FIELD.cpp_type = 3
POINT.name = "Point"
POINT.full_name = ".com.xinqihd.sns.gameserver.proto.Point"
POINT.nested_types = {}
POINT.enum_types = {}
POINT.fields = {POINT_X_FIELD, POINT_Y_FIELD}
POINT.is_extendable = false
POINT.extensions = {}
BOSSREWARD_HARDMODE_FIELD.name = "hardmode"
BOSSREWARD_HARDMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossReward.hardmode"
BOSSREWARD_HARDMODE_FIELD.number = 1
BOSSREWARD_HARDMODE_FIELD.index = 0
BOSSREWARD_HARDMODE_FIELD.label = 1
BOSSREWARD_HARDMODE_FIELD.has_default_value = false
BOSSREWARD_HARDMODE_FIELD.default_value = ""
BOSSREWARD_HARDMODE_FIELD.type = 9
BOSSREWARD_HARDMODE_FIELD.cpp_type = 9
BOSSREWARD_GIFTS_FIELD.name = "gifts"
BOSSREWARD_GIFTS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossReward.gifts"
BOSSREWARD_GIFTS_FIELD.number = 22
BOSSREWARD_GIFTS_FIELD.index = 1
BOSSREWARD_GIFTS_FIELD.label = 3
BOSSREWARD_GIFTS_FIELD.has_default_value = false
BOSSREWARD_GIFTS_FIELD.default_value = {}
BOSSREWARD_GIFTS_FIELD.message_type = GIFT_PB_GIFT
BOSSREWARD_GIFTS_FIELD.type = 11
BOSSREWARD_GIFTS_FIELD.cpp_type = 10
BOSSREWARD.name = "BossReward"
BOSSREWARD.full_name = ".com.xinqihd.sns.gameserver.proto.BossReward"
BOSSREWARD.nested_types = {}
BOSSREWARD.enum_types = {}
BOSSREWARD.fields = {BOSSREWARD_HARDMODE_FIELD, BOSSREWARD_GIFTS_FIELD}
BOSSREWARD.is_extendable = false
BOSSREWARD.extensions = {}
BOSSINFO_ID_FIELD.name = "id"
BOSSINFO_ID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.id"
BOSSINFO_ID_FIELD.number = 1
BOSSINFO_ID_FIELD.index = 0
BOSSINFO_ID_FIELD.label = 2
BOSSINFO_ID_FIELD.has_default_value = false
BOSSINFO_ID_FIELD.default_value = ""
BOSSINFO_ID_FIELD.type = 9
BOSSINFO_ID_FIELD.cpp_type = 9
BOSSINFO_BOSSID_FIELD.name = "bossid"
BOSSINFO_BOSSID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.bossid"
BOSSINFO_BOSSID_FIELD.number = 2
BOSSINFO_BOSSID_FIELD.index = 1
BOSSINFO_BOSSID_FIELD.label = 2
BOSSINFO_BOSSID_FIELD.has_default_value = false
BOSSINFO_BOSSID_FIELD.default_value = ""
BOSSINFO_BOSSID_FIELD.type = 9
BOSSINFO_BOSSID_FIELD.cpp_type = 9
BOSSINFO_NAME_FIELD.name = "name"
BOSSINFO_NAME_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.name"
BOSSINFO_NAME_FIELD.number = 3
BOSSINFO_NAME_FIELD.index = 2
BOSSINFO_NAME_FIELD.label = 2
BOSSINFO_NAME_FIELD.has_default_value = false
BOSSINFO_NAME_FIELD.default_value = ""
BOSSINFO_NAME_FIELD.type = 9
BOSSINFO_NAME_FIELD.cpp_type = 9
BOSSINFO_TITLE_FIELD.name = "title"
BOSSINFO_TITLE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.title"
BOSSINFO_TITLE_FIELD.number = 4
BOSSINFO_TITLE_FIELD.index = 3
BOSSINFO_TITLE_FIELD.label = 2
BOSSINFO_TITLE_FIELD.has_default_value = false
BOSSINFO_TITLE_FIELD.default_value = ""
BOSSINFO_TITLE_FIELD.type = 9
BOSSINFO_TITLE_FIELD.cpp_type = 9
BOSSINFO_TARGET_FIELD.name = "target"
BOSSINFO_TARGET_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.target"
BOSSINFO_TARGET_FIELD.number = 5
BOSSINFO_TARGET_FIELD.index = 4
BOSSINFO_TARGET_FIELD.label = 2
BOSSINFO_TARGET_FIELD.has_default_value = false
BOSSINFO_TARGET_FIELD.default_value = ""
BOSSINFO_TARGET_FIELD.type = 9
BOSSINFO_TARGET_FIELD.cpp_type = 9
BOSSINFO_MAPID_FIELD.name = "mapId"
BOSSINFO_MAPID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.mapId"
BOSSINFO_MAPID_FIELD.number = 6
BOSSINFO_MAPID_FIELD.index = 5
BOSSINFO_MAPID_FIELD.label = 2
BOSSINFO_MAPID_FIELD.has_default_value = false
BOSSINFO_MAPID_FIELD.default_value = ""
BOSSINFO_MAPID_FIELD.type = 9
BOSSINFO_MAPID_FIELD.cpp_type = 9
BOSSINFO_DESC_FIELD.name = "desc"
BOSSINFO_DESC_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.desc"
BOSSINFO_DESC_FIELD.number = 7
BOSSINFO_DESC_FIELD.index = 6
BOSSINFO_DESC_FIELD.label = 2
BOSSINFO_DESC_FIELD.has_default_value = false
BOSSINFO_DESC_FIELD.default_value = ""
BOSSINFO_DESC_FIELD.type = 9
BOSSINFO_DESC_FIELD.cpp_type = 9
BOSSINFO_LEVEL_FIELD.name = "level"
BOSSINFO_LEVEL_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.level"
BOSSINFO_LEVEL_FIELD.number = 8
BOSSINFO_LEVEL_FIELD.index = 7
BOSSINFO_LEVEL_FIELD.label = 2
BOSSINFO_LEVEL_FIELD.has_default_value = false
BOSSINFO_LEVEL_FIELD.default_value = 0
BOSSINFO_LEVEL_FIELD.type = 13
BOSSINFO_LEVEL_FIELD.cpp_type = 3
BOSSINFO_ATTACK_FIELD.name = "attack"
BOSSINFO_ATTACK_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.attack"
BOSSINFO_ATTACK_FIELD.number = 10
BOSSINFO_ATTACK_FIELD.index = 8
BOSSINFO_ATTACK_FIELD.label = 2
BOSSINFO_ATTACK_FIELD.has_default_value = false
BOSSINFO_ATTACK_FIELD.default_value = 0
BOSSINFO_ATTACK_FIELD.type = 13
BOSSINFO_ATTACK_FIELD.cpp_type = 3
BOSSINFO_DEFEND_FIELD.name = "defend"
BOSSINFO_DEFEND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.defend"
BOSSINFO_DEFEND_FIELD.number = 11
BOSSINFO_DEFEND_FIELD.index = 9
BOSSINFO_DEFEND_FIELD.label = 2
BOSSINFO_DEFEND_FIELD.has_default_value = false
BOSSINFO_DEFEND_FIELD.default_value = 0
BOSSINFO_DEFEND_FIELD.type = 13
BOSSINFO_DEFEND_FIELD.cpp_type = 3
BOSSINFO_AGILITY_FIELD.name = "agility"
BOSSINFO_AGILITY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.agility"
BOSSINFO_AGILITY_FIELD.number = 12
BOSSINFO_AGILITY_FIELD.index = 10
BOSSINFO_AGILITY_FIELD.label = 2
BOSSINFO_AGILITY_FIELD.has_default_value = false
BOSSINFO_AGILITY_FIELD.default_value = 0
BOSSINFO_AGILITY_FIELD.type = 13
BOSSINFO_AGILITY_FIELD.cpp_type = 3
BOSSINFO_LUCKY_FIELD.name = "lucky"
BOSSINFO_LUCKY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.lucky"
BOSSINFO_LUCKY_FIELD.number = 13
BOSSINFO_LUCKY_FIELD.index = 11
BOSSINFO_LUCKY_FIELD.label = 2
BOSSINFO_LUCKY_FIELD.has_default_value = false
BOSSINFO_LUCKY_FIELD.default_value = 0
BOSSINFO_LUCKY_FIELD.type = 13
BOSSINFO_LUCKY_FIELD.cpp_type = 3
BOSSINFO_THEW_FIELD.name = "thew"
BOSSINFO_THEW_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.thew"
BOSSINFO_THEW_FIELD.number = 14
BOSSINFO_THEW_FIELD.index = 12
BOSSINFO_THEW_FIELD.label = 2
BOSSINFO_THEW_FIELD.has_default_value = false
BOSSINFO_THEW_FIELD.default_value = 0
BOSSINFO_THEW_FIELD.type = 13
BOSSINFO_THEW_FIELD.cpp_type = 3
BOSSINFO_BLOOD_FIELD.name = "blood"
BOSSINFO_BLOOD_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.blood"
BOSSINFO_BLOOD_FIELD.number = 15
BOSSINFO_BLOOD_FIELD.index = 13
BOSSINFO_BLOOD_FIELD.label = 2
BOSSINFO_BLOOD_FIELD.has_default_value = false
BOSSINFO_BLOOD_FIELD.default_value = 0
BOSSINFO_BLOOD_FIELD.type = 13
BOSSINFO_BLOOD_FIELD.cpp_type = 3
BOSSINFO_DAMAGE_FIELD.name = "damage"
BOSSINFO_DAMAGE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.damage"
BOSSINFO_DAMAGE_FIELD.number = 16
BOSSINFO_DAMAGE_FIELD.index = 14
BOSSINFO_DAMAGE_FIELD.label = 2
BOSSINFO_DAMAGE_FIELD.has_default_value = false
BOSSINFO_DAMAGE_FIELD.default_value = 0
BOSSINFO_DAMAGE_FIELD.type = 13
BOSSINFO_DAMAGE_FIELD.cpp_type = 3
BOSSINFO_SKIN_FIELD.name = "skin"
BOSSINFO_SKIN_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.skin"
BOSSINFO_SKIN_FIELD.number = 17
BOSSINFO_SKIN_FIELD.index = 15
BOSSINFO_SKIN_FIELD.label = 2
BOSSINFO_SKIN_FIELD.has_default_value = false
BOSSINFO_SKIN_FIELD.default_value = 0
BOSSINFO_SKIN_FIELD.type = 13
BOSSINFO_SKIN_FIELD.cpp_type = 3
BOSSINFO_POWER_FIELD.name = "power"
BOSSINFO_POWER_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.power"
BOSSINFO_POWER_FIELD.number = 18
BOSSINFO_POWER_FIELD.index = 16
BOSSINFO_POWER_FIELD.label = 2
BOSSINFO_POWER_FIELD.has_default_value = false
BOSSINFO_POWER_FIELD.default_value = 0
BOSSINFO_POWER_FIELD.type = 13
BOSSINFO_POWER_FIELD.cpp_type = 3
BOSSINFO_BOSSTYPE_FIELD.name = "bosstype"
BOSSINFO_BOSSTYPE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.bosstype"
BOSSINFO_BOSSTYPE_FIELD.number = 20
BOSSINFO_BOSSTYPE_FIELD.index = 17
BOSSINFO_BOSSTYPE_FIELD.label = 1
BOSSINFO_BOSSTYPE_FIELD.has_default_value = true
BOSSINFO_BOSSTYPE_FIELD.default_value = 0
BOSSINFO_BOSSTYPE_FIELD.type = 13
BOSSINFO_BOSSTYPE_FIELD.cpp_type = 3
BOSSINFO_TOTALROUND_FIELD.name = "totalround"
BOSSINFO_TOTALROUND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.totalround"
BOSSINFO_TOTALROUND_FIELD.number = 21
BOSSINFO_TOTALROUND_FIELD.index = 18
BOSSINFO_TOTALROUND_FIELD.label = 1
BOSSINFO_TOTALROUND_FIELD.has_default_value = true
BOSSINFO_TOTALROUND_FIELD.default_value = 0
BOSSINFO_TOTALROUND_FIELD.type = 13
BOSSINFO_TOTALROUND_FIELD.cpp_type = 3
BOSSINFO_GIFTS_FIELD.name = "gifts"
BOSSINFO_GIFTS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.gifts"
BOSSINFO_GIFTS_FIELD.number = 22
BOSSINFO_GIFTS_FIELD.index = 19
BOSSINFO_GIFTS_FIELD.label = 3
BOSSINFO_GIFTS_FIELD.has_default_value = false
BOSSINFO_GIFTS_FIELD.default_value = {}
BOSSINFO_GIFTS_FIELD.message_type = GIFT_PB_GIFT
BOSSINFO_GIFTS_FIELD.type = 11
BOSSINFO_GIFTS_FIELD.cpp_type = 10
BOSSINFO_WIDTH_FIELD.name = "width"
BOSSINFO_WIDTH_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.width"
BOSSINFO_WIDTH_FIELD.number = 23
BOSSINFO_WIDTH_FIELD.index = 20
BOSSINFO_WIDTH_FIELD.label = 1
BOSSINFO_WIDTH_FIELD.has_default_value = false
BOSSINFO_WIDTH_FIELD.default_value = 0
BOSSINFO_WIDTH_FIELD.type = 13
BOSSINFO_WIDTH_FIELD.cpp_type = 3
BOSSINFO_HEIGHT_FIELD.name = "height"
BOSSINFO_HEIGHT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.height"
BOSSINFO_HEIGHT_FIELD.number = 24
BOSSINFO_HEIGHT_FIELD.index = 21
BOSSINFO_HEIGHT_FIELD.label = 1
BOSSINFO_HEIGHT_FIELD.has_default_value = false
BOSSINFO_HEIGHT_FIELD.default_value = 0
BOSSINFO_HEIGHT_FIELD.type = 13
BOSSINFO_HEIGHT_FIELD.cpp_type = 3
BOSSINFO_BEGINTIME_FIELD.name = "begintime"
BOSSINFO_BEGINTIME_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.begintime"
BOSSINFO_BEGINTIME_FIELD.number = 25
BOSSINFO_BEGINTIME_FIELD.index = 22
BOSSINFO_BEGINTIME_FIELD.label = 1
BOSSINFO_BEGINTIME_FIELD.has_default_value = false
BOSSINFO_BEGINTIME_FIELD.default_value = 0
BOSSINFO_BEGINTIME_FIELD.type = 13
BOSSINFO_BEGINTIME_FIELD.cpp_type = 3
BOSSINFO_ENDTIME_FIELD.name = "endtime"
BOSSINFO_ENDTIME_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.endtime"
BOSSINFO_ENDTIME_FIELD.number = 26
BOSSINFO_ENDTIME_FIELD.index = 23
BOSSINFO_ENDTIME_FIELD.label = 1
BOSSINFO_ENDTIME_FIELD.has_default_value = false
BOSSINFO_ENDTIME_FIELD.default_value = 0
BOSSINFO_ENDTIME_FIELD.type = 13
BOSSINFO_ENDTIME_FIELD.cpp_type = 3
BOSSINFO_STATUS_FIELD.name = "status"
BOSSINFO_STATUS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.status"
BOSSINFO_STATUS_FIELD.number = 27
BOSSINFO_STATUS_FIELD.index = 24
BOSSINFO_STATUS_FIELD.label = 1
BOSSINFO_STATUS_FIELD.has_default_value = false
BOSSINFO_STATUS_FIELD.default_value = 0
BOSSINFO_STATUS_FIELD.type = 13
BOSSINFO_STATUS_FIELD.cpp_type = 3
BOSSINFO_CHALLCOUNT_FIELD.name = "challcount"
BOSSINFO_CHALLCOUNT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.challcount"
BOSSINFO_CHALLCOUNT_FIELD.number = 28
BOSSINFO_CHALLCOUNT_FIELD.index = 25
BOSSINFO_CHALLCOUNT_FIELD.label = 1
BOSSINFO_CHALLCOUNT_FIELD.has_default_value = false
BOSSINFO_CHALLCOUNT_FIELD.default_value = 0
BOSSINFO_CHALLCOUNT_FIELD.type = 13
BOSSINFO_CHALLCOUNT_FIELD.cpp_type = 3
BOSSINFO_TOTALUSER_FIELD.name = "totaluser"
BOSSINFO_TOTALUSER_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.totaluser"
BOSSINFO_TOTALUSER_FIELD.number = 30
BOSSINFO_TOTALUSER_FIELD.index = 26
BOSSINFO_TOTALUSER_FIELD.label = 1
BOSSINFO_TOTALUSER_FIELD.has_default_value = false
BOSSINFO_TOTALUSER_FIELD.default_value = 0
BOSSINFO_TOTALUSER_FIELD.type = 13
BOSSINFO_TOTALUSER_FIELD.cpp_type = 3
BOSSINFO_PROGRESS_FIELD.name = "progress"
BOSSINFO_PROGRESS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.progress"
BOSSINFO_PROGRESS_FIELD.number = 31
BOSSINFO_PROGRESS_FIELD.index = 27
BOSSINFO_PROGRESS_FIELD.label = 1
BOSSINFO_PROGRESS_FIELD.has_default_value = false
BOSSINFO_PROGRESS_FIELD.default_value = 0
BOSSINFO_PROGRESS_FIELD.type = 13
BOSSINFO_PROGRESS_FIELD.cpp_type = 3
BOSSINFO_TOTALPROGRESS_FIELD.name = "totalprogress"
BOSSINFO_TOTALPROGRESS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.totalprogress"
BOSSINFO_TOTALPROGRESS_FIELD.number = 32
BOSSINFO_TOTALPROGRESS_FIELD.index = 28
BOSSINFO_TOTALPROGRESS_FIELD.label = 1
BOSSINFO_TOTALPROGRESS_FIELD.has_default_value = false
BOSSINFO_TOTALPROGRESS_FIELD.default_value = 0
BOSSINFO_TOTALPROGRESS_FIELD.type = 13
BOSSINFO_TOTALPROGRESS_FIELD.cpp_type = 3
BOSSINFO_CONDITION_FIELD.name = "condition"
BOSSINFO_CONDITION_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.condition"
BOSSINFO_CONDITION_FIELD.number = 33
BOSSINFO_CONDITION_FIELD.index = 29
BOSSINFO_CONDITION_FIELD.label = 3
BOSSINFO_CONDITION_FIELD.has_default_value = false
BOSSINFO_CONDITION_FIELD.default_value = {}
BOSSINFO_CONDITION_FIELD.type = 9
BOSSINFO_CONDITION_FIELD.cpp_type = 9
BOSSINFO_MEETCOND_FIELD.name = "meetcond"
BOSSINFO_MEETCOND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.meetcond"
BOSSINFO_MEETCOND_FIELD.number = 34
BOSSINFO_MEETCOND_FIELD.index = 30
BOSSINFO_MEETCOND_FIELD.label = 3
BOSSINFO_MEETCOND_FIELD.has_default_value = false
BOSSINFO_MEETCOND_FIELD.default_value = {}
BOSSINFO_MEETCOND_FIELD.type = 8
BOSSINFO_MEETCOND_FIELD.cpp_type = 7
BOSSINFO_REWARD_FIELD.name = "reward"
BOSSINFO_REWARD_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo.reward"
BOSSINFO_REWARD_FIELD.number = 35
BOSSINFO_REWARD_FIELD.index = 31
BOSSINFO_REWARD_FIELD.label = 3
BOSSINFO_REWARD_FIELD.has_default_value = false
BOSSINFO_REWARD_FIELD.default_value = {}
BOSSINFO_REWARD_FIELD.message_type = BOSSREWARD
BOSSINFO_REWARD_FIELD.type = 11
BOSSINFO_REWARD_FIELD.cpp_type = 10
BOSSINFO.name = "BossInfo"
BOSSINFO.full_name = ".com.xinqihd.sns.gameserver.proto.BossInfo"
BOSSINFO.nested_types = {}
BOSSINFO.enum_types = {}
BOSSINFO.fields = {BOSSINFO_ID_FIELD, BOSSINFO_BOSSID_FIELD, BOSSINFO_NAME_FIELD, BOSSINFO_TITLE_FIELD, BOSSINFO_TARGET_FIELD, BOSSINFO_MAPID_FIELD, BOSSINFO_DESC_FIELD, BOSSINFO_LEVEL_FIELD, BOSSINFO_ATTACK_FIELD, BOSSINFO_DEFEND_FIELD, BOSSINFO_AGILITY_FIELD, BOSSINFO_LUCKY_FIELD, BOSSINFO_THEW_FIELD, BOSSINFO_BLOOD_FIELD, BOSSINFO_DAMAGE_FIELD, BOSSINFO_SKIN_FIELD, BOSSINFO_POWER_FIELD, BOSSINFO_BOSSTYPE_FIELD, BOSSINFO_TOTALROUND_FIELD, BOSSINFO_GIFTS_FIELD, BOSSINFO_WIDTH_FIELD, BOSSINFO_HEIGHT_FIELD, BOSSINFO_BEGINTIME_FIELD, BOSSINFO_ENDTIME_FIELD, BOSSINFO_STATUS_FIELD, BOSSINFO_CHALLCOUNT_FIELD, BOSSINFO_TOTALUSER_FIELD, BOSSINFO_PROGRESS_FIELD, BOSSINFO_TOTALPROGRESS_FIELD, BOSSINFO_CONDITION_FIELD, BOSSINFO_MEETCOND_FIELD, BOSSINFO_REWARD_FIELD}
BOSSINFO.is_extendable = false
BOSSINFO.extensions = {}
BossInfo = protobuf.Message(BOSSINFO)
BossReward = protobuf.Message(BOSSREWARD)
Point = protobuf.Message(POINT)
_G.BOSSINFO_PB_BOSSINFO = BOSSINFO
_G.BOSSREWARD_PB_BOSSREWARD = BOSSREWARD
_G.POINT_PB_POINT = POINT
|
local ui = require 'lib.LoveUIView'
local MyTextField = ui.extends(ui.TextField,'MyTextField')
function MyTextField.new(x,y,width,height)
local self = MyTextField.newObject(x,y,width,height)
self._text = self.text
return self
end
function MyTextField:endResponder()
self:super_endResponder()
self._save = self.text
self.text = self._text
end
function MyTextField:confirmText()
if self._save then
self.text = math.floor(tonumber(self._save))
end
end
function MyTextField:mousepressed(...)
self:becomeResponder()
end
function MyTextField:becomeResponder()
if self.screen ~= nil then
self.screen:becomeResponder(self)
end
self._text = self.text
end
return MyTextField |
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:Initialize( ) --This function is run when the entity is created so it's a good place to setup our entity.
local Money = nil
local Money = self.money
local MModel = nil
local ModelNum = nil
if Money == nil or 0 then
self:Remove()
elseif Money <= 10000 then
MModel = "models/props/cs_assault/money.mdl"
ModelNum = 1
else
MModel = "models/props/cs_assault/moneypallete.mdl"
ModelNum = 2
end
if MModel !=nil then
self:SetModel( MModel ) -- Sets the model of the NPC.
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self:SetPos(self:GetPos()+Vector(0,0,90))
end
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
end
function ENT:AcceptInput( iName, Activator, Caller )
if iName == "Use" and Caller:IsPlayer() then
-- if player presses e do this
end
end |
-- Enumerate the source's media cues. Returns the next index or 0 when finished.
-- @index integer
-- @return number, number, boolean, string
function PCMSource:c_f__enum_media_source_cues(index)
local retval, time, end_time, is_region, name = r.CF_EnumMediaSourceCues(self.pointer, index)
if retval then
return time, end_time, is_region, name
end
end
-- Export the source to the given file (MIDI only).
-- @fn string
-- @return boolean
function PCMSource:c_f__export_media_source(fn)
return r.CF_ExportMediaSource(self.pointer, fn)
end
-- Returns the bit depth if available (0 otherwise).
-- @return integer
function PCMSource:c_f__get_media_source_bit_depth()
return r.CF_GetMediaSourceBitDepth(self.pointer)
end
-- Get the value of the given metadata field (eg. DESC, ORIG, ORIGREF, DATE, TIME, UMI, CODINGHISTORY for BWF).
-- @name string
-- @out string
-- @return string
function PCMSource:c_f__get_media_source_metadata(name, out)
local retval, out_ = r.CF_GetMediaSourceMetadata(self.pointer, name, out)
if retval then
return out_
end
end
-- Returns the online/offline status of the given source.
-- @return boolean
function PCMSource:c_f__get_media_source_online()
return r.CF_GetMediaSourceOnline(self.pointer)
end
-- Get the project associated with this source (BWF, subproject...).
-- @return string
function PCMSource:c_f__get_media_source_r_p_p()
local retval, fn = r.CF_GetMediaSourceRPP(self.pointer)
if retval then
return fn
end
end
-- Set the online/offline status of the given source (closes files when set=false).
-- @set boolean
function PCMSource:c_f__set_media_source_online(set)
return r.CF_SetMediaSourceOnline(self.pointer, set)
end
-- Get text-based metadata from a media file for a given identifier. Call with identifier="" to list all identifiers contained in the file, separated by newlines. May return "[Binary data]" for metadata that REAPER doesn't handle.
-- @identifier string
-- @return string
function PCMSource:get_media_file_metadata(identifier)
local retval, buf = r.GetMediaFileMetadata(self.pointer, identifier)
if retval then
return buf
end
end
-- Copies the media source filename to typebuf. Note that in-project MIDI media sources have no associated filename. See GetMediaSourceParent.
-- @filenamebuf string
-- @return string
function PCMSource:get_media_source_file_name(filenamebuf)
return r.GetMediaSourceFileName(self.pointer, filenamebuf)
end
-- Returns the length of the source media. If the media source is beat-based, the length will be in quarter notes, otherwise it will be in seconds.
-- @return boolean
function PCMSource:get_media_source_length()
local retval, length_is_q_n = r.GetMediaSourceLength(self.pointer)
if retval then
return length_is_q_n
end
end
-- Returns the number of channels in the source media.
-- @return integer
function PCMSource:get_media_source_num_channels()
return r.GetMediaSourceNumChannels(self.pointer)
end
-- Returns the parent source, or NULL if src is the root source. This can be used to retrieve the parent properties of sections or reversed sources for example.
-- @return PCM_source
function PCMSource:get_media_source_parent()
return r.GetMediaSourceParent(self.pointer)
end
-- Returns the sample rate. MIDI source media will return zero.
-- @return integer
function PCMSource:get_media_source_sample_rate()
return r.GetMediaSourceSampleRate(self.pointer)
end
-- copies the media source type ("WAV", "MIDI", etc) to typebuf
-- @typebuf string
-- @return string
function PCMSource:get_media_source_type(typebuf)
return r.GetMediaSourceType(self.pointer, typebuf)
end
-- @return ReaProject
function PCMSource:get_sub_project_from_source()
return r.GetSubProjectFromSource(self.pointer)
end
-- finds the playrate and target length to insert this item stretched to a round power-of-2 number of bars, between 1/8 and 256
-- @srcscale number
-- @position number
-- @mult number
-- @return number, number
function PCMSource:get_tempo_match_play_rate(srcscale, position, mult)
local retval, rate, targetlen = r.GetTempoMatchPlayRate(self.pointer, srcscale, position, mult)
if retval then
return rate, targetlen
end
end
-- Deletes a PCM_source -- be sure that you remove any project reference before deleting a source
function PCMSource:p_c_m__source__destroy()
return r.PCM_Source_Destroy(self.pointer)
end
-- Gets block of peak samples to buf. Note that the peak samples are interleaved, but in two or three blocks (maximums, then minimums, then extra). Return value has 20 bits of returned sample count, then 4 bits of output_mode (0xf00000), then a bit to signify whether extra_type was available (0x1000000). extra_type can be 115 ('s') for spectral information, which will return peak samples as integers with the low 15 bits frequency, next 14 bits tonality.
-- @peakrate number
-- @starttime number
-- @numchannels integer
-- @numsamplesperchannel integer
-- @want_extra_type integer
-- @buf reaper.array
-- @return integer
function PCMSource:p_c_m__source__get_peaks(peakrate, starttime, numchannels, numsamplesperchannel, want_extra_type, buf)
return r.PCM_Source_GetPeaks(self.pointer, peakrate, starttime, numchannels, numsamplesperchannel, want_extra_type, buf)
end
-- If a section/reverse block, retrieves offset/len/reverse. return true if success
-- @return number, number, boolean
function PCMSource:p_c_m__source__get_section_info()
local retval, offs, len, rev = r.PCM_Source_GetSectionInfo(self.pointer)
if retval then
return offs, len, rev
end
end
-- Get the value of metadata from media source(.wav only). metaType=BWF,IXML,INFO,CART, key=MetadataID(eg.INAM,IART,... of INFO)
-- @meta_type string
-- @key string
-- @buf string
-- @buf_size integer
-- @return string
function PCMSource:r_d_n_a__get_media_source_metadata(meta_type, key, buf, buf_size)
local retval, buf_ = r.RDNA_GetMediaSourceMetadata(self.pointer, meta_type, key, buf, buf_size)
if retval then
return buf_
end
end
-- Get interleaved audio data from media source
-- @destbuf identifier
-- @destbufoffset integer
-- @numframes integer
-- @numchans integer
-- @samplerate number
-- @sourceposition number
-- @return integer
function PCMSource:xen__get_media_source_samples(destbuf, destbufoffset, numframes, numchans, samplerate, sourceposition)
return r.Xen_GetMediaSourceSamples(self.pointer, destbuf, destbufoffset, numframes, numchans, samplerate, sourceposition)
end
-- If the given PCM_source does not belong to an existing MediaItem/Take, it will be deleted by the preview system when the preview is stopped.
-- @gain number
-- @loop boolean
-- @outputchanindex_in number
-- @return integer
function PCMSource:xen__start_source_preview(gain, loop, outputchanindex_in)
return r.Xen_StartSourcePreview(self.pointer, gain, loop, outputchanindex_in)
end
|
---------------------------------------------------
-- Vicious widgets for the awesome window manager
---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2010, Adrian C. <anrxc@sysphere.org>
---------------------------------------------------
-- {{{ Setup environment
local setmetatable = setmetatable
local wrequire = require("modules.vicious.helpers").wrequire
-- Vicious: widgets for the awesome window manager
-- vicious.contrib
local contrib = { _NAME = "vicious.contrib" }
-- }}}
-- Load modules at runtime as needed
return setmetatable(contrib, { __index = wrequire })
|
local profile = GetPlayerOrMachineProfile(PLAYER_1)
profile:SetFromAll()
local maxGoals = 11
local curPage = 1
local song = GAMESTATE:GetCurrentSong()
local goaltable = profile:GetGoalTable()
local maxPages = math.ceil(#goaltable/maxGoals)
local inDetail = false
local function updateGoalsFromData()
profile:SortByName()
goaltable = profile:GetGoalTable()
GHETTOGAMESTATE:resetGoalTable()
curPage = 1
maxPages = math.ceil(#goaltable/maxGoals)
end
local function byAchieved(scoregoal)
if not scoregoal or scoregoal:IsAchieved() then
return getMainColor("positive")
end
if scoregoal:IsVacuous() then
return color("#ffcccc")
end
return color("#cccccc")
end
local function movePage(n)
if maxPages > 1 then
if n > 0 then
curPage = ((curPage+n-1) % maxPages + 1)
else
curPage = ((curPage+n+maxPages-1) % maxPages+1)
end
end
MESSAGEMAN:Broadcast("UpdateList")
end
local function input(event)
if event.type == "InputEventType_FirstPress" then
if event.button == "Back" or event.button == "Start" then
SCREENMAN:GetTopScreen():Cancel()
elseif event.DeviceInput.button == "DeviceButton_mousewheel up" then
MESSAGEMAN:Broadcast("WheelUpSlow")
elseif event.DeviceInput.button == "DeviceButton_mousewheel down" then
MESSAGEMAN:Broadcast("WheelDownSlow")
elseif event.button == "MenuLeft" then
movePage(-1)
elseif event.button == "MenuRight" then
movePage(1)
end
end
return false
end
local top
local leftSectionWidth = 300
local leftSectionHeight = SCREEN_HEIGHT - 60
local leftUpperSectionHeight = leftSectionHeight / 3
local leftLowerSectionHeight = SCREEN_HEIGHT / 1.5 - 10
local rightSectionWidth = SCREEN_WIDTH - 330
local rightSectionHeight = SCREEN_HEIGHT - 60
local verticalSpacing = 7
local horizontalSpacing = 10
local t = Def.ActorFrame {
OnCommand = function(self)
everything = self
top = SCREENMAN:GetTopScreen()
top:AddInputCallback(input)
SCREENMAN:GetTopScreen():AddInputCallback(MPinput)
end,
DFRFinishedMessageCommand = function(self) -- not sure this would even normally happen on this screen but just in case
profile:SetFromAll()
updateGoalsFromData()
self:queuecommand("UpdateList")
end
}
local boxHeight = 20
local numBoxWidth = leftSectionWidth / 2
t[#t+1] = LoadActor("../_mouse")
t[#t+1] = LoadActor("../_frame")
local frameWidth = 430
local frameHeight = 340
-- The upper left container (Minimal Profile Card)
local function upperLeftContainer()
local t = Def.ActorFrame {
Name = "ProfileCard",
InitCommand = function(self)
self:xy(10,30)
end,
Def.Quad {
InitCommand = function(self)
self:halign(0):valign(0)
self:zoomto(300,100)
self:diffuse(color(colorConfig:get_data().main.frame)):diffusealpha(0.85)
end
}
}
t[#t+1] = LoadActor("../ScreenPlayerProfile decorations/avatar") .. {
InitCommand = function(self)
self:xy(50,50)
end
}
t[#t+1] = LoadFont("Common BLarge") .. {
InitCommand = function(self)
self:xy(100,25)
self:zoom(0.35)
self:halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:queuecommand("Set")
end,
SetCommand = function(self)
self:settext(getCurrentUsername(PLAYER_1))
end
}
t[#t+1] = LoadActor("../ScreenPlayerProfile decorations/expbar") .. {
InitCommand = function(self)
self:xy(100,55)
end
}
return t
end
-- The lower left container (The Tag Editor)
local function lowerLeftContainer()
local goalIndex -- im really killing the scope here haha
local t = Def.ActorFrame {
Name = "EditorContainer",
InitCommand = function(self)
self:xy(10, leftUpperSectionHeight)
end,
HideGoalDetailMessageCommand = function(self)
end,
-- The container quad
Def.Quad {
InitCommand = function(self)
self:zoomto(leftSectionWidth, leftLowerSectionHeight)
self:halign(0):valign(0)
self:diffuse(getMainColor("frame"))
self:diffusealpha(0.85)
end
},
LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(5,10)
self:zoom(0.4)
self:halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Edit Goal")
end
},
LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,25)
self:zoom(0.4)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Title")
end
},
LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,50)
self:zoom(0.4)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("MSD")
end
},
LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,75)
self:zoom(0.4)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Current PB")
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,34)
self:zoom(0.35)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("")
self:maxwidth(leftSectionWidth * 2.3)
end,
SetCommand = function(self)
local ck = goaltable[goalIndex]:GetChartKey()
local goalsong = SONGMAN:GetSongByChartKey(ck)
if goalsong then
self:settextf("%s",goalsong:GetDisplayMainTitle())
else
self:settextf("%s", ck)
end
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
self:queuecommand("Set")
end,
HideGoalDetailMessageCommand = function(self)
self:settext("")
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,59)
self:zoom(0.35)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("")
self:maxwidth(leftSectionWidth * 2.3)
end,
SetCommand = function(self)
local ck = goaltable[goalIndex]:GetChartKey()
local goalsong = SONGMAN:GetSongByChartKey(ck)
local goalsteps = SONGMAN:GetStepsByChartKey(ck)
if goalsteps and goaltable[goalIndex] then
local msd = goalsteps:GetMSD(goaltable[goalIndex]:GetRate(), 1)
self:settextf("%5.1f", msd)
self:diffuse(byMSD(msd))
else
self:settext("??")
end
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
self:queuecommand("Set")
end,
HideGoalDetailMessageCommand = function(self)
self:settext("")
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(leftSectionWidth/2,84)
self:zoom(0.35)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("")
self:maxwidth(leftSectionWidth * 2.3)
end,
SetCommand = function(self)
local pb = goaltable[goalIndex]:GetPBUpTo()
if pb then
if pb:GetMusicRate() < goaltable[goalIndex]:GetRate() then
local ratestring = string.format("%.2f", pb:GetMusicRate()):gsub("%.?0$", "") .. "x"
self:settextf("Best: %5.2f%% (%s)", pb:GetWifeScore() * 100, ratestring)
else
self:settextf("Best: %5.2f%%", pb:GetWifeScore() * 100)
end
self:diffuse(getGradeColor(pb:GetWifeGrade()))
self:visible(true)
else
self:settextf("(Best: %5.2f%%)", 0)
self:diffuse(byAchieved(goaltable[goalIndex]))
end
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
self:queuecommand("Set")
end,
HideGoalDetailMessageCommand = function(self)
self:settext("")
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
}
}
local function rateChangeButton()
local topRowFrameWidth = SCREEN_WIDTH - 20
local topRowFrameHeight = 40
local frameWidth = 150
local frameHeight = 25
local goalIndex
local t = Def.ActorFrame {
Name = "RateChangeButton",
InitCommand = function(self)
self:xy(leftSectionWidth/2 + frameWidth/2,150)
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
self:queuecommand("Set")
end
}
t[#t+1] = LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(-frameWidth/2, -22)
self:zoom(0.35)
self:settext("Change Rate")
end
}
t[#t+1] = Def.Quad{
InitCommand = function(self)
self:zoomto(frameWidth, 25)
self:diffuse(color("#000000")):diffusealpha(0.8)
self:halign(1)
end
}
t[#t+1] = quadButton(6)..{
InitCommand = function(self)
self:zoomto(frameWidth/2, frameHeight)
self:x(-frameWidth/2)
self:diffuse(color("#FFFFFF")):diffusealpha(0)
self:halign(1)
self:faderight(0.5)
end,
TopPressedCommand = function(self, params)
if inDetail then
goaltable[goalIndex]:SetRate(goaltable[goalIndex]:GetRate() - 0.05)
MESSAGEMAN:Broadcast("UpdateGoalDetails")
self:GetParent():GetChild("TriangleLeft"):playcommand("Tween")
self:finishtweening()
self:diffusealpha(0.2)
self:smooth(0.3)
self:diffusealpha(0)
end
end
}
t[#t+1] = quadButton(6)..{
InitCommand = function(self)
self:zoomto(frameWidth/2, frameHeight)
self:diffuse(color("#FFFFFF")):diffusealpha(0)
self:halign(1)
self:fadeleft(0.5)
end,
TopPressedCommand = function(self, params)
if inDetail then
goaltable[goalIndex]:SetRate(goaltable[goalIndex]:GetRate() + 0.05)
MESSAGEMAN:Broadcast("UpdateGoalDetails")
self:GetParent():GetChild("TriangleRight"):playcommand("Tween")
self:finishtweening()
self:diffusealpha(0.2)
self:smooth(0.3)
self:diffusealpha(0)
end
end
}
t[#t+1] = LoadActor(THEME:GetPathG("", "_triangle")) .. {
Name = "TriangleLeft",
InitCommand = function(self)
self:zoom(0.15)
self:x(-frameWidth + 10)
self:diffusealpha(0.8)
self:rotationz(-90)
end,
TweenCommand = function(self)
self:finishtweening()
self:diffuse(getMainColor('highlight')):diffusealpha(0.8)
self:smooth(0.5)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)):diffusealpha(0.8)
end
}
t[#t+1] = LoadActor(THEME:GetPathG("", "_triangle")) .. {
Name = "TriangleRight",
InitCommand = function(self)
self:zoom(0.15)
self:x(-10)
self:diffusealpha(0.8)
self:rotationz(90)
end,
TweenCommand = function(self)
self:finishtweening()
self:diffuse(getMainColor('highlight')):diffusealpha(0.8)
self:smooth(0.5)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)):diffusealpha(0.8)
end
}
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
self:x(-frameWidth/2)
self:zoom(0.3)
self:queuecommand("Set")
end,
SetCommand = function(self, params)
if goaltable[goalIndex] then
local ratestring = string.format("%.2f", goaltable[goalIndex]:GetRate()):gsub("%.?0$", "") .. "x"
self:settext(ratestring)
end
end,
UpdateGoalDetailsMessageCommand = function(self)
self:playcommand("Set")
end,
HideGoalDetailMessageCommand = function(self)
self:settext("")
end
}
return t
end
local function percentChangeButton()
local topRowFrameWidth = SCREEN_WIDTH - 20
local topRowFrameHeight = 40
local frameWidth = 150
local frameHeight = 25
local goalIndex
local t = Def.ActorFrame {
Name = "PercentChangeButton",
InitCommand = function(self)
self:xy(leftSectionWidth/2 + frameWidth/2,200)
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
self:queuecommand("Set")
end
}
t[#t+1] = LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(-frameWidth/2, -22)
self:zoom(0.35)
self:settext("Change Goal Percent")
end
}
t[#t+1] = Def.Quad{
InitCommand = function(self)
self:zoomto(frameWidth, 25)
self:diffuse(color("#000000")):diffusealpha(0.8)
self:halign(1)
end
}
t[#t+1] = quadButton(6)..{
InitCommand = function(self)
self:zoomto(frameWidth/2, frameHeight)
self:x(-frameWidth/2)
self:diffuse(color("#FFFFFF")):diffusealpha(0)
self:halign(1)
self:faderight(0.5)
end,
TopPressedCommand = function(self, params)
if inDetail then
goaltable[goalIndex]:SetPercent(goaltable[goalIndex]:GetPercent() - 0.01)
MESSAGEMAN:Broadcast("UpdateGoalDetails")
self:GetParent():GetChild("TriangleLeft"):playcommand("Tween")
self:finishtweening()
self:diffusealpha(0.2)
self:smooth(0.3)
self:diffusealpha(0)
end
end
}
t[#t+1] = quadButton(6)..{
InitCommand = function(self)
self:zoomto(frameWidth/2, frameHeight)
self:diffuse(color("#FFFFFF")):diffusealpha(0)
self:halign(1)
self:fadeleft(0.5)
end,
TopPressedCommand = function(self, params)
if inDetail then
goaltable[goalIndex]:SetPercent(goaltable[goalIndex]:GetPercent() + 0.01)
MESSAGEMAN:Broadcast("UpdateGoalDetails")
self:GetParent():GetChild("TriangleRight"):playcommand("Tween")
self:finishtweening()
self:diffusealpha(0.2)
self:smooth(0.3)
self:diffusealpha(0)
end
end
}
t[#t+1] = LoadActor(THEME:GetPathG("", "_triangle")) .. {
Name = "TriangleLeft",
InitCommand = function(self)
self:zoom(0.15)
self:x(-frameWidth + 10)
self:diffusealpha(0.8)
self:rotationz(-90)
end,
TweenCommand = function(self)
self:finishtweening()
self:diffuse(getMainColor('highlight')):diffusealpha(0.8)
self:smooth(0.5)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)):diffusealpha(0.8)
end
}
t[#t+1] = LoadActor(THEME:GetPathG("", "_triangle")) .. {
Name = "TriangleRight",
InitCommand = function(self)
self:zoom(0.15)
self:x(-10)
self:diffusealpha(0.8)
self:rotationz(90)
end,
TweenCommand = function(self)
self:finishtweening()
self:diffuse(getMainColor('highlight')):diffusealpha(0.8)
self:smooth(0.5)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText)):diffusealpha(0.8)
end
}
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand = function(self)
self:x(-frameWidth/2)
self:zoom(0.3)
self:queuecommand("Set")
end,
SetCommand = function(self, params)
if goaltable[goalIndex] then
local perc = math.floor(goaltable[goalIndex]:GetPercent() * 10000) / 100
if perc < 99 then
self:settextf("%.f%%", perc)
else
self:settextf("%.2f%%", perc)
end
end
end,
UpdateGoalDetailsMessageCommand = function(self)
self:playcommand("Set")
end,
HideGoalDetailMessageCommand = function(self)
self:settext("")
end
}
return t
end
local function deleteButton()
local goalIndex
local t = Def.ActorFrame {
quadButton(6) .. {
InitCommand = function(self)
self:xy(15, leftLowerSectionHeight/2 - 30)
self:halign(0)
self:diffusealpha(0.2)
self:zoomto(numBoxWidth + 15, 35)
end,
ShowGoalDetailMessageCommand = function(self, params)
goalIndex = params.goalIndex
end,
TopPressedCommand = function(self)
if goaltable[goalIndex] and inDetail then
goaltable[goalIndex]:Delete()
profile:SetFromAll()
updateGoalsFromData()
MESSAGEMAN:Broadcast("HideGoalDetail")
MESSAGEMAN:Broadcast("UpdateList")
self:finishtweening()
self:diffusealpha(0.4)
self:smooth(0.3)
self:diffusealpha(0.2)
end
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(15 + (numBoxWidth+15)/2,leftLowerSectionHeight/2 - 30)
self:zoom(0.4)
self:settext("Delete Goal")
end
}
}
return t
end
t[#t+1] = deleteButton() .. {
InitCommand = function(self)
self:xy(-15 + leftSectionWidth/2 - (numBoxWidth+15)/2, leftLowerSectionHeight/2)
end
}
t[#t+1] = rateChangeButton()
t[#t+1] = percentChangeButton()
return t
end
-- The right container (The Tags Menu)
local function rightContainer()
local boxHeight = 25
local boxWidth = rightSectionWidth - 40
local t = Def.ActorFrame {
Name = "GoalContainer",
InitCommand = function(self)
self:xy(20 + leftSectionWidth,30)
MESSAGEMAN:Broadcast("UpdateList")
end,
-- The container quad
Def.Quad {
InitCommand = function (self)
self:zoomto(rightSectionWidth,rightSectionHeight)
self:halign(0):valign(0)
self:diffuse(getMainColor("frame"))
self:diffusealpha(0.85)
end,
WheelUpSlowMessageCommand = function(self)
if self:isOver() then
movePage(-1)
end
end,
WheelDownSlowMessageCommand = function(self)
if self:isOver() then
movePage(1)
end
end,
MouseRightClickMessageCommand = function(self)
if inDetail and isOver(self) then
self:sleep(0.05)
self:queuecommand("DelayedHide")
end
end,
DelayedHideCommand = function(self)
MESSAGEMAN:Broadcast("HideGoalDetail")
end
},
LoadFont("Common Bold") .. {
InitCommand = function(self)
self:xy(5,10)
self:zoom(0.4)
self:halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Manage Goals")
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(7,25)
self:zoom(0.35)
self:halign(0)
self:valign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Left click a Goal to jump to the song for it. Right click a Goal to edit it in the left section.")
end
},
LoadFont("Common Normal") .. {
InitCommand = function(self)
self:xy(100,10)
self:zoom(0.35)
self:halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:settext("Create a goal for a song by pressing Ctrl + G while on it.")
end
}
}
-- this is copied straight from the filter screen which is copied from the downloader screen
-- theming is so easy lol
local function goalItem(i)
local goalIndex = (curPage-1)*10+i
local goalsong
local goalsteps
local ck
local theDetail
local r = Def.ActorFrame{
Name = "GoalItem"..i,
InitCommand = function(self)
self:diffusealpha(0)
self:xy(25, 30 + ((i-1) *(boxHeight+verticalSpacing)-10))
self:playcommand("Show")
end,
ShowCommand = function(self)
self:y(30 + ((i-1)*(boxHeight+verticalSpacing)-10))
self:diffusealpha(0)
self:finishtweening()
self:sleep((i-1)*0.01)
self:easeOut(0.3)
self:y(30 + ((i-1)*(boxHeight+verticalSpacing)+25))
self:diffusealpha(1)
end,
HideCommand = function(self)
self:finishtweening()
self:easeOut(0.2)
self:diffusealpha(0)
end,
UpdateListMessageCommand = function(self)
goalIndex = (curPage-1)*10+i
theDetail = false
inDetail = false
if goaltable[goalIndex] ~= nil then
ck = goaltable[goalIndex]:GetChartKey()
goalsong = SONGMAN:GetSongByChartKey(ck)
goalsteps = SONGMAN:GetStepsByChartKey(ck)
self:RunCommandsOnChildren(function(self) self:playcommand("Set") end)
self:playcommand("Show")
else
self:playcommand("Hide")
end
end,
ShowGoalDetailMessageCommand = function(self, params)
if params.index == i then
theDetail = true
self:diffusealpha(1)
else
if goaltable[goalIndex] ~= nil then
self:diffusealpha(0.5)
end
end
end,
HideGoalDetailMessageCommand = function(self)
theDetail = false
inDetail = false
if goaltable[goalIndex] ~= nil then
self:finishtweening()
self:easeOut(0.5)
self:diffusealpha(1)
else
self:playcommand("Hide")
end
end
}
-- Tag index number
r[#r+1] = LoadFont("Common Normal")..{
InitCommand = function(self)
self:xy(-10,0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.3)
end,
SetCommand = function(self)
self:settextf("%d", goalIndex)
end
}
-- The tag button
r[#r+1] = quadButton(6) .. {
InitCommand = function(self)
self:halign(0)
self:diffusealpha(0.2)
self:zoomto(boxWidth, boxHeight)
end,
TopPressedCommand = function(self, params)
if goaltable[goalIndex] ~= nil then
if params.input == "DeviceButton_left mouse button" then
if goaltable[goalIndex] and goalsong and goalsteps and ((inDetail and theDetail) or not inDetail) then
MESSAGEMAN:Broadcast("TriggerExitFromPS",{song = goalsong})
GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate(goaltable[goalIndex]:GetRate())
GAMESTATE:GetSongOptionsObject("ModsLevel_Song"):MusicRate(goaltable[goalIndex]:GetRate())
GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(goaltable[goalIndex]:GetRate())
SCREENMAN:GetTopScreen():Cancel()
end
elseif params.input == "DeviceButton_right mouse button" then
if goaltable[goalIndex] and not inDetail then
inDetail = true
MESSAGEMAN:Broadcast("ShowGoalDetail", {index = i, goalIndex = goalIndex})
end
end
end
end
}
-- File name
r[#r+1] = LoadFont("Common Bold")..{
InitCommand = function(self)
self:xy(45,-5):halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
if goalsong then
self:settextf("%s",goalsong:GetDisplayMainTitle())
else
self:settextf("%s", ck)
end
self:maxwidth(boxWidth * 2)
end
}
-- Goal percent
r[#r+1] = LoadFont("Common Bold")..{
InitCommand = function(self)
self:xy(10,5):halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
self:maxwidth(boxWidth / 6)
end,
SetCommand = function(self)
if goaltable[goalIndex] then
local perc = math.floor(goaltable[goalIndex]:GetPercent() * 10000) / 100
if perc < 99 then
self:settextf("%.f%%", perc)
else
self:settextf("%.2f%%", perc)
end
end
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
}
-- Best percent
r[#r+1] = LoadFont("Common Bold")..{
InitCommand = function(self)
self:xy(45,5):halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
local pb = goaltable[goalIndex]:GetPBUpTo()
if pb then
if pb:GetMusicRate() < goaltable[goalIndex]:GetRate() then
local ratestring = string.format("%.2f", pb:GetMusicRate()):gsub("%.?0$", "") .. "x"
self:settextf("Best: %5.2f%% (%s)", pb:GetWifeScore() * 100, ratestring)
else
self:settextf("Best: %5.2f%%", pb:GetWifeScore() * 100)
end
self:diffuse(getGradeColor(pb:GetWifeGrade()))
self:visible(true)
else
self:settextf("(Best: %5.2f%%)", 0)
self:diffuse(byAchieved(goaltable[goalIndex]))
end
end
}
-- Assigned date
r[#r+1] = LoadFont("Common Bold")..{
InitCommand = function(self)
self:xy(boxWidth - 135,5):halign(0)
self:maxwidth(boxWidth / 2)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
self:settextf("Assigned: %s", goaltable[goalIndex]:WhenAssigned())
self:diffuse(byAchieved(goaltable[goalIndex]))
end
}
-- Achieved date
r[#r+1] = LoadFont("Common Bold")..{
InitCommand = function(self)
self:xy(boxWidth - 135,-5):halign(0)
self:maxwidth(boxWidth / 2)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
if goaltable[goalIndex]:IsAchieved() then
self:settextf("Achieved: %s", goaltable[goalIndex]:WhenAchieved())
elseif goaltable[goalIndex]:IsVacuous() then
self:settext("Vacuous goal")
else
self:settext("")
end
self:diffuse(byAchieved(goaltable[goalIndex]))
end
}
-- MSD
r[#r+1] = LoadFont("Common Bold")..{
Name = "MSDString",
InitCommand = function(self)
self:xy(boxWidth - 25,0):halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
if goalsteps and goaltable[goalIndex] then
local msd = goalsteps:GetMSD(goaltable[goalIndex]:GetRate(), 1)
self:settextf("%5.1f", msd)
self:diffuse(byMSD(msd))
else
self:settext("??")
end
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
}
-- Rate
r[#r+1] = LoadFont("Common Bold")..{
Name = "RateString",
InitCommand = function(self)
self:xy(10,-5):halign(0)
self:diffuse(color(colorConfig:get_data().selectMusic.TabContentText))
self:zoom(0.4)
end,
SetCommand = function(self)
if goaltable[goalIndex] then
local ratestring = string.format("%.2f", goaltable[goalIndex]:GetRate()):gsub("%.?0$", "") .. "x"
self:settext(ratestring)
end
end,
UpdateGoalDetailsMessageCommand = function(self)
self:queuecommand("Set")
end
}
-- Color for the button to show assign status
r[#r+1] = Def.Quad{
Name = "Status",
InitCommand = function(self)
self:halign(0)
self:diffuse(color(colorConfig:get_data().main.highlight))
self:diffusealpha(0.8)
self:xy(0, 0)
self:zoomto(4, boxHeight)
end,
SetCommand = function(self)
if goalsteps and goalsong then
local diff = goalsteps:GetDifficulty()
self:diffuse(byDifficulty(diff))
else
self:diffuse(getMainColor("negative"))
end
end
}
return r
end
for i = 1, maxGoals do
t[#t+1] = goalItem(i)
end
return t
end
t[#t+1] = upperLeftContainer()
t[#t+1] = lowerLeftContainer()
t[#t+1] = rightContainer()
t[#t+1] = LoadActor("../_cursor")
return t |
function throwing_register_arrow_standard (kind, desc, eq, toughness, craft)
minetest.register_craftitem("throwing:arrow_" .. kind, {
description = desc .. " arrow",
inventory_image = "throwing_arrow_" .. kind .. ".png",
})
minetest.register_node("throwing:arrow_" .. kind .. "_box", {
drawtype = "nodebox",
node_box = {
type = "fixed",
fixed = {
-- Shaft
{-6.5/17, -1.5/17, -1.5/17, 6.5/17, 1.5/17, 1.5/17},
--Spitze
{-4.5/17, 2.5/17, 2.5/17, -3.5/17, -2.5/17, -2.5/17},
{-8.5/17, 0.5/17, 0.5/17, -6.5/17, -0.5/17, -0.5/17},
--Federn
{6.5/17, 1.5/17, 1.5/17, 7.5/17, 2.5/17, 2.5/17},
{7.5/17, -2.5/17, 2.5/17, 6.5/17, -1.5/17, 1.5/17},
{7.5/17, 2.5/17, -2.5/17, 6.5/17, 1.5/17, -1.5/17},
{6.5/17, -1.5/17, -1.5/17, 7.5/17, -2.5/17, -2.5/17},
{7.5/17, 2.5/17, 2.5/17, 8.5/17, 3.5/17, 3.5/17},
{8.5/17, -3.5/17, 3.5/17, 7.5/17, -2.5/17, 2.5/17},
{8.5/17, 3.5/17, -3.5/17, 7.5/17, 2.5/17, -2.5/17},
{7.5/17, -2.5/17, -2.5/17, 8.5/17, -3.5/17, -3.5/17},
}
},
tiles = {"throwing_arrow_" .. kind .. ".png", "throwing_arrow_" .. kind .. ".png", "throwing_arrow_" .. kind .. "_back.png", "throwing_arrow_" .. kind .. "_front.png",
"throwing_arrow_" .. kind .. "_2.png", "throwing_arrow_" .. kind .. ".png"},
groups = {not_in_creative_inventory=1},
})
local THROWING_ARROW_ENTITY={
physical = false,
visual = "wielditem",
visual_size = {x=0.1, y=0.1},
textures = {"throwing:arrow_" .. kind .. "_box"},
lastpos={},
collisionbox = {0,0,0,0,0,0},
player = "",
bow_damage = 0,
}
THROWING_ARROW_ENTITY.on_step = function(self, dtime)
local newpos = self.object:getpos()
if self.lastpos.x ~= nil then
for _, pos in pairs(throwing_get_trajectoire(self, newpos)) do
local node = minetest.get_node(pos)
local objs = minetest.get_objects_inside_radius({x=pos.x,y=pos.y,z=pos.z}, 2)
for k, obj in pairs(objs) do
local objpos = obj:getpos()
if throwing_is_player(self.player, obj) or throwing_is_entity(obj) then
if throwing_touch(pos, objpos) then
local puncher = self.object
if self.player and minetest.get_player_by_name(self.player) then
puncher = minetest.get_player_by_name(self.player)
end
local damage = eq
if self.bow_damage and self.bow_damage > 0 then
damage = damage + (self.bow_damage/12)
end
obj:punch(puncher, 1.0, {
full_punch_interval=1.0,
damage_groups={fleshy=damage},
}, nil)
if math.random() < toughness then
if math.random(0,100) % 2 == 0 then
minetest.add_item(self.lastpos, 'throwing:arrow_' .. kind)
end
else
minetest.add_item(self.lastpos, 'default:stick')
end
self.object:remove()
return
end
end
end
if node.name ~= "air"
and not string.find(node.name, 'water_')
and not (string.find(node.name, 'grass') and not string.find(node.name, 'dirt'))
and not (string.find(node.name, 'farming:') and not string.find(node.name, 'soil'))
and not string.find(node.name, 'flowers:')
and not string.find(node.name, 'fire:') then
if math.random() < toughness then
minetest.add_item(self.lastpos, 'throwing:arrow_' .. kind)
else
minetest.add_item(self.lastpos, 'default:stick')
end
self.object:remove()
return
end
self.lastpos={x=pos.x, y=pos.y, z=pos.z}
end
end
self.lastpos={x=newpos.x, y=newpos.y, z=newpos.z}
end
minetest.register_entity("throwing:arrow_" .. kind .. "_entity", THROWING_ARROW_ENTITY)
minetest.register_craft({
output = 'throwing:arrow_' .. kind .. ' 16',
recipe = {
{'default:stick', 'default:stick', craft},
}
})
minetest.register_craft({
output = 'throwing:arrow_' .. kind .. ' 16',
recipe = {
{craft, 'default:stick', 'default:stick'},
}
})
end
if not DISABLE_STONE_ARROW then
throwing_register_arrow_standard ('stone', 'Stone', 4, 0.40, 'group:stone')
end
if not DISABLE_STEEL_ARROW then
throwing_register_arrow_standard ('steel', 'Steel', 5, 0.50, 'default:steel_ingot')
end
if not DISABLE_OBSIDIAN_ARROW then
throwing_register_arrow_standard ('obsidian', 'Obsidian', 6, 0.60, 'default:obsidian')
end
if not DISABLE_DIAMOND_ARROW then
throwing_register_arrow_standard ('diamond', 'Diamond', 7, 0.70, 'default:diamond')
end
if not DISABLE_MITHRIL_ARROW then
throwing_register_arrow_standard ('mithril', 'Mithril (Hunter)', 8, 0.80, 'default:mithril_ingot')
end
|
local View = class("View", cc.Node)
local HasSignals = require('HasSignals')
local function mixin(self, script)
for k, v in pairs(script) do
-- added by hthuang: onExit can not be used
-- assert(self[k] == nil, 'Your script "app/views/'..self.name..'.lua" should not have a member named: ' .. k)
self[k] = v
end
end
-- return node on success
-- return emptynode, true on error
local function loadUI(csb)
print('Loading "'..csb..'"...')
if not cc.FileUtils:getInstance():isFileExist(csb) then
print('Not exists. Skippd.')
return cc.Node:create()
end
local node = cc.CSLoader:createLocalizedNode(csb)
if not node then
print(string.format('Failed to load View node from "%s" ', csb))
return cc.Node:create()
end
return node
end
View.loadUI = loadUI
View.loadUI = loadUI
function View:ctor(name, ...)
self:enableNodeEvents()
self.name = name
for _, v in ipairs {'on', 'once'} do
self[v] = HasSignals[v]
end
HasSignals.initialize(self)
self.ui = loadUI('views/'..name..'.csb')
self:addChild(self.ui)
-- load lua script and event view callbacks...
local ok, script = pcall(require, 'app.views.'..name)
if ok then
mixin(self, script)
else
print('not found the view script file',name)
end
if self.initialize then
self:initialize(...)
end
end
return View
|
local buffer = require("doubleBuffering")
local GUI = require("GUI")
local comp = require("component")
local advancedLua = require("advancedLua")
local fs = require("filesystem")
local wrapper = require("is2wrapper")
local gpu = comp.gpu
local app = GUI.application()
local config = {
["firstLaunchWindow"] = true,
["isProxyEnabled"] = false,
["isProxyUrl"] = ""
}
local colors = {
mainColor = 0x00d4cd,
desktopBackground = 0x00aba5,
textColor = 0xFFFFFF,
button = 0x1c1c1c,
buttonText = 0xFFFFFF,
buttonPressed = 0x0d0d0d,
buttonTextPressed = 0xFFFFFF,
inputBackground = 0x1c1c1c,
inputText = 0xFFFFFF,
inputPlaceholderText = 0x6e6e6e,
inputBackgroundFocused = 0x6e6e6e,
inputTextFocused = 0xFFFFFF
}
local windows = {}
windows.minimized = {}
windows.minimizedButtons = {}
windows.apps = {}
local function saveParams()
table.toFile("/Interstellar/params.txt", config)
end
local function loadParams()
if not fs.exists("/Interstellar/") then
fs.makeDirectory("/Interstellar/")
end
if not fs.exists("/Interstellar/params.txt") then
saveParams()
end
config = table.fromFile("/Interstellar/params.txt")
end
-- ISPROXY --
local function log(body)
if not config["isProxyEnabled"] or config["isProxyUrl"] == "" then
return
elseif not comp.isAvailable("internet") then
return
end
local internet = comp.internet
pcall(function()
internet.request(config["isProxyUrl"], body)
end)
end
-- Да-да, решил не юзать жусон либу.
local function logJump(name, fromX, fromY, fromZ, toX, toY, toZ, rotSteps, by)
log(string.format('{"type": "jump", "name": "%s", "jump": [%s, %s, %s, %s, %s, %s], "rot": %s, "player": "%s"}', name, fromX, fromY, fromZ, toX, toY, toZ, rotSteps, by))
end
local function logHyper(name, to, by)
log(string.format('{"type":"hyper", "name": "%s", "to": %s, "player": "%s"}', name, to, by))
end
local function logCancelJump(name, by)
log(string.format('{"type":"cancel_jump", "name": "%s", "player": "%s"}', name, by))
end
local function logPos()
local x, y, z = wrapper.ship.getPosition()
local oX, oZ = wrapper.ship.getOrientation()
local name = wrapper.ship.getShipName()
local mass = wrapper.ship.getShipMass()
local shipEnergy = wrapper.ship.getShipEnergy()
local maxEnergy = wrapper.ship.getMaxShipEnergy()
local energyPercents = math.floor((shipEnergy / maxEnergy) * 100)
local dim = wrapper.ship.getDimensionType()
if dim == 0 then dim = "Space" elseif dim == 1 then dim = "Hyperspace" else dim = "Unknown" end
log(string.format('{"type": "pos", "pos": [%s, %s, %s], "o": [%s, %s], "name": "%s", "mass": %s, "energy": "%s", "dim": "%s"}', x, y, z, oX, oZ, name, mass, energyPercents, dim))
end
local function logRadar(results, name, by)
local out = '{"type": "radarScan", "results": ['
for i = 1, #results - 1 do
out = out .. string.format('"%s",', results[i])
end
out = out .. string.format('"%s"], "name": "%s", "player": "%s"}', results[#results], name, by) -- не знаю под че я это писал и чем меня не устроил join. Похуй пока.
log(out)
end
-------------
local function iInput(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, eraseTextOnFocus, textMask)
local input = GUI.input(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, eraseTextOnFocus, textMask)
input.colors.cursor = colors.mainColor
return input
end
local function iIntInput(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, eraseTextOnFocus, textMask)
local input = iInput(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, eraseTextOnFocus, textMask)
input.validator = function(inputText)
if tonumber(inputText) == nil then
return false
end
return true
end
return input
end
local function iRangedIntInput(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, min, max)
local input = iIntInput(x, y, width, height, backgroundColor, textColor, placeholderTextColor, backgroundFocusedColor, textFocusedColor, text, placeholderText, false, nil)
input.onValidInputFinished = function(num)
end
input.onInputFinished = function(_, input)
num = tonumber(input.text)
if num < min then num = min elseif num > max then num = max end
input.text = tostring(num)
input.onValidInputFinished(num)
end
return input
end
local function iActionButtons(x, y, width)
local container = GUI.container(x, y, width, 1)
container.close = container:addChild(GUI.button(1, 1, 1, 1, colors.mainColor, 0x0, 0x009c96, 0x0, "―"))
container.minimize = container:addChild(GUI.button(container.width, 1, 1, 1, colors.mainColor, 0x0, 0x009c96, 0x0, "▼"))
return container
end
local function iTitledWindow(x, y, width, height, title)
local window = GUI.window(x, y, width, height)
window.name = title
window.backgroundPanel = window:addChild(GUI.panel(1, 1, width, height, 0x545454))
window.titlePanel = window:addChild(GUI.panel(1, 1, width, 1, 0x1c1c1c))
window.titleLabel = window:addChild(GUI.label(1, 1, width, height, 0xFFFFFF, title)):setAlignment(GUI.ALIGNMENT_HORIZONTAL_CENTER, GUI.ALIGNMENT_VERTICAL_TOP)
window.actionButtons = window:addChild(iActionButtons(2, 2, width))
window.actionButtons.localX = 1
window.actionButtons.localY = 1
window.actionButtons.close.onTouch = function()
window:remove()
end
window.actionButtons.minimize.onTouch = function()
windows.addMinimizedWindow(window)
end
return window
end
local function iTabbedWindow(...)
local window = iTitledWindow(...)
window.tabBar = window:addChild(GUI.tabBar(1, 2, window.width, 3, 2, 0, colors.button, colors.buttonText, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, true))
return window
end
local function iListItemEventHandler(application, item, e1, _, x, y)
if e1 == "touch" or e1 == "drag" then
local contextMenu = GUI.addContextMenu(app, x, y)
contextMenu:addItem("To transporter").onTouch = function()
if #item.coords == 0 then
return
end
if not wrapper.transporterApiAvailable() then
GUI.alert("Transporter is not available.")
end
wrapper.transporter.setCoordinates(item.coords[1], item.coords[2], item.coords[3])
end
app:draw()
end
end
local function iListAddItem(list, text, coords)
local item = list:addChild(GUI.button(1, 1, 1, 1, 0, 0, 0, 0, text))
item.switchMode = true
item.eventHandler = iListItemEventHandler
item.coords = coords
return item
end
windows.redrawWindowIcons = function()
for _, button in pairs(windows.minimizedButtons) do
button:remove()
end
windows.minimizedButtons = {}
for i, window in pairs(windows.minimized) do
window:moveToBack()
local button = GUI.framedButton(1 + i * 12 - 12, 44, 12, 6, 0x000000, 0x000000, 0xFAFAFA, 0xFAFAFA, window.name)
button.window = window
button.onTouch = function()
windows.removeMinimizedWindow(button.window)
end
app:addChild(button)
table.insert(windows.minimizedButtons, button)
end
end
windows.addMinimizedWindow = function(window)
table.insert(windows.minimized, window)
windows.redrawWindowIcons()
end
windows.removeMinimizedWindow = function(window)
for k, window2 in pairs(windows.minimized) do
if window == window2 then
window:moveToFront()
table.remove(windows.minimized, k)
break
end
end
windows.redrawWindowIcons()
end
windows.debug = function(x, y)
local window = iTitledWindow(x, y, 30, 11, "Debug")
window.localY = 2
text = window:addChild(GUI.text(2, 2, colors.textColor, "Minimized Windows: "..tostring(#windows.minimized)))
window:addChild(GUI.adaptiveButton(2, 4, 3, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Reload")).onTouch = function()
text.text = "Minimized Windows: "..tostring(#windows.minimized)
end
window:addChild(GUI.adaptiveButton(17, 4, 3, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Windows")).onTouch = function()
if #windows.minimized < 1 then
GUI.alert("No minimized windows!")
return
end
local data = windows.minimized[1].name or "none"
GUI.alert(#windows.minimized.."\n"..data)
end
window:addChild(GUI.adaptiveButton(2, 8, 2, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "ShowAll")).onTouch = function()
for _, window in pairs(windows.minimized) do
windows.removeMinimizedWindow(window)
end
end
window:addChild(GUI.adaptiveButton(16, 8, 1, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "IWrapperDemo")).onTouch = function()
wrapper.toggleDemoMode()
end
return window
end
windows.firstLaunchWindow = function(x, y)
local window = iTitledWindow(x, y, 62, 6, "Welcome to Interstellar2")
window.name = "Interstellar2"
window:addChild(GUI.text(2, 2, colors.textColor, "You are launching Interstellar2 for the first time."))
window:addChild(GUI.text(2, 3, colors.textColor, "Be sure to check out settings to configure IS2 or your ship."))
window:addChild(GUI.text(2, 4, colors.textColor, "Good luck, have fun!"))
window:addChild(GUI.button(window.width-6, window.height-1, 6, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "OK")).onTouch = function()
window:remove()
app:addChild(windows.mainWindow(5, 5))
config.firstLaunchWindow = false
saveParams()
end
window:addChild(GUI.button(window.width-13, window.height-1, 6, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Exit")).onTouch = function()
app:stop()
end
return window
end
windows.mainWindow = function(x, y)
local window = iTitledWindow(x, y, 80, 25, "Interstellar2 Main Window")
window.name = "Main"
count = 1
for _, windowApp in pairs(windows.apps) do
window:addChild(GUI.framedButton(2 + 12 * count - 12, 3, 12, 6, colors.buttonText, colors.buttonText, 0xFAFAFA, 0xFAFAFA, windowApp.name)).onTouch = function()
if windowApp.check() then
app:addChild(windowApp.getWindow(10, 10))
end
end
count = count + 1
end
window.actionButtons.close.onTouch = function()
app:stop()
comp.gpu.setBackground(0x000000)
comp.gpu.setForeground(0xFFFFFF)
require("term").clear()
print("Thanks for using Interstellar2!")
end
return window
end
windows.apps.jumpWindow = {
name = "Jump Menu",
currentWindow = nil,
check = function()
if not wrapper.shipApiAvailable() then
GUI.alert("Ship is not available.")
return false
end
return true
end,
correct = function(x, y, z)
local oX, oZ = wrapper.ship.getOrientation()
local wx, wy, wz
if oX == 1 then
wx, wy, wz = x, y, z
elseif oX == -1 then
wx, wy, wz = -x, y, -z
elseif oZ == 1 then
wx, wy, wz = -z, y, x
elseif oZ == -1 then
wx, wy, wz = z, y, -x
end
return wx, wy, wz
end,
worldMovToShip = function(x, y, z)
local oX, oZ = wrapper.ship.getOrientation()
local mx, my, mz
if oX == 1 then
mx, my, mz = x, y, z
elseif oX == -1 then
mx,my,mz = -x, y, -z
elseif oZ == 1 then
mx,my,mz = z, y, -x
elseif oZ == -1 then
mx,my,mz = -z, y, x
end
return mx, my, mz
end,
update = function()
if windows.apps.jumpWindow.currentWindow then
x = windows.apps.jumpWindow.currentWindow.x
y = windows.apps.jumpWindow.currentWindow.y
windows.apps.jumpWindow.currentWindow:remove()
app:addChild(windows.apps.jumpWindow.getWindow(x, y))
end
end,
getWindow = function(x, y)
local window = iTitledWindow(x, y, 62, 20, "Jump Window")
wrapper.ship.setCommand("MANUAL")
local max = wrapper.ship.getMaxJumpDistance()
local pX, pY, pZ = wrapper.ship.getDimPositive()
local nX, nY, nZ = wrapper.ship.getDimNegative()
local maxX = max + pX + nX
local maxY = max + pY + nY
local maxZ = max + pZ + nZ
local rotmax = 270
local jumpX, jumpY, jumpZ = wrapper.ship.getMovement()
local rot = 0
local autoCorrect = false
if jumpX > maxX then jumpX = maxX elseif jumpX < -maxX then jumpX = -maxX end
if jumpY > maxY then jumpY = maxY elseif jumpY < -maxY then jumpY = -maxY end
if jumpZ > maxZ then jumpZ = maxZ elseif jumpZ < -maxZ then jumpZ = -maxZ end
window:addChild(GUI.label(2, 3, 8, 1, colors.textColor, "Entered values will be automatically limited."))
window:addChild(GUI.label(2, 5, 16, 1, colors.textColor, string.format("X (%s - %s)", pX + nX, maxX)))
window:addChild(iRangedIntInput(2, 6, 30, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, jumpX, "X", -maxX, maxX)).onValidInputFinished = function(num)
jumpX = num
wrapper.ship.setMovement(jumpX, jumpY, jumpZ)
end
window:addChild(GUI.label(2, 8, 12, 1, colors.textColor, string.format("Y (%s - %s)", pY + nY, maxY)))
window:addChild(iRangedIntInput(2, 9, 30, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, jumpY, "Y", -maxY, maxY)).onValidInputFinished = function(num)
jumpY = num
wrapper.ship.setMovement(jumpX, jumpY, jumpZ)
end
window:addChild(GUI.label(2, 11, 14, 1, colors.textColor, string.format("Z (%s - %s)", pZ + nZ, maxZ)))
window:addChild(iRangedIntInput(2, 12, 30, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, jumpZ, "Z", -maxZ, maxZ)).onValidInputFinished = function(num)
jumpZ = num
wrapper.ship.setMovement(jumpX, jumpY, jumpZ)
end
window:addChild(GUI.label(2, 14, 14, 1, colors.textColor, 'Clockwise rotation steps (each is 90°)'))
window:addChild(iRangedIntInput(2, 15, 30, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, rot, "R", 1, 4)).onValidInputFinished = function(num)
rot = num
end
window:addChild(GUI.label(window.width - 24, 12, 8, 1, colors.textColor, "Auto correct:"))
switch = window:addChild(GUI.switch(window.width - 9, 12, 8, colors.mainColor, colors.button, colors.buttonPressed, autoCorrect))
switch.onStateChanged = function()
local oX, oZ = wrapper.ship.getOrientation()
if oX == 1 and oZ == 0 then
switch:setState(false)
end
autoCorrect = switch.state
app:draw()
end
window:addChild(GUI.button(2, 17, 29, 3, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Jump")).onTouch = function(_, _, _, _, _, _, _, by)
local cX, cY, cZ = jumpX, jumpY, jumpZ
if autoCorrect then
cX, cY, cZ = windows.apps.jumpWindow.worldMovToShip(cX, cY, cZ)
end
wrapper.ship.jump(rot, cX, cY, cZ, false)
local dX, dY, dZ = windows.apps.jumpWindow.correct(cX, cY, cZ)
local oX, oZ = wrapper.ship.getOrientation()
local fromX, fromY, fromZ = wrapper.ship.getPosition()
logJump(wrapper.ship.getShipName(), fromX, fromY, fromZ, fromX + dX, fromY + dY, fromZ + dZ, rot, by)
end
window:addChild(GUI.button(33, 17, 29, 3, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Hyperspace jump")).onTouch = function(_, _, _, _, _, _, _, by)
wrapper.ship.jump(nil, nil, nil, nil, true)
logHyper(wrapper.ship.getShipName(), wrapper.ship.getDimensionType() ~= 1, by)
end
window:addChild(GUI.button(window.width - 9, 3, 9, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Refresh")).onTouch = function()
windows.apps.jumpWindow.update()
end
window:addChild(GUI.button(window.width - 13, 5, 13, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Cancel jump")).onTouch = function(_, _, _, _, _, _, _, by)
wrapper.ship.cancelJump()
logCancelJump(wrapper.ship.getShipName(), by)
end
windows.apps.jumpWindow.currentWindow = window
return window
end
}
windows.apps.shipInfoWindow = {
name = "Ship Info",
currentWindow = nil,
check = function()
if not wrapper.shipApiAvailable() then
GUI.alert("Ship is not available.")
return false
end
return true
end,
update = function()
if windows.apps.shipInfoWindow.currentWindow then
x = windows.apps.shipInfoWindow.currentWindow.x
y = windows.apps.shipInfoWindow.currentWindow.y
windows.apps.shipInfoWindow.currentWindow:remove()
app:addChild(windows.apps.shipInfoWindow.getWindow(x, y))
end
end,
getWindow = function(x, y)
local window = iTitledWindow(x, y, 57, 13, "Ship Info")
local x, y, z = wrapper.ship.getPosition()
window:addChild(GUI.label(2, 3, 8, 1, colors.textColor, "Coordinates:"))
window:addChild(GUI.label(2, 4, 8, 1, colors.textColor, x))
window:addChild(GUI.label(2, 5, 8, 1, colors.textColor, y))
window:addChild(GUI.label(2, 6, 8, 1, colors.textColor, z))
local dim = wrapper.ship.getDimensionType()
if dim == 0 then dim = "Space" elseif dim == 1 then dim = "Hyperspace" else dim = "Unknown" end
window:addChild(GUI.label(2, 8, 8, 1, colors.textColor, "Dimension:"))
window:addChild(GUI.label(2, 9, 8, 1, colors.textColor, dim))
local oX, oZ = wrapper.ship.getOrientation()
window:addChild(GUI.label(2, 11, 8, 1, colors.textColor, "Orientation:"))
window:addChild(GUI.label(2, 12, 8, 1, colors.textColor, string.format("X: %s, Z: %s", oX, oZ)))
window:addChild(GUI.label(17, 3, 8, 1, colors.textColor, string.format("Name: %s", wrapper.ship.getShipName())))
window:addChild(GUI.label(17, 5, 8, 1, colors.textColor, string.format("Mass: %s", wrapper.ship.getShipMass())))
local assembly
if wrapper.ship.isAssemblyValid() then assembly = "Valid" else assembly = "Invalid" end
window:addChild(GUI.label(17, 7, 8, 1, colors.textColor, string.format("Assembly: %s", assembly)))
local shipEnergy = wrapper.ship.getShipEnergy()
local maxEnergy = wrapper.ship.getMaxShipEnergy()
local energyPercents = math.floor((shipEnergy / maxEnergy) * 100)
window:addChild(GUI.progressBar(17, 9, 40, colors.mainColor, colors.button, colors.textColor, energyPercents, true, true, "Ship energy: ", "%"))
window:addChild(GUI.button(window.width - 9, window.height - 1, 9, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Refresh")).onTouch = function()
windows.apps.shipInfoWindow.update()
end
windows.apps.shipInfoWindow.currentWindow = window
return window
end
}
windows.apps.radarWindow = {
name = "WarpRadar",
currentWindow = nil,
lastTextBox = {},
scanInProcess = false,
check = function()
if not wrapper.radarApiAvailable() then
GUI.alert("Radar is not available.")
return false
end
return true
end,
update = function()
if windows.apps.radarWindow.currentWindow then
x = windows.apps.radarWindow.currentWindow.x
y = windows.apps.radarWindow.currentWindow.y
windows.apps.radarWindow.currentWindow:remove()
app:addChild(windows.apps.radarWindow.getWindow(x, y))
end
end,
getWindow = function(x, y)
local window = iTitledWindow(x, y, 57, 40, "WarpRadar")
local radarRadius = 1
local scannedBy = ""
local energyPercents = math.floor((wrapper.radar.getRadarEnergy() / wrapper.radar.getMaxRadarEnergy()) * 100 + 0.5)
window:addChild(GUI.button(window.width - 10, 3, 9, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Refresh")).onTouch = function()
windows.apps.radarWindow.update()
end
window:addChild(GUI.progressBar(2, 3, 40, colors.mainColor, colors.button, colors.textColor, energyPercents, true, true, "Radar energy: ", "%"))
local slider = window:addChild(GUI.slider(4, 6, 40, colors.mainColor, colors.button, colors.buttonPressed, colors.textColor, 1, 9999, 1, true, "Radar radius: ", " blocks"))
slider.roundValues = true
slider.onValueChanged = function()
radarRadius = math.round(slider.value)
end
window:addChild(GUI.label(2, 9, 8, 1, colors.textColor, "Limit radius to current energy:"))
switch = window:addChild(GUI.switch(35, 9, 8, colors.mainColor, colors.button, colors.buttonPressed, false))
switch.onStateChanged = function()
if switch.state then
local newMaximum = 10 * (10*wrapper.radar.getRadarEnergy())^(1/3)
slider.maximumValue = newMaximum
local newSliderValue = slider.value
if newSliderValue > newMaximum then newSliderValue = newMaximum end
slider.value = newSliderValue
slider.onValueChanged()
else
slider.maximumValue = 9999
slider.onValueChanged()
end
end
local list = window:addChild(GUI.list(2, 11, 55, 29, 0, 0, colors.button, colors.textColor, colors.buttonPressed, colors.textColor, colors.button, colors.textColor, colors.textColor, false))
list.children = windows.apps.radarWindow.lastTextBox
window:addChild(GUI.button(window.width - 7, 9, 6, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Scan")).onTouch = function(_, _, _, _, _, _, _, by)
if wrapper.radar.getRadarEnergy() < wrapper.radar.getRequiredEnergy(radarRadius) then
GUI.alert("Not enough energy for this scan!")
return
elseif windows.apps.radarWindow.scanInProcess then
return
end
wrapper.radar.scan(radarRadius)
windows.apps.radarWindow.scanInProcess = true
windows.apps.radarWindow.scannedBy = by
end
local obj = app:addChild(GUI.object(0, 0, 1, 1))
obj.eventHandler = function(app, obj, event, count)
if event ~= "is2wrapperRadarScan" then
return
end
windows.apps.radarWindow.scanInProcess = false
list.children = {}
if count < 1 then
iListAddItem(list, "Nothing was found :(", {})
app:draw()
-- windows.apps.radarWindow.lastTextBox = textBox.lines
return
end
for i = 0, count do
local objectType, name, x, y, z, mass = wrapper.radar.getResult(i)
if objectType ~= nil then
iListAddItem(list, string.format("%s %s, X: %s, Y: %s, Z: %s, M: %s", objectType, name, x, y, z, mass), {x, y, z})
end
end
windows.apps.radarWindow.lastTextBox = list.children
local logOutput = {}
for _, v in pairs(list.children) do
table.insert(logOutput, v.text)
end
logRadar(logOutput, wrapper.ship.getShipName(), windows.apps.radarWindow.scannedBy)
app:draw()
end
windows.apps.radarWindow.currentWindow = window
return window
end
}
windows.apps.transporterWindow = {
name = "Transporter",
currentWindow = nil,
check = function()
if not wrapper.transporterApiAvailable() then
GUI.alert("Transporter is not available.")
return false
end
return true
end,
update = function()
if windows.apps.transporterWindow.currentWindow then
x = windows.apps.transporterWindow.currentWindow.x
y = windows.apps.transporterWindow.currentWindow.y
windows.apps.transporterWindow.currentWindow:remove()
app:addChild(windows.apps.transporterWindow.getWindow(x, y))
end
end,
getWindow = function(x, y)
local window = iTitledWindow(x, y, 20, 12, "MO Transporter")
local x = 0
local y = 0
local z = 0
window:addChild(GUI.label(2, 3, 8, 1, colors.textColor, "Enter coordinates:"))
window:addChild(GUI.label(2, 5, 2, 1, colors.textColor, "X:"))
window:addChild(iIntInput(5, 5, 10, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, "", "X", false)).onInputFinished = function(_, input)
x = tonumber(input.text)
end
window:addChild(GUI.label(2, 7, 2, 1, colors.textColor, "Y:"))
window:addChild(iIntInput(5, 7, 10, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, "", "Y", false)).onInputFinished = function(_, input)
y = tonumber(input.text)
end
window:addChild(GUI.label(2, 9, 2, 1, colors.textColor, "Z:"))
window:addChild(iIntInput(5, 9, 10, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, "", "Z", false)).onInputFinished = function(_, input)
z = tonumber(input.text)
end
window:addChild(GUI.button(window.width - 5, 11, 5, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Set")).onTouch = function()
wrapper.transporter.setCoordinates(x, y, z)
end
windows.apps.transporterWindow.currentWindow = window
return window
end
}
windows.apps.settingsWindow = {
name = "Settings",
currentWindow = nil,
check = function()
return true
end,
update = function()
if windows.apps.settingsWindow.currentWindow then
x = windows.apps.settingsWindow.currentWindow.x
y = windows.apps.settingsWindow.currentWindow.y
windows.apps.settingsWindow.currentWindow:remove()
app:addChild(windows.apps.settingsWindow.getWindow(x, y))
end
end,
getWindow = function(x, y)
local window = iTabbedWindow(x, y, 80, 30, "Settings")
local container = window:addChild(GUI.container(1, 5, window.width, window.height - 4))
window.tabBar:addItem("Logging").onTouch = function()
local logUrl = config["isProxyUrl"]
local enableLogging = config["isProxyEnabled"]
container:removeChildren()
container:addChild(GUI.label(2, 2, 8, 1, colors.textColor, "Logging feature is using InterstellarProxy. Please consult"))
container:addChild(GUI.label(2, 3, 8, 1, colors.textColor, "README.md if you don't know what it is."))
container:addChild(GUI.label(2, 5, 8, 1, colors.textColor, "Enable logging:"))
switch = container:addChild(GUI.switch(19, 5, 8, colors.mainColor, colors.button, colors.buttonPressed, enableLogging))
switch.onStateChanged = function()
enableLogging = switch.state
end
container:addChild(GUI.label(2, 7, 8, 1, colors.textColor, "InterstellarProxy URL:"))
container:addChild(iInput(2, 9, 25, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, logUrl, "URL")).onInputFinished = function(_, input)
logUrl = input.text
end
container:addChild(GUI.button(window.width - 6, container.height - 1, 6, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Save")).onTouch = function()
config["isProxyUrl"] = logUrl
config["isProxyEnabled"] = enableLogging
saveParams()
end
container:addChild(GUI.button(window.width - 26, container.height - 1, 19, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Send test request")).onTouch = function()
logPos()
end
app:draw()
end
window.tabBar:addItem("Ship").onTouch = function()
container:removeChildren()
if not wrapper.shipApiAvailable() then
container:addChild(GUI.label(2, 2, 8, 1, colors.textColor, "Ship is not available. Settings aren't too. Please, connect your ship."))
app:draw()
return
end
local back, left, down = wrapper.ship.getDimNegative()
local front, right, up = wrapper.ship.getDimPositive()
local name = wrapper.ship.getShipName()
container:addChild(GUI.label(2, 3, 16, 1, colors.textColor, "Ship name:"))
container:addChild(iInput(2, 5, 30, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, name, "Имя корабля")).onInputFinished = function(container, input, eventData, text)
name = input.text
end
container:addChild(GUI.label(2, 7, 16, 1, colors.textColor, "Ship dimensions:"))
container:addChild(GUI.label(2, 9, 16, 1, colors.textColor, "Front"))
container:addChild(iIntInput(2, 10, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, front, "Кол-во блоков")).onInputFinished = function(_, input)
front = tonumber(input.text)
end
container:addChild(GUI.label(2, 12, 16, 1, colors.textColor, "Back"))
container:addChild(iIntInput(2, 13, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, back, "Кол-во блоков")).onInputFinished = function(_, input)
back = tonumber(input.text)
end
container:addChild(GUI.label(2, 15, 16, 1, colors.textColor, "Up"))
container:addChild(iIntInput(2, 16, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, up, "Кол-во блоков")).onInputFinished = function(_, input)
up = tonumber(input.text)
end
container:addChild(GUI.label(20, 9, 16, 1, colors.textColor, "Down"))
container:addChild(iIntInput(20, 10, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, down, "Кол-во блоков")).onInputFinished = function(_, input)
down = tonumber(input.text)
end
container:addChild(GUI.label(20, 12, 16, 1, colors.textColor, "Left"))
container:addChild(iIntInput(20, 13, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, left, "Кол-во блоков")).onInputFinished = function(_, input)
left = tonumber(input.text)
end
container:addChild(GUI.label(20, 15, 16, 1, colors.textColor, "Right"))
container:addChild(iIntInput(20, 16, 13, 1, colors.inputBackground, colors.inputText, colors.inputPlaceholderText, colors.inputBackgroundFocused, colors.inputTextFocused, right, "Кол-во блоков")).onInputFinished = function(_, input)
right = tonumber(input.text)
end
container:addChild(GUI.button(window.width - 6, container.height - 1, 6, 1, colors.button, colors.buttonText, colors.buttonPressed, colors.buttonTextPressed, "Save")).onTouch = function()
wrapper.ship.setShipName(name)
wrapper.ship.setDimNegative(back, left, down)
wrapper.ship.setDimPositive(front, right, up)
end
app:draw()
end
window.tabBar:getItem(window.tabBar.selectedItem).onTouch()
windows.apps.settingsWindow.currentWindow = window
return window
end
}
------------------------------------------------------------------------
local maxRes = {}
maxRes[1], maxRes[2] = gpu.maxResolution()
if gpu.getDepth() < 4 and (maxRes[1] < 80 and maxRes[2] < 25) then
io.stderr:write("Ошибка: ваша видеокарта не подходит для данной программы.")
end
loadParams()
logPos()
local res = {}
res[1], res[2] = gpu.getResolution()
if (res[1] < 100) and (res[2] < 40) then
gpu.setResolution(160, 50)
end
buffer.setResolution(res[1], res[2])
app:addChild(GUI.panel(1, 1, app.width, app.height, colors.desktopBackground))
if config.firstLaunchWindow then
app:addChild(windows.firstLaunchWindow(5, 5))
else
app:addChild(windows.mainWindow(5, 5))
end
app:addChild(windows.debug(5, 30))
------------------------------------------------------------------------
app:draw(true)
app:start() |
local Component = require("cokeline/components").Component
local sliders = require("cokeline/sliders")
local utils = require("cokeline/utils")
local insert = table.insert
local echo = vim.api.nvim_echo
local islist = vim.tbl_islist
local defaults = {
show_if_buffers_are_at_least = 1,
buffers = {
filter_valid = false,
filter_visible = false,
focus_on_delete = false,
new_buffers_position = "last",
},
mappings = {
cycle_prev_next = true,
},
rendering = {
max_buffer_width = 999,
slider = sliders.center_current_buffer,
},
---@type table<string, any>
default_hl = {
fg = function(buffer)
return buffer.is_focused and utils.get_hex("ColorColumn", "bg")
or utils.get_hex("Normal", "fg")
end,
bg = function(buffer)
return buffer.is_focused and utils.get_hex("Normal", "fg")
or utils.get_hex("ColorColumn", "bg")
end,
style = "NONE",
},
---@type Component[]
components = {
{
text = function(buffer)
return " " .. buffer.devicon.icon
end,
fg = function(buffer)
return buffer.devicon.color
end,
},
{
text = function(buffer)
return buffer.unique_prefix
end,
fg = utils.get_hex("Comment", "fg"),
style = "italic",
},
{
text = function(buffer)
return buffer.filename .. " "
end,
},
{
text = "",
delete_buffer_on_left_click = true,
},
{
text = " ",
},
},
sidebar = false,
}
-- Formats an error message.
---@param msg string
local echoerr = function(msg)
echo({
{ "[nvim-cokeline]: ", "ErrorMsg" },
{ 'Configuration option "' },
{ msg, "WarningMsg" },
{ '" does not exist!' },
}, true, {})
end
-- Updates the `settings` table with options from `preferences`, printing an
-- error message if a configuration option in `preferences` is not defined in
-- `settings`.
---@param settings table
---@param preferences table
---@param key string | nil
---@return table
local function update(settings, preferences, key)
local updated = settings
for k, v in pairs(preferences) do
local key_tree = key and ("%s.%s"):format(key, k) or k
if settings[k] == nil then
echoerr(key_tree)
else
updated[k] = (
type(v) == "table"
and not islist(v)
and not k:find("sidebar")
)
and update(settings[k], v, key_tree)
or v
end
end
return updated
end
local get = function(preferences)
local config = update(defaults, preferences)
_G.cokeline.components = {}
for i, component in ipairs(config.components) do
insert(
_G.cokeline.components,
Component.new(component, i, config.default_hl)
)
end
return config
end
return {
get = get,
}
|
--[[
--=====================================================================================================--
Script Name: One In The Chamber (v1.2), for SAPP (PC & CE)
Description: Each player is given a pistol - and only a pistol - with one bullet.
Use it wisely. Every shot kills.
If you miss, you're limited to Melee-Combat.
Every time you kill a player, you get a bullet.
Success requires a combination of precision and reflexes. Know when to go for the shot or close in for the kill.
Copyright (c) 2019-2020, Jericho Crosby <jericho.crosby227@gmail.com>
* Notice: You can use this document subject to the following conditions:
https://github.com/Chalwk77/HALO-SCRIPT-PROJECTS/blob/master/LICENSE
--=====================================================================================================--
]]--
api_version = "1.12.0.0"
--====================================== --
-- Configuration [STARTS]
--====================================== --
local OITC = {
-- Loaded Ammo (clip):
starting_primary_ammo = 1,
-- Unloaded Ammo: (Mag):
starting_secondary_ammo = 0,
-- Bullets given per kill:
ammo_per_kill = 1,
-- Starting Grenades:
starting_frags = 0,
starting_plasmas = 0,
-- Primary Weapon:
weapon = "weapons\\pistol\\pistol",
-- Heads Up Display Message:
hud_message = "Bullets: %count%",
-- Miscellaneous Settings:
disable_vehicles = true,
disable_weapon_pickups = true,
disable_grenade_pickups = true,
remove_grenades_on_spawn = true,
--===========================================--
-- DAMAGE MULTIPLIERS | STOCK TAGS --
-- {tag name, multiplier }
-- 1 = normal damage
multipliers = {
melee = {
{ "weapons\\assault rifle\\melee", 1.50 },
{ "weapons\\ball\\melee", 1.50 },
{ "weapons\\flag\\melee", 1.50 },
{ "weapons\\flamethrower\\melee", 1.50 },
{ "weapons\\needler\\melee", 1.50 },
{ "weapons\\pistol\\melee", 1.50 },
{ "weapons\\plasma pistol\\melee", 1.50 },
{ "weapons\\plasma rifle\\melee", 1.50 },
{ "weapons\\rocket launcher\\melee", 1.50 },
{ "weapons\\shotgun\\melee", 1.50 },
{ "weapons\\sniper rifle\\melee", 1.50 },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", 1.50 },
},
grenades = {
{ "weapons\\frag grenade\\explosion", 1.00 },
{ "weapons\\plasma grenade\\explosion", 1.50 },
{ "weapons\\plasma grenade\\attached", 10.0 },
},
vehicles = {
{ "vehicles\\ghost\\ghost bolt", 1.015 },
{ "vehicles\\scorpion\\bullet", 1.020 },
{ "vehicles\\warthog\\bullet", 1.025 },
{ "vehicles\\c gun turret\\mp bolt", 1.030 },
{ "vehicles\\banshee\\banshee bolt", 1.035 },
{ "vehicles\\scorpion\\shell explosion", 1.00 },
{ "vehicles\\banshee\\mp_fuel rod explosion", 1.00 },
},
projectiles = {
{ "weapons\\pistol\\bullet", 10.0 },
{ "weapons\\plasma rifle\\bolt", 10.0 },
{ "weapons\\shotgun\\pellet", 10.0 },
{ "weapons\\plasma pistol\\bolt", 10.0 },
{ "weapons\\needler\\explosion", 10.0 },
{ "weapons\\assault rifle\\bullet", 10.0 },
{ "weapons\\needler\\impact damage", 10.0 },
{ "weapons\\flamethrower\\explosion", 10.0 },
{ "weapons\\sniper rifle\\sniper bullet", 10.0 },
{ "weapons\\rocket launcher\\explosion", 10.0 },
{ "weapons\\needler\\detonation damage", 10.0 },
{ "weapons\\plasma rifle\\charged bolt", 10.0 },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_melee", 10.0 },
{ "weapons\\plasma_cannon\\effects\\plasma_cannon_explosion", 10.0 },
},
vehicle_collision = {
{ "globals\\vehicle_collision", 1.00 },
},
fall_damage = {
{ "globals\\falling", 1.00 },
{ "globals\\distance", 1.00 },
},
}
}
--====================================== --
-- Configuration [ENDS]
--====================================== --
local gsub = string.gsub
function OnScriptLoad()
register_callback(cb["EVENT_TICK"], "OnTick")
register_callback(cb['EVENT_DIE'], "OnPlayerKill")
register_callback(cb["EVENT_GAME_END"], "OnGameEnd")
register_callback(cb["EVENT_GAME_START"], "OnGameStart")
register_callback(cb["EVENT_SPAWN"], "OnPlayerSpawn")
register_callback(cb["EVENT_LEAVE"], "OnPlayerDisconnect")
register_callback(cb['EVENT_DAMAGE_APPLICATION'], "OnDamageApplication")
OnGameStart()
end
function OnGameStart()
if (get_var(0, "$gt") ~= "n/a") then
OITC.players = { }
OITC.game_over = false
for i = 1, 16 do
if player_present(i) then
OITC.players[i] = { assign = true }
end
end
-- Disable all vehicles
if (OITC.disable_vehicles) then
execute_command("disable_all_vehicles 0 1")
end
-- Disable weapon pick ups:
if (OITC.disable_weapon_pickups) then
execute_command("disable_object 'weapons\\assault rifle\\assault rifle'")
execute_command("disable_object 'weapons\\flamethrower\\flamethrower'")
execute_command("disable_object 'weapons\\needler\\mp_needler'")
execute_command("disable_object 'weapons\\pistol\\pistol'")
execute_command("disable_object 'weapons\\plasma pistol\\plasma pistol'")
execute_command("disable_object 'weapons\\plasma rifle\\plasma rifle'")
execute_command("disable_object 'weapons\\plasma_cannon\\plasma_cannon'")
execute_command("disable_object 'weapons\\rocket launcher\\rocket launcher'")
execute_command("disable_object 'weapons\\shotgun\\shotgun'")
execute_command("disable_object 'weapons\\sniper rifle\\sniper rifle'")
end
-- Disable grenade pick ups:
if (OITC.disable_grenade_pickups) then
execute_command("disable_object 'weapons\\frag grenade\\frag grenade'")
execute_command("disable_object 'weapons\\plasma grenade\\plasma grenade'")
end
end
end
function OnGameEnd()
OITC.game_over = true
end
local function GetXYZ(Ply)
local DyN = get_dynamic_player(Ply)
if (DyN ~= 0) then
local VehicleID = read_dword(DyN + 0x11C)
if (VehicleID == 0xFFFFFFFF) then
return read_vector3d(DyN + 0x5c)
end
end
return nil
end
local function cls(Ply, Count)
Count = Count or 25
for _ = 1, Count do
rprint(Ply, " ")
end
end
function OITC:SetAmmo(Ply, Type, Amount)
for i = 1, 4 do
if (Type == "unloaded") then
execute_command("ammo " .. Ply .. " " .. Amount .. " " .. i)
elseif (Type == "loaded") then
execute_command("mag " .. Ply .. " " .. Amount .. " " .. i)
end
end
cls(Ply, 25)
local ammo = OITC:GetAmmo(Ply, "loaded")
rprint(Ply, gsub(self.hud_message, "%%count%%", ammo))
end
function OITC:OnTick()
if (not self.game_over) then
for i, v in pairs(self.players) do
if player_alive(i) and (v.assign) then
local x, y, z = GetXYZ(i)
if (x) then
v.assign = false
execute_command("wdel " .. i)
assign_weapon(spawn_object("weap", self.weapon, x, y, z), i)
self:SetAmmo(i, "loaded", self.starting_primary_ammo)
self:SetAmmo(i, "unloaded", self.starting_secondary_ammo)
end
end
end
end
end
function OITC:OnPlayerKill(VictimIndex, KillerIndex)
if (not self.game_over) then
local k, v = tonumber(KillerIndex), tonumber(VictimIndex)
if (k > 0 and k ~= v) then
local ammo = OITC:GetAmmo(k, "loaded") + (self.ammo_per_kill)
self:SetAmmo(k, "loaded", ammo)
end
end
end
function OITC:GetAmmo(Ply, Type)
local DyN = get_dynamic_player(Ply)
if (DyN ~= 0) then
local WeaponID = read_dword(DyN + 0x118)
if (WeaponID ~= 0) then
local WeaponObject = get_object_memory(WeaponID)
if (WeaponObject ~= 0) then
if (Type == "unloaded") then
return read_dword(WeaponObject + 0x2B6)
elseif (Type == "loaded") then
return read_dword(WeaponObject + 0x2B8)
end
end
end
end
return 0
end
function OnPlayerSpawn(Ply)
local DyN = get_dynamic_player(Ply)
if (DyN ~= 0) then
OITC.players[Ply] = { assign = true }
if (OITC.remove_grenades_on_spawn) then
write_byte(DyN + 0x31E, OITC.starting_frags)
write_byte(DyN + 0x31F, OITC.starting_plasmas)
end
end
end
local function GetTag(obj_type, obj_name)
local tag = lookup_tag(obj_type, obj_name)
return tag ~= 0 and read_dword(tag + 0xC) or nil
end
function OnDamageApplication(V, C, MetaID, Damage, _, _)
if (tonumber(C) > 0 and V ~= C) then
for Table, _ in pairs(OITC.multipliers) do
for _, Tag in pairs(OITC.multipliers[Table]) do
if (Tag[1]) then
if (MetaID == GetTag("jpt!", Tag[1])) then
return true, Damage * Tag[2]
end
end
end
end
end
end
function OnPlayerDisconnect(Ply)
OITC.players[Ply] = nil
end
function OnScriptUnload()
-- N/A
end
function OnTick()
return OITC:OnTick()
end
function OnPlayerKill(V, K)
return OITC:OnPlayerKill(V, K)
end |
VBLANG = VBLANG or {}
VBLANG.__index = VBLANG
VBLANG.Language = {}
VBLANG.Language.French = {}
VBLANG.Language.English = {}
VBLANG.CurrentLanguage = "French"
function Translate(phrase, ...)
if not VBLANG.Language[VBLANG.CurrentLanguage][phrase] then
return "[TranslationManager] Translation not found"
end
if ... ~= nil then
return string.format(VBLANG.Language[VBLANG.CurrentLanguage][phrase], ...)
end
return VBLANG.Language[VBLANG.CurrentLanguage][phrase]
end |
-- LSTM training framework for hdf5 data
-- Author: Pau Rodríguez López (@prlz77)
-- Mail: pau.rodri1 at gmail.com
-- Institution: ISELAB in CVC-UAB
-- Date: 14/06/2016
-- Description: Performs regression and classification with a LSTM neural
-- network on arbitrary sequential hdf5 data in the form n-to-one.
-- It also has plotting features and saves outputs for further processing.
require 'rnn'
require 'cutorch'
require 'cunn'
--require 'cudnn'
require 'optim'
require 'paths'
require 'gnuplot'
require 'math'
--[[command line arguments]]--
cmd = torch.CmdLine()
cmd:text()
cmd:text('Train a dataset using LSTM')
cmd:text('Example:')
cmd:text("LSTM.lua --rho 10")
cmd:text('Options:')
cmd:option('--trainPath', '', 'train.h5 path')
cmd:option('--valPath', '', 'validation.h5 path')
cmd:option('--learningRate', 0.01, 'learning rate at t=0')
cmd:option('--momentum', 0.9, 'momentum')
cmd:option('--batchSize', 32, 'number of examples per batch')
cmd:option('--testBatchSize', 0, 'number of examples per test batch (0 = same as train)')
-- model i/0
cmd:option('--load', '', 'Load LSTM pre-trained weights')
cmd:option('--saveOutputs', '', '.h5 file path to save outputs')
cmd:option('--saveBestAuc', '', '.h5 file path to save best outputs')
cmd:option('--saveBestMSE', '', '.h5 file path to save best test mse outputs')
cmd:option('--targetName', 'labels', 'target field name in the h5 file')
cmd:option('--labelOffset', 0, '1 to sum 1 to all labels')
--cmd:option('--cuda', false, 'use CUDA')
cmd:option('--useDevice', 1, 'sets the device (GPU) to use')
cmd:option('--maxEpoch', 1000, 'maximum number of epochs to run')
--cmd:option('--maxTries', 50, 'maximum number of epochs to try to find a better local minima for early-stopping')
cmd:option('--uniform', 0.1, 'initialize parameters using uniform distribution between -uniform and uniform. -1 means default initialization')
-- recurrent layer
cmd:option('--maskzero', false, 'mask zero flag')
cmd:option('--rho', 5, 'back-propagate through time (BPTT) for rho time-steps')
cmd:option('--hiddenSize', 200, 'number of hidden units used at output of each recurrent layer. When more than one is specified, RNN/LSTMs/GRUs are stacked')
cmd:option('--depth', 1, 'number of hidden layers')
--cmd:option('--zeroFirst', false, 'first step will forward zero through recurrence (i.e. add bias of recurrence). As opposed to learning bias specifically for first step.')
cmd:option('--dropoutProb', 0.5, 'probability of zeroing a neuron (dropout probability)')
-- loss
cmd:option('--task', 'regress', 'main LSTM task [regress | classify]')
cmd:option('--criterion', 'MSECriterion', 'loss type')
cmd:option('--nlabels', 0, 'number of output neurons (max(labels) by default)')
cmd:option('--balanceWeights', false, 'whether to weight labels')
-- other
cmd:option('--printEvery', 0, 'print loss every n iters')
cmd:option('--testEvery', 1, 'print test accuracy every n epochs')
cmd:option('--logPath', '', 'log here')
cmd:option('--confMat', '', 'save confusion matrix here')
cmd:option('--savePath', './snapshots', 'save snapshots here')
cmd:option('--saveEvery', 0, 'number of epochs to save model snapshot')
cmd:option('--plotRegression', 0, 'number of epochs to plot regression approximation')
cmd:option('--testOnly', false, 'Test only flag')
cmd:option('--auc', false, 'Save auc flag')
cmd:option('--earlyStop', 0, 'Stop when test error plateaus for n epochs.')
cmd:text()
opt = cmd:parse(arg or {})
-- Set test batch size
if opt.testBatchSize == 0 then
opt.testBatchSize = opt.batchSize
end
-- Different data loaders if we need to mask with zeros
if opt.maskzero == true then
print('Using masked data reader')
require 'masked_data_loader'
else
print('Using batch interleaving')
require 'data_loader'
end
-- choose device
cutorch.setDevice(opt.useDevice)
-- setting earlyStopping to max Epochs if necessary.
if opt.earlyStop == 0 then
opt.earlyStop = opt.maxEpoch
end
-- snapshots folder
if opt.saveEvery ~= 0 then
opt.savePath=paths.concat(opt.savePath, os.date("%d_%m_%y-%T"))
paths.mkdir(opt.savePath)
end
--log path settings
if opt.logPath == '' then
paths.mkdir('./logs')
opt.logPath = paths.concat('./logs', os.date("%d_%m_%y-%T")..'.log')
else
paths.mkdir(paths.dirname(opt.logPath))
end
-- initialize dataset
local hdf5_fields = {data='outputs', labels=opt.targetName, seq='seq_number'}
if opt.maskzero == true then
trainDB = SequentialDB(opt.trainPath, opt.batchSize, false, hdf5_fields, opt.labelOffset)
valDB = SequentialDB(opt.valPath, opt.testBatchSize, false, hdf5_fields, opt.labelOffset) --bs=1 to loop only once through all the data.
opt.trainRho = trainDB.rho
opt.valRho = valDB.rho
else
--TODO add label offsets to basic sequential db
trainDB = SequentialDB(opt.trainPath, opt.batchSize, opt.rho, false, hdf5_fields)
valDB = SequentialDB(opt.valPath, opt.testBatchSize, opt.rho, false, hdf5_fields) --bs=1 to loop only once through all the data.
opt.trainRho = opt.rho
opt.valRho = opt.rho
end
local trainIters = math.floor(trainDB.N / trainDB.bs)
local valIters = math.floor(valDB.N / valDB.bs)
local dataDim = trainDB.dim[2]*trainDB.dim[3]*trainDB.dim[4] -- get flat data dimensions
-- start logger
logger = optim.Logger(opt.logPath)
local names = {'epoch', 'train_error', 'test_error'}
if opt.auc then
table.insert(names,'auc')
end
if opt.task == 'classify' then
table.insert(names, 'accuracy')
end
logger:setNames(names)
if opt.load == '' then
-- turn on recurrent batchnorm
nn.FastLSTM.bn = true
-- build LSTM RNN
rnn = nn.Sequential()
rnn:add(nn.SplitTable(1,2)) -- (bs, rho, dim)
local lstm = nn.FastLSTM(dataDim, opt.hiddenSize)
if opt.maskzero == true then
lstm = lstm:maskZero(1)
end
rnn = rnn:add(nn.Sequencer(lstm))
if opt.dropoutProb > 0 then
rnn = rnn:add(nn.Sequencer(nn.Dropout(opt.dropoutProb)))
end
for d = 1,(opt.depth - 1) do
local lstm = nn.FastLSTM(opt.hiddenSize, opt.hiddenSize)
if opt.maskzero == true then
lstm = lstm:maskZero(1)
end
rnn = rnn:add(nn.Sequencer(lstm))
if opt.dropoutProb > 0 then
rnn = rnn:add(nn.Sequencer(nn.Dropout(opt.dropoutProb)))
end
end
rnn:add(nn.SelectTable(-1))
if opt.task == 'regress' then
rnn = rnn:add(nn.Linear(opt.hiddenSize, trainDB.ldim[2]))
else
if opt.labelOffset == 0 then
trainDB:minLabelToOne()
valDB:minLabelToOne()
end
if opt.nlabels > 0 then
nlabels = opt.nlabels
else
nlabels = trainDB.maxLabel -- warning, it must be after calling minLabelToOne
end
rnn = rnn:add(nn.Linear(opt.hiddenSize, nlabels))
end
-- CPU -> GPU
rnn:cuda()
if nlabels and opt.confMat ~= '' then
-- Confusion matrix
fConfMat = io.open(opt.confMat, 'w')
confusion = optim.ConfusionMatrix(nlabels)
end
-- random init weights
for k,param in ipairs(rnn:parameters()) do
param:uniform(-opt.uniform, opt.uniform)
end
else --pre-trained model
rnn = torch.load(opt.model)
end
-- show the network
print(rnn)
-- build criterion
local criterion
if opt.task == 'regress' then
criterion = nn[opt.criterion]():cuda()
else
if opt.balanceWeights == true then
local weights = trainDB:getLabelWeights()
print("Label importance: ", 1 - weights)
criterion = nn.CrossEntropyCriterion(1 - weights):cuda()
else
criterion = nn.CrossEntropyCriterion():cuda()
end
end
print(criterion)
-- optimizer state
local optimState = {learningRate = opt.learningRate}
parameters, gradParameters = rnn:getParameters()
-- save only the necessary values
lightModel = rnn:clone('weight','bias','running_mean','running_std')
--set current epoch
local epoch = 1
-- train loop
function train()
print(optimState)
rnn:training()
-- Compute gradients
local feval = function(x)
if x ~= parameters then parameters:copy(x) end
gradParameters:zero()
inputs, targets = trainDB:getBatch()
inputs = inputs:resize(trainDB.bs, opt.trainRho, dataDim):cuda()
targets = targets[{{},-1,{}}]:resize(trainDB.bs, valDB.ldim[2]):cuda()
outputs = rnn:forward(inputs)
local f = criterion:forward(outputs, targets)
local df_do = criterion:backward(outputs, targets)
rnn:backward(inputs, df_do)
--clip gradients
rnn:gradParamClip(5)
return f,gradParameters
end
-- keep avg loss
local loss = 0
for iter = 1, trainIters do
parameters, f = optim.adam(feval, parameters, optimState) -- update params.
xlua.progress(iter, trainIters)
if iter % opt.printEvery == 0 then
print('Iter: '..iter..', loss: '..loss )
end
loss = loss + f[1]
end
return loss / trainIters
end
local auc = function(outputs, targets)
-- sort the scores:
if not outputs:nElement() == 0 then return 0.5 end
local scores, sortind = torch.sort(outputs, 1, true)
-- construct the ROC curve:
local tpr = torch.DoubleTensor(outputs:nElement() + 1):zero()
local fpr = torch.DoubleTensor(outputs:nElement() + 1):zero()
for n = 2,scores:nElement() + 1 do
if targets[sortind[n - 1]] == 1 then
tpr[n], fpr[n] = tpr[n - 1] + 1, fpr[n - 1]
else
tpr[n], fpr[n] = tpr[n - 1], fpr[n - 1] + 1
end
end
tpr:div(targets:sum())
fpr:div(torch.mul(targets, -1):add(1):sum())
-- compute AUC:
local auc = torch.cmul(
tpr:narrow(1, 1, tpr:nElement() - 1),
fpr:narrow(1, 2, fpr:nElement() - 1) -
fpr:narrow(1, 1, fpr:nElement() - 1)):sum()
-- return AUC and ROC curve:
return auc, tpr, fpr
end
-- auxiliar variables
aucScore = 0
local bestAuc = -1
local bestMSE = 10000000
local bestEpoch = 1
-- Test loop
function test()
rnn:evaluate()
-- Discard last frames to make it multiple of rho*batchSize
valDB:reset()
-- keep avg loss
local loss = 0
local outputHist = {}
local targetHist = {}
local saveHist = (opt.plotRegression ~= 0 or opt.auc or opt.saveOutputs ~= '' or opt.saveBestAuc ~= '' or opt.saveBestMSE ~= '' or opt.confMat ~= '' )
accuracy = 0
-- restart confusion matrix
if confusion then
confusion:zero()
end
--local inputHist = {} uncomment if 1D
for iter = 1, valIters do
inputs, targets = valDB:getBatch()
inputs = inputs:resize(valDB.bs,opt.valRho,dataDim):cuda()
targets = targets[{{},-1,{}}]:resize(valDB.bs, valDB.ldim[2]):cuda()
local outputs = rnn:forward(inputs)
if opt.task == 'classify' then
max, ind = torch.max(outputs, 2)
accuracy = accuracy + ind:float():cuda():eq(targets):sum() / outputs:size(1)
end
if confusion then
confusion:batchAdd(outputs, targets)
end
if saveHist then
--inputHist[iter] = inputs[{{},-1,{}}]:float():view(-1) uncomment if 1D
outputHist[iter] = outputs:float():view(-1)
targetHist[iter] = targets:float():view(-1)
end
-- forward step
local f = criterion:forward(outputs, targets)
xlua.progress(iter, valIters)
loss = loss + f
end
loss = loss / valIters -- average loss
if opt.task == 'classify' then
accuracy = accuracy / valIters -- average accuracy
print('Accuracy ' .. accuracy)
end
-- Keep track of the best loss (MSE <-> LogLikelihood)
if loss < bestMSE then
bestMSE = loss
bestEpoch = epoch
end
if saveHist then
--inputHist = nn.JoinTable(1,1):forward(inputHist) uncomment if 1D
-- edge efects if rho > 1 because we need rho frames to predict the last one
outputHist_join = nn.JoinTable(1,1):forward(outputHist)
targetHist_join = nn.JoinTable(1,1):forward(targetHist)
if opt.auc then
aucScore, tpr, fpr = auc(outputHist_join, torch.gt(targetHist_join,0))
print('Auc:' .. aucScore)
end
if (epoch % opt.plotRegression) == 0 then
gnuplot.plot({'outputs', outputHist_join, '-'},{'targets', targetHist_join, '-'})
end
--gnuplot.plot({'inputs', inputHist, '.'},{'outputs', outputHist, '-'},{'targets', targetHist, '-'}) --uncomment if 1D
-- Blocks for saving on best auc, accuracy, etc.
if opt.saveOutputs ~= '' then
local output = hdf5.open(opt.saveOutputs, 'w')
output:write('outputs', outputHist_join)
output:write('labels', targetHist_join)
output:close()
end
if opt.saveBestAuc ~= '' and bestAuc < aucScore then
bestAuc = aucScore
local output = hdf5.open(opt.saveBestAuc, 'w')
output:write('outputs', outputHist_join)
output:write('labels', targetHist_join)
output:close()
end
if opt.saveBestMSE ~= '' and epoch == bestEpoch then
local output = hdf5.open(opt.saveBestMSE, 'w')
output:write('outputs', outputHist_join)
output:write('labels', targetHist_join)
output:close()
end
if confusion then
confusion:updateValids()
fConfMat:write('epoch: '..epoch..'\n')
fConfMat:write(confusion:__tostring__()..'\n')
fConfMat:flush()
end
end
return loss, outputs
end
-- main loop
while epoch < opt.maxEpoch do
local trainLoss = nil
-- train step
if not opt.testOnly then
print('epoch '..epoch..':')
print('Train:')
trainLoss = train()
print('Avg train loss: '..trainLoss)
end
local testLoss = nil
-- test step
if (epoch % opt.testEvery) == 0 then
print('Test:')
testLoss = test()
print('Avg test loss: '..testLoss)
end
-- logging
if opt.task == 'regress' then
if opt.auc then
logger:add({epoch, trainLoss, testLoss, aucScore})
else
logger:add({epoch, trainLoss, testLoss})
end
else
logger:add({epoch, trainLoss, testLoss, accuracy})
end
-- save snapshot
if (epoch % opt.saveEvery) == 0 then
torch.save(opt.savePath..'/model_'..epoch..'.t7',lightModel)
end
-- stop on plateau
if epoch - bestEpoch > opt.earlyStop then
os.exit()
end
epoch = epoch + 1
collectgarbage()
end
|
function doom.init()
common.init({
hideEnemyHealth = true,
hideNames = true
})
end
print("Loading particle...")
local bouncing = load_particle("bounce.obj")
local bouncing2 = load_particle("bounce2.obj")
local hurt = load_particle("hurt.obj")
local bouncing_shell = load_particle("shell_bounce.obj")
local bouncing_shell_shotgun = load_particle("shell_bounce_shotgun.obj")
local bouncing_meat = load_particle("meat_bounce.obj")
---slimpack
local slimpack = load_particle("slimpack_heal.obj")
local slimpack_speed = load_particle("slimpack_speed.obj")
local slimpack_loop = load_particle("slimpack_loop.obj")
---plasmablade
local plasmablade = load_particle("PlasmaBlade.obj")
local plasmablade_swing = load_particle("PlasmaBlade_Swing.obj")
local plasmablade_block = load_particle("plasmablade_block.obj")
local plasmablade_swing_sound = load_particle("plasmasaber_swing_sound.obj")
---Grenade
local grenade = load_particle("grenade.obj")
---Assault Rifle
local assaultrifle = load_particle("assaultrifle1_bullet.obj")
---BFG blaster
local bfg_big = load_particle("BFG_b.obj")
local bfg = load_particle("BFG.obj")
local bfg_flash = load_particle("flash_bfg.obj")
local bfg_flash_small = load_particle("flash_bfg_small.obj")
local bfg_flash_smallest = load_particle("flash_bfg_smallest.obj")
local bfg_small = load_particle("BFG_s.obj")
local bfg_smallest = load_particle("BFG_st.obj")
local bfg_sound_1 = load_particle("bfg_sound_1.obj")
local bfg_sound_2 = load_particle("bfg_sound_2.obj")
local bfg_sound_3 = load_particle("bfg_sound_3.obj")
local bfg_sound_4 = load_particle("bfg_sound_4.obj")
local bfg_firetrail = load_particle("bfg_firetrail.obj")
local bfg_sound_firestop = load_particle("bfg_sound_firestop.obj")
---Chaingun
local smoke = load_particle("chaingun_trail.obj")
---Flamethrower
local flames = load_particle("flamethrower_on.obj")
local flame_burner = load_particle("flamethrower_onfire.obj")
---Remote Bomb
local remotebomb = load_particle("remotebomb.obj")
local remotebomb_explode = load_particle("remotebomb_script_bang.obj")
local remotebomb_select = load_particle("remotebomb_select.obj")
local remotebomb_button = load_particle("remotebomb_button.obj")
local remotebomb_click = load_particle("click.obj")
---IonCannon
local ioncannon1 = load_particle("ioncannon_1.obj")
local ioncannon2 = load_particle("ioncannon_2.obj")
local ioncannonflash = load_particle("flash_ioncannon.obj")
local ion_charge_sound = sounds["ion_charge.ogg"]
function doom.bouncing(object)
if vector_distance( object:spd() ) > 0.2 then
object:shoot(bouncing, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
function doom.bouncing_heavy(object)
if vector_distance( object:spd() ) > 0.2 then
object:shoot(bouncing2, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
function doom.bouncing_shell(object)
if vector_distance( object:spd() ) > 0.2 then
object:shoot(bouncing_shell, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
function doom.bouncing_meat(object)
if vector_distance( object:spd() ) > 0.2 then
object:shoot(bouncing_meat, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
function doom.bouncing_shell_shotgun(object)
if vector_distance( object:spd() ) > 0.2 then
object:shoot(bouncing_shell_shotgun, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
function doom.parts_worm(object)
if vector_distance( object:spd() ) > 1.8 then
object:shoot(hurt, 1, 0, 0, 0, 0, 0, 0, 0)
end
end
----------------------------slimpack---------------------------
function doom.slimpack_speed_active(worm)
player = worm:player()
player:data().slimpack_speed = 1
player:data().slimpack_speed_sound = 1
player:data().slimpack_speed_posx, player:data().slimpack_speed_posy = player:worm():pos()
end
function doom.slimpack_speed_reset(worm)
player = worm:player()
player:data().slimpack_speed = nil
player:data().slimpack_speed_sound = nil
end
function doom.slimpack_speed(worm)
player = worm:player()
if player:data().slimpack_speed then
player:data().slimpack_speed = player:data().slimpack_speed + 1
player:data().slimpack_speed_sound = player:data().slimpack_speed_sound + 1
if player:is_local() then
local newx, newy = player:worm():pos()
local deltax = newx - player:data().slimpack_speed_posx
local deltay = newy - player:data().slimpack_speed_posy
player:worm():set_pos(newx + deltax + deltax , newy + deltay + deltay)
player:data().slimpack_speed_posx, player:data().slimpack_speed_posy = player:worm():pos()
end
if player:is_local()== false then
player:data().slimpack_speed = nil
player:data().slimpack_speed_sound = nil
end
if player:data().slimpack_speed % 5 == 0 then
worm:shoot(slimpack_speed, 1, -0.1, 0, 0, 0.5, 0, 0, -2)
end
if player:data().slimpack_speed_sound == 55 then
worm:shoot(slimpack_loop, 1, 0, 0, 0, 0, 0, 0, 0)
player:data().slimpack_speed_sound = 1
end
if player:data().slimpack_speed == 1200 then
player:data().slimpack_speed = nil
player:data().slimpack_speed_sound = nil
end
end
end
function doom.slimpack(object,target)
local healthexcess = target:health() - 125
while healthexcess > 0 do
healthexcess = healthexcess - 1
target:shoot(slimpack,1)
end
end
----------------------------needler----------------------------
function doom.lgrSetTarg(object)
local x,y = object:pos()
local player = object:player()
if player then
object:player():data().lgrTargX = x
object:player():data().lgrTargY = y
end
end
function doom.lgrTurnToTarg(object)
local player = object:player()
if player then
local x1,y1 = object:pos()
local x2 = player:data().lgrTargX
local y2 = player:data().lgrTargY
local a = object:get_angle()
--object:set_angle(vector_direction(x1, y1, x2, y2))
if ( angle_diff(a,vector_direction(x1, y1, x2, y2)) > 0 ) then
object:set_angle(a + 25)
else
object:set_angle(a - 25)
end
end
end
--------------------------------Plasmablade---------------------------
-------------------------------block--------------------------
print("Loading Plasmablade. . .")
function doom.plasmablade_block_trigger(worm)
worm:player():data().plasmablade_trigger_block = 1
worm:player():data().plasmablade_aid = 1
end
function doom.plasmablade_loop(worm)
-------------------------------block--------------------------
if worm:player():data().plasmablade_aid
then
if worm:player():data().plasmablade_trigger_block
then
worm:shoot(plasmablade_block, 1, 1, 0, 0, 0, 0, worm:player():data().plasmablade_trigger_block - 60, 8)
worm:player():data().plasmablade_trigger_block = worm:player():data().plasmablade_trigger_block + 12
if worm:player():data().plasmablade_trigger_block == 1
then
worm:shoot(plasmablade_swing_sound,1)
end
if worm:player():data().plasmablade_trigger_block == 360
then
worm:player():data().plasmablade_trigger_block = 1
end
end
-------------------------------single strike--------------------------
if worm:player():data().plasmablade_trigger
then
worm:shoot(plasmablade_swing, 1, 1, 0, 0, 0, 0, worm:player():data().plasmablade_trigger - 60, 4)
worm:player():data().plasmablade_trigger = worm:player():data().plasmablade_trigger + 9
worm:shoot(plasmablade_swing_sound,1)
if worm:player():data().plasmablade_trigger > 120
then
worm:player():data().plasmablade_trigger_aid = worm:player():data().plasmablade_trigger_aid + 1
end
if worm:player():data().plasmablade_trigger_aid == 2
then
worm:player():data().plasmablade_trigger = worm:player():data().plasmablade_trigger - 18
end
if worm:player():data().plasmablade_trigger < 0
then
worm:player():data().plasmablade_trigger = nil
worm:player():data().plasmablade_trigger_aid = nil
worm:player():data().plasmablade_aid = nil
end
end
else
worm:shoot(plasmablade, 1, 1, 0, 0, 0, 0, -60, 4)
end
end
function doom.plasmablade_strike_trigger(worm)
worm:player():data().plasmablade_trigger = 1
worm:player():data().plasmablade_trigger_aid = 1
worm:player():data().plasmablade_trigger_block = nil
end
function doom.plasmablade_reset(worm)
worm:player():data().plasmablade_trigger = nil
worm:player():data().plasmablade_trigger_aid = nil
worm:player():data().plasmablade_trigger_block = nil
worm:player():data().plasmablade_trigger_block = nil
worm:player():data().plasmablade_aid = nil
end
--------------------------------Plasmablade---------------------------
-----------------------------------Grenade----------------------------
print("Loading Grenade. . .")
function doom.grenade_reset(worm)
worm:player():data().grenade_hold = 1
worm:player():data().grenade_reload = 2
end
function doom.grenade_loop(worm)
if worm:player():data().grenade_hold then
worm:player():data().grenade_hold = worm:player():data().grenade_hold + 0.05
end
if worm:player():data().grenade_hold > 3.5 then
worm:player():data().grenade_hold = worm:player():data().grenade_hold - 0.05
end
end
function doom.grenade_release(worm)
if worm:player():data().grenade_reload then
worm:shoot (grenade,1, worm:player():data().grenade_hold , 1 ,0.1 , 0.5, 0, 10, 0, 6)
worm:player():data().grenade_hold = 1
end
end
function doom.grenade_out_of_ammo(worm)
worm:player():data().grenade_reload = nil
end
function doom.grenade_reload(worm)
worm:player():data().grenade_reload = 1
end
-----------------------------------Grenade----------------------------
---------------------------------AssaultRifle-------------------------
print("Loading Assault Rifle. . .")
function doom.ar_reset(worm)
worm:player():data().ar_fire = 0
worm:player():data().ar_timer = 0
end
function doom.ar_fire_start(worm)
worm:player():data().ar_fire = 1
worm:player():data().ar_timer = 1
end
function doom.ar_fire_loop(worm)
if worm:player():data().ar_fire < 9 then
worm:player():data().ar_fire = worm:player():data().ar_fire + 0.4
worm:shoot (assaultrifle, 1 , 0.9, 0, 0, 0, worm:player():data().ar_fire + 1, 0, 6)
end
if worm:player():data().ar_fire > 9 then
worm:player():data().ar_fire = worm:player():data().ar_fire - 0.4
end
end
---------------------------------AssaultRifle-------------------------
-------------------------------------BFG------------------------------
print("Loading BFG Blaster. . .")
function doom.bfg_reset(worm)
worm:player():data().bfg_fire = 0
worm:player():data().bfg_timer = 0
end
function doom.bfg_fire_start(worm)
worm:player():data().bfg_fire = 1
worm:player():data().bfg_timer = 1
end
function doom.bfg_fire_loop(worm)
if worm:player():data().bfg_fire < 255 and worm:player():data().bfg_timer == 1 then
worm:player():data().bfg_fire = worm:player():data().bfg_fire + 1
end
if worm:player():data().bfg_fire == 255 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 300
worm:shoot (bfg_sound_firestop,1,0,0,0,0,0,0,5)
end
--firetrail--
if worm:player():data().bfg_fire > 30 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire > 60 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire > 90 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire > 120 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire > 150 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire > 180 and worm:player():data().bfg_timer == 1 then
worm:shoot (bfg_firetrail,1,0,0,0,0,0,0,5)
end
--firetrail--
--sound--
if worm:player():data().bfg_fire == 17 then
worm:shoot (bfg_sound_1,1)
end
if worm:player():data().bfg_fire == 74 then
worm:shoot (bfg_sound_2,1)
end
if worm:player():data().bfg_fire == 132 then
worm:shoot (bfg_sound_3,1)
end
if worm:player():data().bfg_fire == 200 then
worm:shoot (bfg_sound_4,1)
end
end
--sound--
function doom.bfg_fire_end(worm)
if worm:player():data().bfg_fire == 300 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 0
end
if worm:player():data().bfg_fire > 200 and worm:player():data().bfg_timer == 1 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 0
worm:shoot (bfg_big,1 , 2.5, 0, 0, 0, 0, 0, 5 )
worm:shoot (bfg_flash,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire < 200 and worm:player():data().bfg_fire > 132 and worm:player():data().bfg_timer == 1 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 0
worm:shoot (bfg,1 , 2.5, 0, 0, 0, 0, 0, 5 )
worm:shoot (bfg_flash,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire < 132 and worm:player():data().bfg_fire > 74 and worm:player():data().bfg_timer == 1 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 0
worm:shoot (bfg_small,1 , 2.5, 0, 0, 0, 0, 0, 5 )
worm:shoot (bfg_flash_small,1,0,0,0,0,0,0,5)
end
if worm:player():data().bfg_fire < 74 and worm:player():data().bfg_fire > 2 and worm:player():data().bfg_timer == 1 then
worm:player():data().bfg_timer = 0
worm:player():data().bfg_fire = 0
worm:shoot (bfg_smallest,1 , 2.5, 0, 0, 0, 0, 0, 5 )
worm:shoot (bfg_flash_smallest,1,0,0,0,0,0,0,5)
end
end
-------------------------------------BFG------------------------------
----------------------------------chaingun----------------------------
print("Loading Chaingun. . .")
function doom.chaingun_smoke_reset(worm)
worm:player():data().out = 0
worm:player():data().chaingun = 0
end
function doom.chaingun_smoke_in(worm)
worm:player():data().out = 1
worm:player():data().chaingun = 1
end
function doom.chaingun_smoke_out(worm)
worm:player():data().out = 0
end
function doom.chaingun_smoke_loop(worm)
if worm:player():data().chaingun < 500 and worm:player():data().out == 1 then
worm:player():data().chaingun = worm:player():data().chaingun + 1
end
if worm:player():data().out == 0 and worm:player():data().chaingun > 0 then
worm:player():data().chaingun = worm:player():data().chaingun - 1.5
end
if worm:player():data().chaingun < 500 and worm:player():data().chaingun > 150 and worm:player():data().out == 0 then
worm:shoot (smoke,1,0,0.05,0,0,10,0,6)
end
end
----------------------------------chaingun----------------------------
--------------------------------Flamethrower--------------------------
print("Loading Flamethrower. . .")
function doom.flame_loop(worm)
if worm:player():data().flame == 1 then
worm:shoot (flames,1,0.5,0,0,0,30,0,5)
end
end
function doom.flame_reset(worm)
worm:player():data().flame = 1
flamethrowertimer = 0
end
function doom.flame_set(worm)
worm:player():data().flame = 0
end
function doom.burner(worm)
if flamethrowertimer == 10 then
worm:shoot(flame_burner,1,1,0,0,0,11,0,5)
flamethrowertimer = 0
else
flamethrowertimer = flamethrowertimer + 1
end
end
function doom.burnpos(object,worm)
wx,wy = worm:pos()
object:set_pos(wx,wy)
end
--------------------------------Flamethrower--------------------------
---------------------------------RemoteBomb--------------------------
print("Loading RemoteBomb. . .")
function doom.remotebomb_reset(worm)
worm:player():data().remotebomb = 0
worm:player():data().remotebomb_mode = 1
end
function doom.remotebomb_set(worm)
worm:player():data().remotebomb = 1
end
function doom.remotebomb_loop(worm)
if worm:player():data().remotebomb < 20 then
worm:player():data().remotebomb = worm:player():data().remotebomb + 1
end
end
function doom.remotebomb_loping(worm)
if worm:player():data().remotebomb_mode == 2 then
worm:shoot (remotebomb_button,1,0,0,0,0,0,0,0)
end
end
function doom.remotebomb_select(worm)
if worm:player():data().remotebomb > 10 and worm:player():data().remotebomb_mode == 1 then
worm:shoot (remotebomb,1,worm:player():data().remotebomb/20, 0, 0, 0, 0, 0, 6)
end
if worm:player():data().remotebomb > 10 and worm:player():data().remotebomb_mode == 2 then
remotebomb_boom = 1
worm:shoot (remotebomb_click,1)
end
if worm:player():data().remotebomb < 10 then
worm:shoot (remotebomb_select,1)
worm:player():data().remotebomb_mode = worm:player():data().remotebomb_mode + 1
worm:player():data().remotebomb = 0
end
if worm:player():data().remotebomb_mode == 3 then
worm:player():data().remotebomb_mode = 1
remotebomb_boom = nil
end
end
function doom.remotebomb_active (object)
if remotebomb_boom then
object:shoot (remotebomb_explode,1)
remotebomb_boom = nil
end
end
---------------------------------RemoteBomb--------------------------
---------------------------------IonCannon---------------------------
print("Loading Ion Cannon. . .")
function doom.ion_reset(worm)
worm:player():data().ion_fire = 0
worm:player():data().ion_timer = 0
end
function doom.ion_fire_start(worm)
worm:player():data().ion_fire = 1
worm:player():data().ion_timer = 1
end
function doom.ion_fire_loop(worm)
local player = worm:player()
if worm:player():data().ion_fire and worm:player():data().ion_timer == 1 then
worm:player():data().ion_fire = worm:player():data().ion_fire + 1
end
if worm:player():data().ion_fire == 50 then
ion_charge_sound:play(worm, nil, 100, 1, 0)
end
if worm:player():data().ion_fire == 120 then
worm:player():data().ion_timer = 0
worm:player():data().ion_fire = 0
worm:shoot (ioncannon2,1,1,0,0,0,0,0,5)
worm:shoot (ioncannonflash,1,0,0,0,0,0,0,5)
worm:shoot (ioncannonflash,1,0,0,0,0,0,0,5)
worm:shoot (ioncannonflash,1,0,0,0,0,0,0,5)
end
end
function doom.ion_fire_end(worm)
if worm:player():data().ion_fire < 150 and worm:player():data().ion_fire > 5 and worm:player():data().ion_timer == 1 then
worm:player():data().ion_timer = 0
worm:player():data().ion_fire = 0
worm:shoot (ioncannon1,1,1,0,0,0,0,0,5)
worm:shoot (ioncannonflash,1,0,0,0,0,0,0,5)
end
end
---------------------------------IonCannon--------------------------- |
-- Creator:
-- AltiV - December 27th, 2019
LinkLuaModifier("modifier_item_imba_cultic_hammer", "components/items/item_cultic_hammer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_imba_cultic_hammer_aura", "components/items/item_cultic_hammer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_imba_cultic_pull", "components/items/item_cultic_hammer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_imba_cultic_status_resistance", "components/items/item_cultic_hammer", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_item_imba_cultic_root", "components/items/item_cultic_hammer", LUA_MODIFIER_MOTION_NONE)
item_imba_cultic_hammer = item_imba_cultic_hammer or class({})
modifier_item_imba_cultic_hammer = modifier_item_imba_cultic_hammer or class({})
modifier_item_imba_cultic_hammer_aura = modifier_item_imba_cultic_hammer_aura or class({})
modifier_item_imba_cultic_pull = modifier_item_imba_cultic_pull or class({})
modifier_item_imba_cultic_status_resistance = modifier_item_imba_cultic_status_resistance or class({})
modifier_item_imba_cultic_root = modifier_item_imba_cultic_root or class({})
-----------------------------
-- ITEM_IMBA_CULTIC_HAMMER --
-----------------------------
function item_imba_cultic_hammer:GetChannelAnimation()
return ACT_DOTA_GENERIC_CHANNEL_1
end
function item_imba_cultic_hammer:GetIntrinsicModifierName()
return "modifier_item_imba_cultic_hammer"
end
function item_imba_cultic_hammer:GetAOERadius()
return self:GetSpecialValueFor("wretched_radius")
end
function item_imba_cultic_hammer:OnSpellStart()
self:GetParent():EmitSound("Imba.Curseblade")
self.aoe_particle_1 = ParticleManager:CreateParticle("particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate_ring.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.aoe_particle_1, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.aoe_particle_1, 1, Vector(self:GetSpecialValueFor("wretched_radius"), 0, 0))
self.aoe_particle_2 = ParticleManager:CreateParticle("particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate_dmg_dark_core.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.aoe_particle_2, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.aoe_particle_2, 1, Vector(self:GetSpecialValueFor("wretched_radius") * 0.5, 0, 0))
self.aoe_particle_3 = ParticleManager:CreateParticle("particles/item/cultic_hammer/cultic_hammer_channel_hammers.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.aoe_particle_3, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.aoe_particle_3, 1, Vector(self:GetSpecialValueFor("wretched_radius"), 0, 0))
self:GetCaster():StartGesture(ACT_DOTA_GENERIC_CHANNEL_1)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCursorPosition(), nil, self:GetSpecialValueFor("wretched_radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
enemy:AddNewModifier(self:GetCaster(), self, "modifier_item_imba_cultic_pull", {
duration = self:GetChannelTime(),
pos_x = self:GetCursorPosition().x,
pos_y = self:GetCursorPosition().y,
pos_z = self:GetCursorPosition().z
})
end
end
function item_imba_cultic_hammer:OnChannelFinish(bInterrupted)
self:GetParent():StopSound("Imba.Curseblade")
ParticleManager:DestroyParticle(self.aoe_particle_1, true)
ParticleManager:ReleaseParticleIndex(self.aoe_particle_1)
ParticleManager:DestroyParticle(self.aoe_particle_2, true)
ParticleManager:ReleaseParticleIndex(self.aoe_particle_2)
ParticleManager:DestroyParticle(self.aoe_particle_3, true)
ParticleManager:ReleaseParticleIndex(self.aoe_particle_3)
self:GetCaster():FadeGesture(ACT_DOTA_GENERIC_CHANNEL_1)
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCursorPosition(), nil, FIND_UNITS_EVERYWHERE, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES + DOTA_UNIT_TARGET_FLAG_INVULNERABLE + DOTA_UNIT_TARGET_FLAG_OUT_OF_WORLD, FIND_ANY_ORDER, false)) do
if enemy:FindModifierByNameAndCaster("modifier_item_imba_cultic_pull", self:GetCaster()) then
enemy:RemoveModifierByNameAndCaster("modifier_item_imba_cultic_pull", self:GetCaster())
end
end
if not bInterrupted then
EmitSoundOnLocationWithCaster(self:GetCursorPosition(), "DOTA_Imba_Item.Cultic_Hammer.Slam", self:GetCaster())
self.aoe_particle_impact = ParticleManager:CreateParticle("particles/units/heroes/hero_void_spirit/planeshift/void_spirit_planeshift_impact.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.aoe_particle_impact, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.aoe_particle_impact, 1, Vector(self:GetSpecialValueFor("wretched_radius"), 0, 0))
ParticleManager:ReleaseParticleIndex(self.aoe_particle_impact)
self.aoe_particle_impact_2 = ParticleManager:CreateParticle("particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate_dmg.vpcf", PATTACH_POINT, self:GetCaster())
ParticleManager:SetParticleControl(self.aoe_particle_impact_2, 0, self:GetCursorPosition())
ParticleManager:SetParticleControl(self.aoe_particle_impact_2, 1, Vector(self:GetSpecialValueFor("wretched_radius") * 0.5, 0, 0))
ParticleManager:ReleaseParticleIndex(self.aoe_particle_impact_2)
local health_loss = nil
for _, enemy in pairs(FindUnitsInRadius(self:GetCaster():GetTeamNumber(), self:GetCursorPosition(), nil, self:GetSpecialValueFor("wretched_radius"), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NONE, FIND_ANY_ORDER, false)) do
health_loss = enemy:GetHealth() * self:GetSpecialValueFor("wretched_hp_damage_pct") * 0.01
enemy:SetHealth(math.max(enemy:GetHealth() - health_loss, 1))
SendOverheadEventMessage(nil, OVERHEAD_ALERT_BONUS_POISON_DAMAGE, enemy, health_loss, nil)
ApplyDamage({
victim = enemy,
damage = self:GetSpecialValueFor("wretched_base_damage"),
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_HPLOSS + DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
attacker = self:GetCaster(),
ability = self
})
enemy:AddNewModifier(self:GetCaster(), self, "modifier_item_imba_cultic_status_resistance", {duration = self:GetSpecialValueFor("wretched_status_duration")})
local root_modifier = enemy:AddNewModifier(self:GetCaster(), self, "modifier_item_imba_cultic_root", {duration = self:GetSpecialValueFor("wretched_root_duration")})
if root_modifier then
root_modifier:SetDuration(self:GetSpecialValueFor("wretched_root_duration") * (1 - enemy:GetStatusResistance()), true)
end
end
GridNav:DestroyTreesAroundPoint(self:GetCursorPosition(), self:GetSpecialValueFor("wretched_radius"), true)
end
end
--------------------------------------
-- MODIFIER_ITEM_IMBA_CULTIC_HAMMER --
--------------------------------------
function modifier_item_imba_cultic_hammer:IsHidden() return true end
function modifier_item_imba_cultic_hammer:IsPurgable() return false end
function modifier_item_imba_cultic_hammer:RemoveOnDeath() return false end
function modifier_item_imba_cultic_hammer:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end
function modifier_item_imba_cultic_hammer:OnCreated()
if not self:GetAbility() then return end
self.bonus_str = self:GetAbility():GetSpecialValueFor("bonus_str")
self.bonus_damage = self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_imba_cultic_hammer:DeclareFunctions()
return {
MODIFIER_PROPERTY_STATS_STRENGTH_BONUS,
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE
}
end
function modifier_item_imba_cultic_hammer:GetModifierBonusStats_Strength()
return self.bonus_str
end
function modifier_item_imba_cultic_hammer:GetModifierPreAttack_BonusDamage()
return self.bonus_damage
end
function modifier_item_imba_cultic_hammer:IsAura() return true end
function modifier_item_imba_cultic_hammer:IsAuraActiveOnDeath() return false end
function modifier_item_imba_cultic_hammer:GetAuraRadius() return self:GetAbility():GetSpecialValueFor("soul_drain_radius") end
function modifier_item_imba_cultic_hammer:GetAuraSearchFlags() return DOTA_UNIT_TARGET_FLAG_NONE end
function modifier_item_imba_cultic_hammer:GetAuraSearchTeam() return DOTA_UNIT_TARGET_TEAM_ENEMY end
function modifier_item_imba_cultic_hammer:GetAuraSearchType() return DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC end
function modifier_item_imba_cultic_hammer:GetModifierAura() return "modifier_item_imba_cultic_hammer_aura" end
-------------------------------------------
-- MODIFIER_ITEM_IMBA_CULTIC_HAMMER_AURA --
-------------------------------------------
function modifier_item_imba_cultic_hammer_aura:GetEffectName()
return "particles/item/curseblade/imba_curseblade_curse_rope_pnt.vpcf"
end
function modifier_item_imba_cultic_hammer_aura:OnCreated()
if not self:GetAbility() then return end
self.soul_drain_health = self:GetAbility():GetSpecialValueFor("soul_drain_health")
self.soul_drain_mana = self:GetAbility():GetSpecialValueFor("soul_drain_mana")
self.soul_drain_health_illusions = self.soul_drain_health * self:GetAbility():GetSpecialValueFor("soul_drain_illusion_efficiency") * 0.01
self.soul_drain_mana_illusions = self.soul_drain_mana * self:GetAbility():GetSpecialValueFor("soul_drain_illusion_efficiency") * 0.01
if not IsServer() then return end
self:StartIntervalThink(1)
end
function modifier_item_imba_cultic_hammer_aura:OnIntervalThink()
if not self:GetCaster():IsIllusion() then
self.soul_drain_health_actual = self.soul_drain_health
self.soul_drain_mana_actual = self.soul_drain_mana
else
self.soul_drain_health_actual = self.soul_drain_health_illusions
self.soul_drain_mana_actual = self.soul_drain_mana_illusions
end
ApplyDamage({
victim = self:GetParent(),
damage = self.soul_drain_health_actual,
damage_type = DAMAGE_TYPE_PURE,
damage_flags = DOTA_DAMAGE_FLAG_HPLOSS + DOTA_DAMAGE_FLAG_NO_SPELL_AMPLIFICATION,
attacker = self:GetCaster(),
ability = self:GetAbility()
})
self.heal_particle = ParticleManager:CreateParticle("particles/items3_fx/octarine_core_lifesteal.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster())
ParticleManager:ReleaseParticleIndex(self.heal_particle)
self:GetCaster():Heal(self.soul_drain_health_actual, self:GetAbility())
if self:GetParent().GetMaxMana and self:GetParent():GetMaxMana() > 0 then
self:GetParent():ReduceMana(self.soul_drain_mana_actual)
self:GetCaster():GiveMana(self.soul_drain_mana_actual)
end
end
------------------------------------
-- MODIFIER_ITEM_IMBA_CULTIC_PULL --
------------------------------------
function modifier_item_imba_cultic_pull:IsPurgable() return false end
function modifier_item_imba_cultic_pull:IgnoreTenacity() return true end
function modifier_item_imba_cultic_pull:GetEffectName()
return "particles/item/curseblade/imba_curseblade_curse.vpcf"
end
function modifier_item_imba_cultic_pull:OnCreated(keys)
self.wretched_pull_speed = self:GetAbility():GetSpecialValueFor("wretched_pull_speed")
if not IsServer() then return end
self.pos = Vector(keys.pos_x, keys.pos_y, keys.pos_z)
self:StartIntervalThink(FrameTime())
end
function modifier_item_imba_cultic_pull:OnRefresh(keys)
self.pos = Vector(keys.pos_x, keys.pos_y, keys.pos_z)
end
function modifier_item_imba_cultic_pull:OnIntervalThink()
self:GetParent():SetAbsOrigin(self:GetParent():GetAbsOrigin() + (self.pos - self:GetParent():GetAbsOrigin()):Normalized() * FrameTime() * self.wretched_pull_speed)
end
function modifier_item_imba_cultic_pull:OnDestroy()
if not IsServer() then return end
FindClearSpaceForUnit(self:GetParent(), self:GetParent():GetAbsOrigin(), true)
self:GetParent():StopSound("Imba.Curseblade")
end
-------------------------------------------------
-- MODIFIER_ITEM_IMBA_CULTIC_STATUS_RESISTANCE --
-------------------------------------------------
function modifier_item_imba_cultic_status_resistance:IsPurgable() return false end
function modifier_item_imba_cultic_status_resistance:IgnoreTenacity() return true end
function modifier_item_imba_cultic_status_resistance:GetEffectName()
return "particles/item/curseblade/imba_hellblade_curse.vpcf"
end
function modifier_item_imba_cultic_status_resistance:GetStatusEffectName()
return "particles/status_fx/status_effect_abaddon_frostmourne.vpcf"
end
function modifier_item_imba_cultic_status_resistance:OnCreated()
self.wretched_status_resistance = self:GetAbility():GetSpecialValueFor("wretched_status_resistance") * (-1)
end
function modifier_item_imba_cultic_status_resistance:DeclareFunctions()
return {MODIFIER_PROPERTY_STATUS_RESISTANCE_STACKING}
end
function modifier_item_imba_cultic_status_resistance:GetModifierStatusResistanceStacking()
return self.wretched_status_resistance
end
------------------------------------
-- MODIFIER_ITEM_IMBA_CULTIC_ROOT --
------------------------------------
function modifier_item_imba_cultic_root:GetEffectName()
return "particles/items2_fx/rod_of_atos.vpcf"
end
function modifier_item_imba_cultic_root:CheckState()
return {[MODIFIER_STATE_ROOTED] = true}
end
|
g_yoda_house_loot_deed = {
description = "Yoda's Hut House Blueprint",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "yoda_house_loot_deed", weight = 10000000}
}
}
addLootGroupTemplate("g_yoda_house_loot_deed", g_yoda_house_loot_deed)
|
--[[
Plugin for Cheat Engine what provide for you small interface to OpenGL
tested with
Cheat Engine 6.6
by srg91
]]--
require([[autorun\OGLHook\Const]])
require([[autorun\OGLHook\Utils]])
require([[autorun\OGLHook\Commands]])
require([[autorun\OGLHook\Textures]])
require([[autorun\OGLHook\Sprites]])
require([[autorun\OGLHook\Fonts]])
-- Private --
local OPENGL32_NAME = 'OPENGL32'
local OGLH_ADDR_NAME = OPENGL32_NAME .. '.wglSwapBuffers'
OGL_HOOK = nil
local function OGLHook_InitMemory(hook_size)
if not hook_size then
hook_size = 16 * 1024
end
OGLHook_Utils.AllocateRegister('oglh_hook_code', hook_size)
OGLHook_Utils.AllocateRegister('oglh_window_hdc', 4)
OGLHook_Utils.AllocateRegister('oglh_parent_context', 4)
OGLHook_Utils.AllocateRegister('oglh_context', 4)
OGLHook_Utils.AllocateRegister('oglh_thread_context', 4)
OGLHook_Utils.AllocateRegister('oglh_initialized', 1, 'db 0')
OGLHook_Utils.AllocateRegister('oglh_image_ptr', 4)
OGLHook_Utils.AllocateRegister('oglh_image_handle', 4)
OGLHook_Utils.AllocateRegister('oglh_window_rect', 20)
return true
end
local function OGLHook_ClearHook(ogl_hook)
local command = [[
OPENGL32.wglSwapBuffers:
]] .. ogl_hook._orig_opcodes
return autoAssemble(command)
end
local function OGLHook_RewriteHook()
local command = [[
label(oglh_return)
OPENGL32.wglSwapBuffers:
jmp oglh_hook_code
oglh_return:
oglh_hook_code:
push [esp+4]
pop [oglh_window_hdc]
]] .. OGLHook_Commands.commands_stack_text .. '\r\n' .. [[
jmp oglh_return
]]
return autoAssemble(command)
end
local function OGLHook_RewriteBody()
local command = [[
label(oglh_return)
OPENGL32.wglSwapBuffers+5:
oglh_return:
oglh_hook_code:
push [esp+4]
pop [oglh_window_hdc]
]] .. OGLHook_Commands.commands_stack_text .. '\r\n' .. [[
jmp oglh_return
]]
return autoAssemble(command)
end
function OGLHook_UpdateWindowSize()
OGLHook_Commands.RunExternalCmd([[
push [oglh_window_hdc]
call WindowFromDC
push oglh_window_rect
push eax
call GetClientRect
fild [oglh_window_rect]
fstp dword ptr [oglh_window_rect]
fild [oglh_window_rect+4]
fstp dword ptr [oglh_window_rect+4]
fild [oglh_window_rect+8]
fstp dword ptr [oglh_window_rect+8]
fild [oglh_window_rect+c]
fstp dword ptr [oglh_window_rect+c]
fld [oglh_window_rect+8]
fld [oglh_window_rect+c]
fdivp
fstp [oglh_window_rect+10]
]])
end
local function OGLHook_BeforeUpdate()
OGLHook_Commands.RunExternalCmd([[
label(initialized)
label(initialization)
]])
OPENGL32.wglGetCurrentContext('->', 'oglh_parent_context')
if OGL_HOOK._initialization_part ~= nil then
OGLHook_Commands.RunExternalCmd(OGL_HOOK._initialization_part)
end
OPENGL32.wglMakeCurrent('[oglh_window_hdc]', '[oglh_context]')
OPENGL32.glBlendFunc(OPENGL32.GL_SRC_ALPHA, OPENGL32.GL_ONE_MINUS_SRC_ALPHA)
end
local function OGLHook_AfterUpdate()
OPENGL32.wglMakeCurrent('[oglh_window_hdc]', '[oglh_parent_context]')
OGLHook_Commands.RunExternalCmd(OGL_HOOK._orig_opcodes)
end
local function _getSelf(...)
local self, _ = ...
if self == nil then
self = OGL_HOOK
end
return self, _
end
local function OGLHook_Update(...)
local self = _getSelf(...)
if self == nil then
return
end
if self._orig_opcodes == nil then
return
end
OGLHook_BeforeUpdate()
for _,sprite in ipairs(OGLHook_Sprites.list) do
if sprite and sprite.visible then
sprite:before_render()
sprite:render()
sprite:after_render()
end
end
for i,k in ipairs(self.update_funcs) do
k()
end
OGLHook_AfterUpdate()
OGLHook_Commands.Flush()
return OGLHook_RewriteBody()
end
local function OGLHook_GetOpcodesText(address, size)
local start_address
if type(address) == 'number' then
start_address = address
elseif type(address) == 'string' and OGLHook_Utils.getAddressSilent(address) ~= 0 then
start_address = OGLHook_Utils.getAddressSilent(address)
else
return
end
local opcodes_len = 0
local result = ''
repeat
local current_opcode_size = getInstructionSize(start_address + opcodes_len)
if current_opcode_size == nil or current_opcode_size == 0 then
break
end
local _, opcode_text, _ = splitDisassembledString(disassemble(start_address + opcodes_len))
if #result > 0 then
result = result .. '\r\n'
end
result = result .. opcode_text
opcodes_len = opcodes_len + current_opcode_size
until opcodes_len >= size
return result
end
local function OLGHook_CreteFakeWindow()
OGLHook_Utils.AllocateRegister(
'oglh_wnd_class_name', 256, [[db 'OGLHookFakeWindowClass',0]]
)
OGLHook_Utils.AllocateRegister('oglh_fake_wnd_class', 48, [[
// cbSize
dd #48
// style
dd 0
// lpfnWndProc
dd DefWindowProcA
// cbClsExtra
dd 0
// cbWndExtra
dd 0
// hinstance
dd 0
// hIcon
dd 0
// hCursor
dd 0
// hbrBackground
dd 0
// lpszMenuName
dd 0
// lpszClassName
dd oglh_wnd_class_name
// hIconSm
dd 0
]])
OGLHook_Utils.AllocateRegister('oglh_fake_wnd_pf', 40, [[
// nSize
dw #40
// nVersion
dw 1
// dwFlags
// PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER
dd #37
// PFD_TYPE_RGBA, 32 bit framebuffer
db 0 #32
// ...
dd 0 0 0
db 0
// 24 bit depthbuffer, 8 bit stencilbuffer, 0 aux buffers
db #24 #8 0
// PFD_MAIN_PLANE
db 0
// ...
dd 0
]])
OGLHook_Utils.AllocateRegister('oglh_current_hinstance', 4)
OGLHook_Utils.AllocateRegister('oglh_thread_hwnd', 4)
OGLHook_Utils.AllocateRegister('oglh_thread_hdc', 4)
OGLHook_Commands.RunExternalCmd('call GetModuleHandleA', 0, 'oglh_current_hinstance')
OGLHook_Commands.RunExternalCmd([[
push [oglh_current_hinstance]
pop [oglh_fake_wnd_class+24]
]])
OGLHook_Commands.RunExternalCmd('call RegisterClassExA', 'oglh_fake_wnd_class')
OGLHook_Commands.RunExternalCmd(
'call CreateWindowExA',
{0, 'oglh_wnd_class_name', 0, 0, 100, 100, 1, 1, 0, 0, '[oglh_current_hinstance]', 0},
'oglh_thread_hwnd'
)
OGLHook_Commands.RunExternalCmd('call GetDC', '[oglh_thread_hwnd]', 'oglh_thread_hdc')
OGLHook_Commands.RunExternalCmd('call ChoosePixelFormat', {'[oglh_thread_hdc]', 'oglh_fake_wnd_pf'})
OGLHook_Commands.RunExternalCmd('call SetPixelFormat', {'[oglh_thread_hdc]', 'eax', 'oglh_fake_wnd_pf'})
end
local function OGLHook_Destroy_Fake_Window()
if OGLHook_Utils.getAddressSilent('oglh_wnd_class_name') == 0 then
return
end
local command = [[
push [oglh_thread_hwnd]
call DestroyWindow
push [oglh_current_hinstance]
push oglh_fake_wnd_class
call UnregisterClassA
]]
OGLHook_Commands.SyncRun(command)
end
local function OGLHook_Init(...)
local self = _getSelf(...)
if self == nil then
return false
end
self._orig_opcodes = OGLHook_GetOpcodesText(OGLH_ADDR_NAME, 5)
OGLHook_Commands.RunExternalCmd(self._orig_opcodes)
OGLHook_Commands.Flush()
if not OGLHook_RewriteHook() then
return false
end
OGLHook_Commands.RunExternalCmd([[
cmp [oglh_initialized], 0
jnz initialized
]])
OLGHook_CreteFakeWindow()
OPENGL32.wglCreateContext('[oglh_window_hdc]', '->', 'oglh_context')
OPENGL32.wglCreateContext('[oglh_thread_hdc]', '->', 'oglh_thread_context')
OPENGL32.wglShareLists('[oglh_parent_context]', '[oglh_thread_context]')
OPENGL32.wglShareLists('[oglh_thread_context]', '[oglh_context]')
OPENGL32.wglMakeCurrent('[oglh_window_hdc]', '[oglh_context]')
OGLHook_Commands.PutLabel('initialization')
OGLHook_Commands.RunExternalCmd('mov [oglh_initialized],#1')
OGLHook_UpdateWindowSize()
if type(OGL_HOOK.onInit) == 'function' then
OGL_HOOK:onInit()
else
OGLHook_SimpleOrtho()
end
OGLHook_Commands.PutLabel('initialized')
self._initialization_part = OGLHook_Commands.Flush()
if not OGLHook_Update() then
return false
end
return true
end
local function OGLHook_Destroy(...)
local self = _getSelf(...)
if self == nil then
return
end
OGLHook_ClearHook(self)
OGLHook_Destroy_Fake_Window()
local units = {
'Sprites', 'Textures', 'Fonts', 'Commands', 'Utils', 'Errors', 'Const'
}
for _,unit_name in ipairs(units) do
local olgh_unit_name = 'OGLHook_' .. unit_name
local unit_table = _G[olgh_unit_name]
if unit_table.destroy then
unit_table:destroy()
end
_G[olgh_unit_name] = nil
end
for i=#units,1,-1 do
local oglh_unit_path = [[autorun\OGLHook\]] .. units[i]
package.loaded[oglh_unit_path] = nil
require(oglh_unit_path)
end
end
function OGLHook_isActive(self)
local init_addr = OGLHook_Utils.getAddressSilent('oglh_initialized')
if init_addr == 0 then
return false
end
return readBytes(init_addr, 1, false) == 1
end
-- Public --
function OGLHook_SimpleOrtho(x, y, width, height, znear, zfar)
local x = x or '[oglh_window_rect]'
local y = y or '[oglh_window_rect+4]'
local width = width or '[oglh_window_rect+8]'
local height = height or '[oglh_window_rect+c]'
local znear = znear or 1.0
local zfar = zfar or -1.0
OPENGL32.glMatrixMode(OPENGL32.GL_PROJECTION)
OPENGL32.glLoadIdentity()
OPENGL32.glOrtho(x, width, height, y, znear, zfar)
OPENGL32.glMatrixMode(OPENGL32.GL_MODELVIEW)
OPENGL32.glLoadIdentity()
OPENGL32.glClearColor(0, 0, 0, 1)
end
function OGLHook_SimplePerspective(fov, aspect_ratio, znear, zfar)
local fov = fov or 45
local aspect_ratio = aspect_ratio or '[oglh_window_rect+10]'
local znear = znear or 0.1
local zfar = zfar or 100
OPENGL32.glMatrixMode(OPENGL32.GL_PROJECTION)
OPENGL32.glLoadIdentity()
GLU32.gluPerspective(fov, aspect_ratio, znear, zfar)
OPENGL32.glMatrixMode(OPENGL32.GL_MODELVIEW)
OPENGL32.glLoadIdentity()
OPENGL32.glClearColor(0, 0, 0, 1)
OPENGL32.glShadeModel(OPENGL32.GL_SMOOTH)
OPENGL32.glClearDepth('(float)1')
OPENGL32.glEnable(OPENGL32.GL_DEPTH_TEST)
OPENGL32.glDepthFunc(OPENGL32.GL_LEQUAL)
OPENGL32.glHint(OPENGL32.GL_PERSPECTIVE_CORRECTION_HINT, OPENGL32.GL_NICEST)
end
function OGLHook_Create(onInit, hook_size)
reinitializeSymbolhandler()
local hook_address = OGLHook_Utils.getAddressSilent(OGLH_ADDR_NAME)
if hook_address == 0 then
return -1
end
if OGL_HOOK ~= nil then
OGL_HOOK:destroy()
end
if not OGLHook_InitMemory(hook_size) then
return -2
end
OGL_HOOK = {
_orig_opcodes=nil,
_initialization_part=nil,
update_funcs={},
init = OGLHook_Init,
onInit = onInit,
update = OGLHook_Update,
registerUpdateFunc = function(self, update_func)
table.insert(self.update_funcs, update_func)
end,
destroy = OGLHook_Destroy,
loadTexture = OGLHook_Textures.LoadTexture,
createSprite = OGLHook_Sprites.Sprite,
generateFontMap = OGLHook_Fonts.generateFontMap,
createTextContainer = OGLHook_Sprites.TextContainer,
isActive = OGLHook_isActive,
}
if not OGL_HOOK:init() then
return -3
end
return OGL_HOOK
end
|
local bit = require "bit"
local instruction = require "instruction"
local utils = require "utils"
local machine
function love.load()
-- initialize machine
machine = {
-- memory
memory = utils.newArray(0x1000, 0x00),
-- register
reg_v = utils.newArray(0x10, 0x00),
pc = 0x0200,
sp = 0x00,
i = 0x0000,
-- timer
dt = 0x00,
st = 0x00,
}
-- load internal sprites
utils.loadInternalSprites(machine.memory)
-- load rom
utils.loadRom(machine.memory, "rom.ch8")
end
local updateFlag = false
local interval = 0
function love.update(dt)
-- set update flag
interval = interval+dt
if interval*120 >= 1 then
updateFlag = true
interval = 0
end
if updateFlag then
-- update timers
if machine.dt>0 then
machine.dt = machine.dt-1
end
if machine.st>0 then
machine.st = machine.st-1
end
-- run one cycle
instruction.runOneCycle(machine)
-- reset update flag
updateFlag = false
end
end
function love.draw()
-- draw frame
for i = 0x0000, 0x00FF do
for j = 7, 0, -1 do
if utils.getBit(machine.memory[0x0F00+i], j) ~= 0 then
local index = i*8+(7-j)
love.graphics.rectangle("fill", index%64*10, math.floor(index/64)*10, 10, 10)
end
end
end
end |
modpath = minetest.get_modpath("gridgen")
A = 8 -- Controlls size of the dungeon rooms
function save_spawns(spawns)
local file = io.open(minetest.get_worldpath().."/spawns.txt", "w")
if file then
file:write(minetest.serialize(spawns))
file:close()
end
end
minetest.register_on_mapgen_init(function(params) -- Automatically turn on singlenode generator
minetest.set_mapgen_params({
mgname = "singlenode"
})
end)
dofile(modpath .. "/gridgen.lua")
dofile(modpath .. "/spawn.lua")
dofile(modpath .. "/undergroundgen.lua")
dofile(modpath .. "/utils.lua")
dofile(modpath .. "/nodes.lua")
|
require("lualib_bundle");
__TS__SourceMapTraceBack(debug.getinfo(1).short_src, {["4"] = 1,["5"] = 1,["6"] = 5,["7"] = 5,["8"] = 5,["9"] = 5,["11"] = 14,["12"] = 15,["13"] = 17,["14"] = 19,["15"] = 13,["16"] = 23,["17"] = 24,["18"] = 23,["19"] = 27,["20"] = 28,["21"] = 29,["23"] = 31,["24"] = 33,["25"] = 34,["26"] = 36,["27"] = 27,["28"] = 39,["29"] = 40,["30"] = 39,["31"] = 43,["32"] = 44,["33"] = 46,["34"] = 47,["36"] = 49,["37"] = 51,["38"] = 52,["40"] = 54,["41"] = 56,["42"] = 57,["43"] = 59,["45"] = 62,["46"] = 64,["47"] = 43,["48"] = 67,["49"] = 68,["50"] = 67,["51"] = 71,["52"] = 72,["53"] = 73,["54"] = 74,["56"] = 71,["57"] = 5,["58"] = 5});
local ____exports = {}
local ____Utils = require("Lilac.Utility.Utils")
local luaTableIpairs = ____Utils.luaTableIpairs
____exports.default = (function()
____exports.default = __TS__Class()
local SparseSet = ____exports.default
SparseSet.name = "SparseSet"
function SparseSet.prototype.____constructor(self)
self.sparse = {}
self.dense = {}
self.elements = self.dense
self.count = 0
end
function SparseSet.prototype.values(self)
return luaTableIpairs(self.dense)
end
function SparseSet.prototype.add(self, element)
if self.sparse[element] then
return false
end
local index = #self.dense + 1
self.sparse[element] = index
self.dense[index] = element
return true
end
function SparseSet.prototype.get(self, index)
return self.dense[index]
end
function SparseSet.prototype.remove(self, element)
local index = self.sparse[element]
if index == nil then
return false
end
local size = #self.dense
if index == size then
self.dense[index] = nil
else
local other = self.dense[size]
self.dense[index] = other
self.sparse[other] = index
self.dense[size] = nil
end
self.sparse[element] = nil
return true
end
function SparseSet.prototype.has(self, element)
return self.sparse[element] ~= nil
end
function SparseSet.prototype.clear(self)
for index, element in self:values() do
self.dense[index] = nil
self.sparse[element] = nil
end
end
return SparseSet
end)()
return ____exports
|
local Hi = require("resty.moongoo.utils").pbkdf2_hmac_sha1
local saslprep = require("resty.moongoo.utils").saslprep
local pass_digest = require("resty.moongoo.utils").pass_digest
local xor_bytestr = require("resty.moongoo.utils").xor_bytestr
local b64 = ngx and ngx.encode_base64 or require("mime").b64
local unb64 = ngx and ngx.decode_base64 or require("mime").unb64
local hmac_sha1 = ngx and ngx.hmac_sha1 or function(str, key) return require("crypto").hmac.digest("sha1", key, str, true) end
local sha1_bin = ngx and ngx.sha1_bin or function(str) return require("crypto").digest("sha1", str, true) end
local cbson = require("cbson")
local function auth(db, username, password)
local username = saslprep(username)
local c_nonce = b64(string.sub(tostring(math.random()), 3 , 14))
local first_bare = "n=" .. username .. ",r=" .. c_nonce
local sasl_start_payload = b64("n,," .. first_bare)
r, err = db:_cmd("saslStart", {
mechanism = "SCRAM-SHA-1" ;
autoAuthorize = 1 ;
payload = cbson.binary(sasl_start_payload);
})
if not r then
return nil, err
end
local conversationId = r['conversationId']
local server_first = r['payload']:raw()
local parsed_t = {}
for k, v in string.gmatch(server_first, "(%w+)=([^,]*)") do
parsed_t[k] = v
end
local iterations = tonumber(parsed_t['i'])
local salt = parsed_t['s']
local s_nonce = parsed_t['r']
if not string.sub(s_nonce, 1, 12) == c_nonce then
return nil, 'Server returned an invalid nonce.'
end
local without_proof = "c=biws,r=" .. s_nonce
local pbkdf2_key = pass_digest ( username , password )
local salted_pass = Hi(pbkdf2_key, iterations, unb64(salt), 20)
local client_key = hmac_sha1(salted_pass, "Client Key")
local stored_key = sha1_bin(client_key)
local auth_msg = first_bare .. ',' .. server_first .. ',' .. without_proof
local client_sig = hmac_sha1(stored_key, auth_msg)
local client_key_xor_sig = xor_bytestr(client_key, client_sig)
local client_proof = "p=" .. b64(client_key_xor_sig)
local client_final = b64(without_proof .. ',' .. client_proof)
local server_key = hmac_sha1(salted_pass, "Server Key")
local server_sig = b64(hmac_sha1(server_key, auth_msg))
r, err = db:_cmd("saslContinue",{
conversationId = conversationId ;
payload = cbson.binary(client_final);
})
if not r then
return nil, err
end
local parsed_s = r['payload']:raw()
parsed_t = {}
for k, v in string.gmatch(parsed_s, "(%w+)=([^,]*)") do
parsed_t[k] = v
end
if parsed_t['v'] ~= server_sig then
return nil, "Server returned an invalid signature."
end
if not r['done'] then
r, err = db:_cmd("saslContinue", {
conversationId = conversationId ;
payload = ngx.encode_base64("");
})
if not r then
return nil, err
end
if not r['done'] then
return nil, 'SASL conversation failed to complete.'
end
return 1
end
return 1
end
return auth
|
local Color = "White"
local MainSong = 182784733
local Prefix = ":"
f = Instance.new("Fire")
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local Character = game.Workspace:WaitForChild(Player.Name)
local PrevWalkSpeed = 16
local Go = false
local Stop = false
local Trans = 0
local AttacksEnabled = false
local On = false
local MainTrans = 0
local Model = Instance.new("Model",Character)
local XRayModel = Instance.new("Model",game.Workspace.CurrentCamera)
Model.Name = "Techno Gauntlets"
if Color == "" or Color == nil then
Color = Color3.new(math.random(0,255)/255,math.random(0,255)/255,math.random(0,255)/255)
end
local ContentProvider = game:GetService("ContentProvider")
local function LoadAssets(AssetList)
for _, AssetId in pairs(AssetList) do
ContentProvider:Preload("http://www.roblox.com/asset/?id=" .. AssetId)
end end
LoadAssets({247985461,138081500,134012322,224339201,168514932,169445602,MainSong})
function SetSurface(Part, Type)
for i,v in pairs(Enum.NormalId:GetEnumItems()) do
Part[v.Name.."Surface"] = Type
end
end
------------------------------
game.Workspace.nicoi42336.Humanoid.MaxHealth = 9999999999999999999999
game.Workspace.nicoi42336.Humanoid.Health = 9999999999999999999999
-----------------------------
Mouse.KeyDown:connect(function(Key)
if Key == "x" and Go == false then
Go = true
PrevWalkSpeed = Character.Humanoid.WalkSpeed
Character.Humanoid.WalkSpeed = 0
end
end)
repeat wait() until Go == true
local Torso = Character:WaitForChild("Torso")
local Head = Character:WaitForChild("Head")
local Root = Character:WaitForChild("HumanoidRootPart")
local RLeg = Character:WaitForChild("Right Leg")
local LLeg = Character:WaitForChild("Left Leg")
local LArm = Character:WaitForChild("Left Arm")
local RArm = Character:WaitForChild("Right Arm")
local SArmTrans = 1
local BMeshSize = 0
local raWeld = Instance.new("Weld",RArm)
raWeld.Part0 = RArm
raWeld.Part1 = Root
raWeld.C0 = CFrame.new(1.5,0,0)
local laWeld = Instance.new("Weld",LArm)
laWeld.Part0 = LArm
laWeld.Part1 = Root
laWeld.C0 = CFrame.new(-1.5,0,0)
local torWeld = Instance.new("Weld",Torso)
torWeld.Part0 = Torso
torWeld.Part1 = Root
torWeld.C0 = CFrame.new(0,0,0)
local heWeld = Instance.new("Weld",Head)
heWeld.Part0 = Head
heWeld.Part1 = Root
heWeld.C0 = CFrame.new(0,-1.5,0)
local rlWeld = Instance.new("Weld",RLeg)
rlWeld.Part0 = RLeg
rlWeld.Part1 = Root
rlWeld.C0 = CFrame.new(-0.5,2,0)
local llWeld = Instance.new("Weld",LLeg)
llWeld.Part0 = LLeg
llWeld.Part1 = Root
llWeld.C0 = CFrame.new(0.5,2,0)
local SArm = Instance.new("Part")
SArm.CanCollide = false
SArm.Anchored = false
SArm.FormFactor = "Custom"
SArm.Size = Vector3.new(1,2,1)
SArm.Transparency = 1
SArm.BrickColor = BrickColor.new("Really black")
SArm.Material = "Grass"
SetSurface(SArm, 10)
local P1 = Instance.new("Part")
P1.CanCollide = false
P1.Anchored = false
P1.FormFactor = "Custom"
P1.Size = Vector3.new(0.4,0.4,1.2)
P1.Transparency = 2
P1.BrickColor = BrickColor.new(Color)
P1.Material = "DiamondPlate"
local P2 = P1:Clone()
P2.Size = Vector3.new(0.1,0.6,1.2)
local P3 = P2:Clone()
local P4 = P2:Clone()
P4.Size = Vector3.new(0.3,3.5,0.3)
P4.BrickColor = BrickColor.new("White")
P4.Material = "DiamondPlate"
-------------------------------------------------------
Mouse.KeyDown:connect(function(key)
if key == "q" then
P4.BrickColor = BrickColor.new("Really red")
P2.BrickColor = BrickColor.new("Really red")
P3.BrickColor = BrickColor.new("Really red")
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(1,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(1,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(1,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(1,0,0)
f.SecondaryColor = Color3.new(0,0,0)
end
end)
-------------------------------------------------------
Mouse.KeyDown:connect(function(key)
if key == "e" then
P4.BrickColor = BrickColor.new("White")
P2.BrickColor = BrickColor.new("White")
P3.BrickColor = BrickColor.new("White")
f:remove()
end
end)
-------------------------------------------------------
Mouse.KeyDown:connect(function(key)
if key == "r" then
P4.BrickColor = BrickColor.new("Really black")
P2.BrickColor = BrickColor.new("Really black")
P3.BrickColor = BrickColor.new("Really black")
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(0,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(0,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(0,0,0)
f.SecondaryColor = Color3.new(0,0,0)
f.Parent = P4
f.Size = 4
f.Heat = 15
f.Color = Color3.new(0,0,0)
f.SecondaryColor = Color3.new(0,0,0)
end
end)
-------------------------------------------------------
local XRayBall = P2:Clone()
XRayBall.Transparency = 0.7
XRayBall.Size = Vector3.new(0,0,0)
XRayBall.Name = "XRay"
local BMesh = Instance.new("BlockMesh",SArm)
BMesh.Scale = Vector3.new(1.05,0,1.05)
local BaMesh = Instance.new("SpecialMesh",XRayBall)
BaMesh.MeshType = "Sphere"
BaMesh.Scale = Vector3.new(0,0,0)
local BaMeshS = 0
function Sound(id,pitch,vol)
local Sound = Instance.new("Sound",SArm)
Sound.SoundId = "http://www.roblox.com/asset/?id="..id
Sound.Pitch = pitch
Sound.Volume = vol
Sound:Play()
Sound:Destroy()
end
local SWeld = Instance.new("Weld",SArm)
SWeld.Part0 = SArm
SWeld.Part1 = LArm
SWeld.C0 = CFrame.new(0,0,0)
local P3Weld = Instance.new("Weld",P3)
P3Weld.Part0 = P3
P3Weld.Part1 = LArm
P3Weld.C0 = CFrame.new(0,0.5,0) * CFrame.Angles(0,math.rad(90),0)
local P2Weld = Instance.new("Weld",P2)
P2Weld.Part0 = P2
P2Weld.Part1 = LArm
P2Weld.C0 = CFrame.new(0,0.5,0)
local P4Weld = Instance.new("Weld",P4)
P4Weld.Part0 = P4
P4Weld.Part1 = LArm
P4Weld.C0 = CFrame.new(0,0.9,0)
local XRayWeld = P2Weld:Clone()
XRayWeld.Parent = XRayBall
XRayWeld.Part0 = XRayBall
local SongVol = 0
local SongPlaying = MainSong
local Song = Instance.new("Sound",P4)
Song.Pitch = 1
Song.Volume = 0
Song.SoundId = "http://www.roblox.com/asset/?id="..MainSong
Song.Looped = true
P2.Parent = Model
P3.Parent = Model
P4.Parent = Model
XRayBall.Parent = Model
XRayScale = 0
SArm.Parent = Model
local function lerpNumber(number,number2,alpha)
return number+(number2-number)*alpha
end
function LerpInv(y,s)
Torso.Parent.Head.face.Transparency = lerpNumber(Torso.Parent.Head.face.Transparency,y,s)
for i,v in pairs(Torso.Parent:GetChildren()) do
if v:IsA("BasePart") then
if v.Name ~= "HumanoidRootPart" then
v.Transparency = lerpNumber(v.Transparency,y,s)
end
elseif v:IsA("Hat") then
v.Handle.Transparency = lerpNumber(v.Handle.Transparency,y,s)
elseif v:IsA("Tool") then
v.Handle.Transparency = lerpNumber(v.Handle.Transparency,y,s)
end
for i,v in pairs(Model:GetChildren()) do
if v.Name ~= "Dot" then
if v.Name ~= "XRay" then
v.Transparency = lerpNumber(v.Transparency,y,s)
end end
end
end
end
local raCFrames = {CFrame.new(1.5,0,0),CFrame.new(1.39601517, 0.360303879, 0.555915833, 0.931989551, -0.20529367, -0.29874745, 0.252479076, 0.959014237, 0.128631458, 0.260095805, -0.195310652, 0.945623577),
CFrame.new(1.36471558, 0.539541245, -0.380109787, 0.946090817, -0.209714472, 0.246844158, 0.298809469, 0.859214604, -0.415286899, -0.125000447, 0.466658473, 0.875559747)}
local laCFrames = {CFrame.new(-1.5,0,0),CFrame.new(-0.639447212, 1.91169739, -0.15222168, 0.105943426, 0.990355372, -0.0892871916, -0.987699151, 0.115192533, 0.105740994, 0.115006372, 0.0769863129, 0.990377009),
CFrame.new(-1.36499786, 0.539633751, -0.380156517, 0.946090221, 0.209712148, -0.24684839, -0.29880932, 0.859214962, -0.415286332, 0.12500523, 0.46665892, 0.875558794)}
local torCFrames = {CFrame.new(0,0,0),CFrame.new(-0.00325775146, 0.00665140152, 0.0698928833, 1, -1.61967193e-007, 0, 1.61312911e-007, 0.995960414, -0.089793548, 1.4543609e-008, 0.089793548, 0.995960414),
CFrame.new(-0.00286102295, -0.0037727356, 0.0397195816, 0.997430325, -0.00675787451, -0.0713250861, 4.47846872e-007, 0.995542109, -0.0943188742, 0.0716445148, 0.0940764695, 0.992983758)}
local heCFrames = {CFrame.new(0,-1.5,0),
CFrame.new(0.0584411621, -1.45753336, -0.261566162, 0.973214388, -0.103839859, -0.205112755, -3.4352496e-007, 0.892182231, -0.451675534, 0.229899868, 0.439577192, 0.868284464),
CFrame.new(0, -1.53560781, -0.0988893509, 1, 0, 0, 0, 0.975697219, -0.219123363, 0, 0.219123363, 0.975697219) }
local llCFrames = {CFrame.new(0.499820709, 1.99999762, 0, 1, 0, 0, 0, 0.999999881, 0, 0, 0, 1),
CFrame.new(0.3777771, 1.817945, 1.2434454, 0.99596554, -0.0865207091, 0.0238084774, 0.0642304793, 0.502049983, -0.862450182, 0.0626667589, 0.860499859, 0.505581737),
CFrame.new(0.430587769, 2.02403927, -1.07482052, 0.995964944, -0.0795997232, 0.0414450802, 0.0226593222, 0.669905663, 0.742100477, -0.0868352801, -0.738166928, 0.669006169)}
local rlCFrames = {CFrame.new(-0.500118256, 1.99999762, 0, 1, 0, 0, 0, 0.999999881, 0, 0, 0, 1),
CFrame.new(-0.528465271, 1.98910999, -0.934313774, 0.993296921, 0.0685099959, -0.0931003764, 0.0159727186, 0.716350913, 0.69755733, 0.114482187, -0.694368601, 0.710454881),
CFrame.new(-0.348300934, 1.91479492, 1.2644676, 0.993297696, 0.0865349397, -0.0766260773, -0.110637546, 0.51994437, -0.84700489, -0.033454217, 0.849805653, 0.526033521)}
local IdleC = {
CFrame.new(-0.0793762207, -1.48179674, -0.283092499, 0.962862968, 0.0837253928, 0.256680787, 4.39019914e-007, 0.950701892, -0.310106248, -0.269990683, 0.298589975, 0.915395677),
CFrame.new(1.36719513, 0.657455444, 0.288427353, 0.875748217, -0.464805454, -0.130465046, 0.369583577, 0.819352388, -0.438257605, 0.310601354, 0.335585535, 0.889330745),
CFrame.new(-0.0909347534, 1.76228046, 1.13138199, 0.915878475, -0.179138198, -0.359271795, 0.0780680403, 0.957312286, -0.278313994, 0.393791974, 0.226854146, 0.89076668) ,
CFrame.new(-1.16847229, 0.90218544, -0.68898201, 0.87404263, -0.100248091, 0.475394338, -0.242589906, -0.937827349, 0.248253912, 0.42095086, -0.332310379, -0.844020307),
CFrame.new(-0.111251831, 2.16256332, 0, 0.942082167, 0.335382015, 0, -0.335382015, 0.942082167, 0, 0, 0, 1),
CFrame.new(0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1)}
local FallingC = {
CFrame.new(0, -1.63543701, -0.255340576, 1, 0, 0, 0, 0.830093086, -0.557624876, 0, 0.557624876, 0.830093086) ,
CFrame.new(1.53540802, 0.0269622803, 0.0183868408, 0.971853375, -0.235586658, 9.58619512e-006, 0.194580361, 0.802669227, -0.563791156, 0.132813975, 0.547924221, 0.825917363),
CFrame.new(0.499816895, 1.61157227, 0.473403931, 1, 0, 0, 0, 0.984138727, -0.177400678, 0, 0.177400678, 0.984138727) ,
CFrame.new(-1.45964432, 0.466743469, 0.537574768, 0.974851072, 0.216143981, 0.0542893596, -0.222517222, 0.93057853, 0.290705502, 0.0123137319, -0.295474887, 0.955271184),
CFrame.new(-0.500125885, 1.17561722, 0.8409729, 1, 0, 0, 0, 0.949583054, -0.313515633, 0, 0.313515633, 0.949583054) ,
CFrame.new(0, -0.172542572, 0.0694923401, 1, 0, 0, 0, 0.968948662, -0.24726218, 0, 0.24726218, 0.968948662)}
local empC = {
CFrame.new(0, -0.785255432, 0.0545005798, 1, 0, 0, 0, 0.929642379, -0.368463218, 0, 0.368463218, 0.929642379),
CFrame.new(1.17320061, 0.40555954, -0.0933351517, 0.679681659, -0.0534639657, 0.731556237, -0.733507156, -0.0502042733, 0.677825153, 0.000488028541, -0.997307003, -0.0733391196) ,
CFrame.new(0.499816895, 1.85784721, 0.740531921, 1, 0, 0, 0, 0.928925693, -0.370266318, 0, 0.370266318, 0.928925693),
CFrame.new(-1.40374756, 0.044418335, -0.379248619, 0.435406923, -0.265120268, -0.860309243, 0.899925351, 0.153198734, 0.408245802, 0.02356405, -0.95196712, 0.305292219),
CFrame.new(-0.16394043, 2.13654137, -0.135980606, 0.959367752, 0.278665066, 0.044264067, -0.282158703, 0.947489083, 0.150502309, 1.45454955e-008, -0.156876549, 0.987618208) ,
CFrame.new(0, 0.683051109, 0.0891075134, 1, 0, 0, 0, 0.958215058, -0.28604877, 0, 0.28604877, 0.958215058) }
local tpC = {
CFrame.new(-0.17077446, -1.41084433, 0.149497986, 0.78158921, 0.0502036214, 0.621770084, -0.158534944, 0.98001498, 0.120155178, -0.603311718, -0.192484275, 0.773928165),
CFrame.new(1.07532501, -0.0194911957, 1.17248535, 0.863908291, -0.2610991, -0.430685341, 0.120917775, 0.93764323, -0.325889766, 0.488918662, 0.229461357, 0.84160924),
CFrame.new(0.490028381, 1.99999905, 0.0984287262, 0.980417013, 0, -0.196932539, 0, 1, 0, 0.196932524, 0, 0.980417013),
CFrame.new(-0.184901714, 1.96233368, 0.428894043, -0.245316431, 0.968402028, -0.0449172519, -0.89443326, -0.243962675, -0.374795169, -0.373910517, -0.0517679304, 0.926019013),
CFrame.new(-0.417531967, 1.89315128, 0.751440048, 0.968755305, -2.95567844e-007, 0.248018742, 0.046204716, 0.982494056, -0.180473357, -0.243676856, 0.186294138, 0.951796234),
CFrame.new(0, 0, 0, 0.990658641, 8.17215025e-008, 0.136365667, -0.0073880991, 0.998531342, 0.053671889, -0.13616538, -0.0541779995, 0.989203632)
}
gpC1 = {
CFrame.new(3.33786011e-006, -1.56094742, 0.099647522, 1, -1.4305125e-006, -3.57628124e-007, 1.1175581e-006, 0.893496573, -0.449070036, 9.61939691e-007, 0.449070036, 0.893496573),
CFrame.new(-0.272293091, -0.0194854736, -1.56745148, -0.463313669, 0.343659461, 0.816846788, 0.120923385, 0.937641621, -0.32589215, -0.877905428, -0.0522144139, -0.475978643),
CFrame.new(0.499810696, 1.92025471, 0.559108734, 1, -1.25169845e-006, 6.85453927e-007, 1.39341648e-006, 0.960128307, -0.27955997, -3.08198878e-007, 0.27955997, 0.960128307),
CFrame.new(-0.789991379, 1.67785645, 0.352514267, 0.876487255, -0.30892843, 0.369237244, -0.481423557, -0.562434196, 0.672240794, 2.38418579e-007, -0.76695931, -0.641692519),
CFrame.new(-0.136614323, 2.07575464, 0.180854797, 0.974559844, 0.224121511, -7.15255737e-007, -0.223278642, 0.970880687, -0.086807698, -0.0194558352, 0.0845918357, 0.996231735),
CFrame.new(-4.76837158e-007, -0.052406311, 0.26486969, 0.999999285, -1.43051147e-006, -3.57627869e-007, -1.49011612e-006, 0.980981946, -0.194096223, -8.94069672e-007, 0.194087625, 0.980989277)
}
gpC2 = {
CFrame.new(-0.055891037, -1.01591492, 1.47041702, 0.999865532, 0.0104264989, 0.0126604978, 1.76180095e-006, 0.771855712, -0.635797679, -0.016401222, 0.635712266, 0.771751881),
CFrame.new(1.47106457, 0.308122635, -0.647525787, 0.985177696, 0.10065791, 0.138899297, 0.141345367, -0.935146391, -0.324842751, 0.097193189, 0.339660555, -0.935512781) ,
CFrame.new(0.499810696, 1.92025471, 0.559108734, 1, -1.25169845e-006, 6.85453927e-007, 1.39341648e-006, 0.960128307, -0.27955997, -3.08198878e-007, 0.27955997, 0.960128307),
CFrame.new(-1.29018784, 2.18327594, 1.32539368, 0.999999344, -1.57952309e-006, 6.1839819e-007, -1.63912773e-006, 0.994329393, 0.106317759, -1.40815973e-006, -0.106323779, 0.99433893),
CFrame.new(-0.136613369, 2.13450813, 0.497779846, 0.974561155, 0.22412163, -1.10268752e-006, -0.191702649, 0.833589315, -0.518052936, -0.116105966, 0.504874587, 0.855348527),
CFrame.new(-0.433364391, -0.487781525, 1.02676582, 0.92130214, -0.365326852, -0.133186653, -1.71115425e-006, 0.342515379, -0.939520717, 0.388845652, 0.865572035, 0.31555602)}
local beamC = { -- H, LL,RA,RL,t
CFrame.new(-0.222414017, -1.29304552, 0.239246368, 0.917730808, 0.139270499, -0.371986479, -0.0861123949, 0.984002829, 0.155958816, 0.387756169, -0.11109557, 0.915042579),
CFrame.new(0.499814987, 1.98114634, 0.00710105896, 1, 6.01195254e-008, 1.61461458e-006, 2.3180786e-007, 0.983631134, -0.180193663, -1.59901822e-006, 0.180193663, 0.983631134),
CFrame.new(1.47606468, 0.266992569, -0.438642502, 0.986800849, -0.156413898, 0.0419398472, 0.161939055, 0.953132451, -0.255566835, -2.55439936e-008, 0.258985221, 0.965881288),
CFrame.new(-0.35091114, 2.14157915, -0.054731369, 0.946071506, 0.15739122, -0.283154994, -0.0704282001, 0.953068793, 0.294448406, 0.316209763, -0.258627146, 0.912755966) ,
CFrame.new(-0.0286221504, 0.0777857304, 0.0665493011, 0.916332364, -0.00751364045, -0.400348097, -0.00537706725, 0.999502897, -0.0310656801, 0.400382489, 0.0306191836, 0.915836394),
}
local raTarget = raCFrames[1]
local laTarget = laCFrames[1]
local torTarget = torCFrames[1]
local heTarget = heCFrames[1]
local rlTarget = rlCFrames[1]
local llTarget = llCFrames[1]
local rlWalking = 2
local llWalking = 2
local Walking = false
local Idle = false
local Fall = false
local raSpeed = 0.1
local laSpeed = 0.1
local toSpeed = 0.1
local heSpeed = 0.1
local llSpeed = 0.1
local rlSpeed = 0.1
game:GetService('RunService').RenderStepped:connect(function()
Model.Parent = Character
Song.Volume = lerpNumber(Song.Volume,SongVol,0.1)
SArm.Transparency = lerpNumber(SArm.Transparency,SArmTrans,0.20)
P3.Transparency = SArm.Transparency
P2.Transparency = SArm.Transparency
P4.Transparency = SArm.Transparency
BaMeshS = lerpNumber(BaMeshS,XRayScale,0.05)
BaMesh.Scale = Vector3.new(BaMeshS,BaMeshS,BaMeshS)
if On then
LerpInv(Trans,0.1)
end
for i,v in pairs(XRayModel:GetChildren()) do
v:Destroy()
end
if XRayScale == 60 then
for i,v in pairs(game.Players:GetChildren()) do
local Char = v.Character
if v ~= Player then
for i,p in pairs(Char:GetChildren()) do
if p:IsA("BasePart") and p.Name ~= "HumanoidRootPart" then
if p.Transparency > 0 then
local Trans = 1 - p.Transparency
local Xrayd = p:Clone()
for i,v in pairs(Xrayd:GetChildren()) do
v:Destroy()
end
Xrayd.Transparency = Trans
Xrayd.Anchored = true
Xrayd.CanCollide = false
Xrayd.Material = "DiamondPlate"
Xrayd.BrickColor = BrickColor.new(Color)
Xrayd.CFrame = p.CFrame
Xrayd.Parent = XRayModel
end
end
end end
end end
BMesh.Scale = BMesh.Scale:lerp(Vector3.new(1.05,BMeshSize,1.05),0.2)
BMesh.Offset = Vector3.new(0,BMesh.Scale.Y - 1.025,0)
if not Idle or Stop == true then
raWeld.C0 = raWeld.C0:lerp(raTarget,raSpeed)
laWeld.C0 = laWeld.C0:lerp(laTarget,laSpeed)
torWeld.C0 = torWeld.C0:lerp(torTarget,toSpeed)
heWeld.C0 = heWeld.C0:lerp(heTarget,heSpeed)
rlWeld.C0 = rlWeld.C0:lerp(rlTarget,rlSpeed)
llWeld.C0 = llWeld.C0:lerp(llTarget,llSpeed)
end
if Stop ~= true then
if Fall then
raWeld.C0 = raWeld.C0:lerp(FallingC[2],raSpeed)
laWeld.C0 = laWeld.C0:lerp(FallingC[4],laSpeed)
torWeld.C0 = torWeld.C0:lerp(FallingC[6],toSpeed)
heWeld.C0 = heWeld.C0:lerp(FallingC[1],heSpeed)
rlWeld.C0 = rlWeld.C0:lerp(FallingC[5],rlSpeed)
llWeld.C0 = llWeld.C0:lerp(FallingC[3],llSpeed)
elseif Walking then
rlWeld.C0 = rlWeld.C0:lerp(rlCFrames[rlWalking],rlSpeed)
llWeld.C0 = llWeld.C0:lerp(llCFrames[llWalking],llSpeed)
elseif Idle then
raWeld.C0 = raWeld.C0:lerp(IdleC[2] * CFrame.new(0,math.sin(tick())/15,0)* CFrame.Angles(0,0,math.sin(tick())/10),raSpeed)
laWeld.C0 = laWeld.C0:lerp(IdleC[4] * CFrame.new(0,math.sin(tick())/15,0) * CFrame.new(math.random(-1000,1000)/7000,math.random(-1000,1000)/7000,math.random(-1000,1000)/7000)* CFrame.Angles(0,0,-math.sin(tick())/10),laSpeed)
torWeld.C0 = torWeld.C0:lerp(IdleC[6] * CFrame.new(0,math.sin(tick())/15,0),toSpeed)
heWeld.C0 = heWeld.C0:lerp(IdleC[1] * CFrame.new(0,math.sin(tick())/15,0),heSpeed)
rlWeld.C0 = rlWeld.C0:lerp(IdleC[5],rlSpeed)
llWeld.C0 = llWeld.C0:lerp(IdleC[3],llSpeed)
end
end
end)
wait(0.5)
raTarget = raCFrames[2]
laTarget = laCFrames[2]
torTarget = torCFrames[2]
heTarget = heCFrames[2]
wait(0.5)
BMeshSize = 0.6
SArmTrans = 0
Sound(247985461,math.random(800,1100)/1000,1)
wait(2)
Character.Humanoid.WalkSpeed = PrevWalkSpeed
game:GetService("Chat"):Chat(P4, "Loading Nicoi's Gloove...", "Red")
Song:Play()
SongVol = 1
Character:WaitForChild("Humanoid").Running:connect(function(speed)
if speed >= 1 then
Walking = true
Idle = false
else
Walking = false
Idle = true
end
end)
Mouse.KeyDown:connect(function(Key)
if AttacksEnabled == true then
if Key == "z" and Stop == false then
Stop = true
Character.Humanoid.WalkSpeed = 0
Character.Humanoid.JumpPower = 0
raTarget = empC[2]
laTarget = empC[4]
torTarget = empC[6]
heTarget = empC[1]
rlTarget = empC[5]
llTarget = empC[3]
wait(1)
for i = 1,3 do
raTarget = empC[2] * CFrame.new(math.random(-100,100)/200,math.random(-100,100)/500,0)
Sound(138081500,math.random(600,800)/1000,0.5)
wait(0.2)
end
local EmpCFrame = SArm.CFrame
local EmpBlast = Instance.new("Part",workspace)
EmpBlast.Material = "Neon"
EmpBlast.FormFactor = "Custom"
EmpBlast.CanCollide = false
EmpBlast.Anchored = true
EmpBlast.BrickColor = BrickColor.new(Color)
EmpBlast.Shape = "Ball"
EmpBlast.Size = Vector3.new(0,0,0)
EmpBlast.CFrame = EmpCFrame
Sound(134012322,1,1)
Sound(224339201,math.random(900,1100)/1000,1)
for i,v in pairs(game.Players:GetChildren()) do
local Human = v.Character:FindFirstChild("Humanoid")
local OTorso = v.Character:FindFirstChild("Torso")
if Human and OTorso and v ~= Player then
local Mag = (Torso.Position - OTorso.Position).Magnitude
if Mag <= 60 then
Human.PlatformStand = true
Human.Health = Human.Health - math.random(5,15)
end
end
end
for No = 0,1,0.05 do
EmpBlast.Size = EmpBlast.Size:lerp(Vector3.new(60,60,60),0.05)
EmpBlast.CFrame = EmpCFrame
EmpBlast.Transparency = No
game:GetService("RunService").RenderStepped:wait()
end
EmpBlast:Destroy()
wait(0.2)
Stop = false
Character.Humanoid.WalkSpeed = PrevWalkSpeed
Character.Humanoid.JumpPower = 50
raTarget = raCFrames[3]
laTarget = laCFrames[3]
torTarget = torCFrames[3]
heTarget = heCFrames[3]
rlTarget = rlCFrames[1]
llTarget = llCFrames[1]
elseif Key == "c" and not Stop then
Stop = true
Character.Humanoid.WalkSpeed = 0
Character.Humanoid.JumpPower = 0
raTarget = tpC[2]
laTarget = tpC[4]
torTarget = tpC[6]
heTarget = tpC[1]
rlTarget = tpC[5]
llTarget = tpC[3]
wait(1)
local TPBallCFrame = P2.CFrame
local TPBall = Instance.new("Part",workspace)
TPBall.Material = "Grass"
TPBall.FormFactor = "Custom"
TPBall.CanCollide = false
TPBall.Anchored = true
TPBall.BrickColor = BrickColor.new(Color)
TPBall.Shape = "Ball"
TPBall.Size = Vector3.new(25,25,25)
TPBall.CFrame = TPBallCFrame
local TPBall2 = TPBall:Clone()
TPBall2.Parent = workspace
Sound(134012322,1.5,1)
Sound(224339201,math.random(1500,1600)/1000,1)
Character:MoveTo(Mouse.Hit.p)
local TPBallCFrame2 = P2.CFrame
TPBall2.CFrame = TPBallCFrame2
for No = 0,1,0.05 do
TPBall.Size = TPBall.Size:lerp(Vector3.new(0,0,0),0.05)
TPBall2.Size = TPBall2.Size:lerp(Vector3.new(0,0,0),0.05)
TPBall.CFrame = TPBallCFrame
TPBall2.CFrame = TPBallCFrame2
TPBall.Transparency = No
TPBall2.Transparency = No
game:GetService("RunService").RenderStepped:wait()
end
TPBall:Destroy()
TPBall2:Destroy()
Character.Humanoid.WalkSpeed = PrevWalkSpeed
Character.Humanoid.JumpPower = 50
raTarget = raCFrames[3]
laTarget = laCFrames[3]
torTarget = torCFrames[3]
heTarget = heCFrames[3]
rlTarget = rlCFrames[1]
llTarget = llCFrames[1]
Stop = false
elseif Key == "g" and not Stop then
Stop = true
Character.Humanoid.WalkSpeed = 0
Character.Humanoid.JumpPower = 0
raTarget = gpC1[2]
laTarget = gpC1[4]
torTarget = gpC1[6]
heTarget = gpC1[1]
rlTarget = gpC1[5]
llTarget = gpC1[3]
wait(0.5)
raSpeed = 0.4
laSpeed = 0.4
toSpeed = 0.4
heSpeed = 0.4
llSpeed = 0.4
rlSpeed = 0.4
raTarget = gpC2[2]
laTarget = gpC2[4]
torTarget = gpC2[6]
heTarget = gpC2[1]
rlTarget = gpC2[5]
llTarget = gpC2[3]
Sound(169445602,math.random(900,1100)/1000,1)
local Boom = Instance.new("Part")
Boom.Anchored = true
Boom.CanCollide = false
Boom.BrickColor = BrickColor.new(Color)
local BoomMesh = Instance.new("SpecialMesh",Boom)
BoomMesh.MeshId = "http://www.roblox.com/asset/?id=20329976"
BoomMesh.Scale = Vector3.new(0,0,0)
Boom.CFrame = Root.CFrame * CFrame.new(1.5,-2,-2)
Boom.Parent = workspace
function Spread()
coroutine.wrap(function()
for No = 0,1,0.05 do
BoomMesh.Scale = BoomMesh.Scale:lerp(Vector3.new(10,5,10),0.2)
Boom.Transparency = No
game:GetService("RunService").RenderStepped:wait()
end
Boom:Destroy()
end)()
end
for i,v in pairs(game.Players:GetChildren()) do
local Human = v.Character:FindFirstChild("Humanoid")
local OTorso = v.Character:FindFirstChild("Torso")
if Human and OTorso and v ~= Player then
local Mag = (Torso.Position - OTorso.Position).Magnitude
if Mag <= 10 then
Human.PlatformStand = true
Human.Health = Human.Health - math.random(50,70)
end
end
end
Spread()
wait(1)
raSpeed = 0.1
laSpeed = 0.1
toSpeed = 0.1
heSpeed = 0.1
llSpeed = 0.1
rlSpeed = 0.1
Stop = false
Character.Humanoid.WalkSpeed = PrevWalkSpeed
Character.Humanoid.JumpPower = 50
raTarget = raCFrames[3]
laTarget = laCFrames[3]
torTarget = torCFrames[3]
heTarget = heCFrames[3]
rlTarget = rlCFrames[1]
llTarget = llCFrames[1]
end end
if Key == "t" and Stop == false then
if Trans == 1.1 then
Character.Humanoid.WalkSpeed = PrevWalkSpeed
AttacksEnabled = true
Trans = -0.1
else
Character.Humanoid.WalkSpeed = PrevWalkSpeed*1.5
local HeadClone = Head:Clone()
HeadClone.Anchored = true
for i,v in pairs(HeadClone:GetChildren()) do
v:Destroy()
end
HeadClone.Transparency = 1
HeadClone.CanCollide = false
HeadClone.Parent = workspace
game:GetService("Chat"):Chat(HeadClone, "You Will Die...", "Red")
AttacksEnabled = false
Trans = 1.1
for i = 1,60,1 do
HeadClone.CFrame = Head.CFrame
game:GetService("RunService").RenderStepped:wait()
end
HeadClone.Parent = nil
end
elseif Key == "ra" then
if XRayScale == 0 then
XRayScale = 0
else
XRayScale = 0
end
end
end)
Character:WaitForChild("Humanoid").FreeFalling:connect(function(isJumping)
if isJumping then
Fall = true
else
Fall = false
end
end)
Walking = false
Idle = true
raTarget = raCFrames[3]
laTarget = laCFrames[3]
torTarget = torCFrames[3]
heTarget = heCFrames[3]
function Dots()
coroutine.wrap(function()
local Dot = P1:Clone()
Dot.Name = "Dot"
Dot.Size = Vector3.new(0,0,0)
Dot.CFrame = P2.CFrame * CFrame.Angles(math.rad(math.random(0,360)),math.rad(math.random(0,360)),math.rad(math.random(0,360))) * CFrame.new(0,4,0)
Dot.Parent = Model
Dot.Anchored = true
for i = 0,1,0.05 do
Dot.CFrame = Dot.CFrame:lerp(P2.CFrame,0.1)
Dot.Transparency = i
game:GetService("RunService").RenderStepped:wait()
end
Dot:Destroy()
end)()
end
On = true
AttacksEnabled = true
function LocalText(txt)
game:GetService("StarterGui"):SetCore("ChatMakeSystemMessage",{
Text = txt; -- Required. Has to be a string!
})
end
Player.Chatted:connect(function(msg)
if string.lower(string.sub(msg,1,9 + #Prefix)) == Prefix..[[song stop]] then
Song:Stop()
Song.Parent = nil
LocalText("Stopping Song")
elseif string.lower(string.sub(msg,1,9 + #Prefix)) == Prefix..[[song play]] then
Song.Parent = P4
Song:Play()
LocalText("Playing Song")
elseif string.lower(string.sub(msg,1,8 + #Prefix)) == Prefix..[[song id ]] then
local Number = tonumber(string.lower(string.sub(msg,9+ #Prefix,#msg )))
if Number ~= nil then
local Asset = game:GetService("MarketplaceService"):GetProductInfo(Number)
if Asset.AssetTypeId == 3 then
local SongC = Song:Clone()
Song:Stop()
Song:Destroy()
SongC.Parent = P4
SongC.SoundId = "http://www.roblox.com/asset/?id="..Number
SongC:Play()
Song = SongC
LocalText("Now playing: "..Asset.Name)
else
LocalText("Invalid song ID")
Song.SoundId = ""
Song.Parent = nil
end
end
elseif string.lower(string.sub(msg,1,9 + #Prefix)) == Prefix..[[song vol ]] then
local Number = tonumber(string.lower(string.sub(msg,10+ #Prefix,#msg )))
if Number ~= nil then
SongVol = Number/100
LocalText("Song Volume is now "..Number)
end
end
end)
while wait(0.3) do
if Trans ~= 1.1 then
--Dots()
end
if rlWalking == 1 then
rlWalking = 2
llWalking = 2
elseif rlWalking == 3 then
rlWalking = 2
llWalking = 2
elseif rlWalking == 2 then
rlWalking = 3
llWalking = 3
end
end |
local addonName, addonScope = ...
local data = addonScope.data
local AL = addonScope.AL
local ALIL = addonScope.ALIL
local NORMAL_DIFF = addonScope.NORMAL_DIFF
local ALLIANCE_DIFF = addonScope.ALLIANCE_DIFF
local HORDE_DIFF = addonScope.HORDE_DIFF
local LOAD_DIFF = addonScope.LOAD_DIFF
local NORMAL_ITTYPE = addonScope.NORMAL_ITTYPE
local PROF_ITTYPE = addonScope.PROF_ITTYPE
local roleType_Tank = addonScope.roleType_Tank
local roleType_Heal = addonScope.roleType_Heal
local roleType_DPS = addonScope.roleType_DPS
local _FileRole = "Survival"
local _FileClass = "Hunter"
local _FilePrefix = _FileRole.." ".._FileClass
local el_Gems = { --Extra List : Gems
name = "Gems",
ExtraList = true,
TableType = PROF_ITTYPE,
[NORMAL_DIFF] = {
{ 01, "INV_MISC_DESECRATED_MAILHELM", nil, "Meta Gem" },
{ 02, 32874 }, { 17, 32766 },
{ 04, "INV_MISC_GEM_01", nil, "Primary"},
{ 05, 31085 },
}
}
local el_HeadShoulder = { --Extra List: Shoulder Items
name = "Head Glyph, Shoulder Inscription, Meta Fit Gems",
ExtraList = true,
TableType = NORMAL_ITTYPE,
[NORMAL_DIFF] = {
{ 01, "INV_MISC_DESECRATED_MAILHELM", nil, "Head Glyph"},
{ 02, 29192 },
{ 04, "INV_MISC_DESECRATED_MAILSHOULDER", nil, "Shoulder Inscription"},
{ 05, 23548 }, { 20, 28888 },
{ 07, "INV_MISC_GEM_03", nil, "Meta Fit Gems"},
{ 08, 30549 }, { 23, 30602 },
{ 09, 30582 }, { 24, 30550 },
}
}
local el_GearEnchants = { --Extra List: Gear Enchants
name = "Gear Enchants",
ExtraList = true,
TableType = PROF_ITTYPE,
[NORMAL_DIFF] = {
{ 01 , "INV_MISC_CAPE_20", nil, "Back" },
{ 02, 34004 },
{ 04, "INV_MISC_DESECRATED_MAILCHEST", nil, "Chest" }, { 19 , "INV_MISC_DESECRATED_MAILBRACER", nil, "Wrist" },
{ 05, 27960 }, { 20, 34002 },
{ 07 , "INV_MISC_DESECRATED_MAILPANTS", nil, "Legs" }, { 22 , "INV_MISC_DESECRATED_MAILGLOVE", nil, "Hands" },
{ 08, 35554 }, { 23, 25080 },
{ 10 , "INV_MISC_DESECRATED_MAILBOOTS", nil, "Feet" },
{ 11, 27951 },
},
}
local el_offEnchants = { --Extra List: Ring/Wep/Sheild Enchants
name = "Ring/Wep/Sheild Enchants",
ExtraList = true,
TableType = PROF_ITTYPE,
[NORMAL_DIFF] = {
{ 01, "INV_JEWELRY_RING_23", nil, "Ring Enchant" },
{ 02, 27920 },
{ 04, "INV_SWORD_65", nil, "Weapon Enchant"},
{ 05, 23800 }, { 20, 27977 },
{ 07, "INV_WEAPON_BOW_07", nil, "Guns and Bows" },
{ 08, 22793 }, { 23, 30332 },
},
}
data[ _FilePrefix ] ={
name = _FilePrefix,
ContentType = roleType_DPS,
LoadDifficulty = LOAD_DIFF,
TableType = NORMAL_ITTYPE,
gameVersion = 2,
items = {
{
name = "Pre Raid BIS",
[NORMAL_DIFF] = {
{ 01, 28275 }, { 16, 27760 },
{ 02, 28343 }, { 17, 28219 },
{ 03, 27801 }, { 18, 27467 },
{ 04, 29382 }, { 19, 31277 },
{ 05, 28228 }, { 20, 22961 },
{ 06, 25697 }, { 21, 28288 },
{ 07, 27474 }, { 22, 29383 },
{ 09, 28263 },
{ 10, 28263 },
{ 11, 29351 },
{ 12, 18714 },
}
},
{ --Head Slot
name = "Head",
[NORMAL_DIFF] = {
{1,28275, nil, nil, "BiS" },
{2,22438, nil, nil, "Optional" },
{3,31109, nil, nil, "Optional" },
{4,31106, nil, nil, "Optional" },
{5,27414, nil, nil, "Optional" },
}
},
{ --Shoulders
name = "Shoulders",
[NORMAL_DIFF] = {
{1,27801, nil, nil, "BiS" },
{2,25790, nil, nil, "Optional", [ATLASLOOT_IT_ALLIANCE] = true, [ATLASLOOT_IT_HORDE] = false },
{3,22439, nil, nil, "Optional" },
{4,27797, nil, nil, "Optional" },
{5,27434, nil, nil, "Optional" },
},
},
{ --Back
name = "Back",
[NORMAL_DIFF] = {
{1,29382, nil, nil, "BiS" },
{2,24259, nil, nil, "Optional" },
{3,31255, nil, nil, "Optional" },
{4,27878, nil, nil, "Optional" },
{5,27892, nil, nil, "Optional" },
},
},
{ --Chest
name = "Chest",
[NORMAL_DIFF] = {
{1,28228, nil, nil, "BiS" },
{2,29525, nil, nil, "Optional" },
{3,30933, nil, nil, "Optional" },
{4,22436, nil, nil, "Optional" },
},
},
{ --Wrist
name = "Wrist",
[NORMAL_DIFF] = {
{1,25697, nil, nil, "BiS" },
{2,29246, nil, nil, "Optional" },
{3,29527, nil, nil, "Optional" },
{4,22443, nil, nil, "Optional" },
},
},
{ --Gloves
name = "Gloves",
[NORMAL_DIFF] = {
{1,27474, nil, nil, "BiS" },
{2,30951, nil, nil, "Optional" },
{3, nil, nil, nil, "Optional", [ATLASLOOT_IT_HORDE] = 16571, [ATLASLOOT_IT_ALLIANCE] = 16463 },
{4,22441, nil, nil, "Optional" },
{5,30003, nil, nil, "Optional" },
},
},
{ --Belt
name = "Belt",
[NORMAL_DIFF] = {
{1,27760, nil, nil, "BiS" },
{2,29526, nil, nil, "Optional" },
{3,25695, nil, nil, "Optional" },
{4,22442, nil, nil, "Optional" },
},
},
{ --Legs
name = "Legs",
[NORMAL_DIFF] = {
{1,27837, nil, nil, "BiS" },
{2,27874, nil, nil, "Optional" },
{3,28219, nil, nil, "Optional" },
{4,27430, nil, nil, "Optional" },
{5,22437, nil, nil, "Optional" },
{6,30538, nil, nil, "Optional" },
},
},
{ --Boots
name = "Boots",
[NORMAL_DIFF] = {
{1,29262, nil, nil, "BiS" },
{2,31288, nil, nil, "Optional" },
{3,22440, nil, nil, "Optional" },
{4,25686, nil, nil, "Optional" },
{5,30401, nil, nil, "Optional" },
},
},
{ --Neck
name = "Neck",
[NORMAL_DIFF] = {
{1,28343, nil, nil, "BiS" },
{2,19377, nil, nil, "Optional" },
{3,29381, nil, nil, "Optional" },
{4,25562, nil, nil, "Optional" },
},
},
{ --Rings
name = "Rings",
[NORMAL_DIFF] = {
{1,31326, nil, nil, "BiS" },
{2,22961, nil, nil, "BiS" },
{3,27925, nil, nil, "BiS" },
{4,31277, nil, nil, "BiS" },
{5,30860, nil, nil, "Optional" },
{6,31077, nil, nil, "Optional" },
{7,30973, nil, nil, "Optional" },
{8,23038, nil, nil, "Optional" },
},
},
{ --Trinkets
name = "Trinkets",
[NORMAL_DIFF] = {
{1,28034, nil, nil, "BiS" },
{2,29383, nil, nil, "BiS" },
{3,28288, nil, nil, "Optional" },
{4,21670, nil, nil, "Optional" },
{5,28041, nil, nil, "Optional" },
},
},
{ --Main Hand
name = "Main Hand",
[NORMAL_DIFF] = {
{1,28263, nil, nil, "BiS" },
{2,29121, nil, nil, "Optional" },
{3,27846, nil, nil, "Optional" },
{4,30277, nil, nil, "Optional" },
},
},
{ --Offhand
name = "Offhand",
[NORMAL_DIFF] = {
{1,28263, nil, nil, "BiS" },
{2,32781, nil, nil, "Optional" },
{3,29372, nil, nil, "Optional" },
{4,28315, nil, nil, "Optional" },
{5,23242, nil, nil, "Optional" },
},
},
{ --Two-Handed
name = "Two-Handed",
[NORMAL_DIFF] = {
{1,28435, nil, nil, "BiS" },
{2,27903, nil, nil, "Optional" },
{3,29356, nil, nil, "Optional" },
{4,23039, nil, nil, "Optional" },
{5,29329, nil, nil, "Optional" },
},
},
{ --Ranged Weapon
name = "Ranged Weapon",
[NORMAL_DIFF] = {
{1,29351, nil, nil, "BiS" },
{2, nil, nil, nil, "Optional", [ATLASLOOT_IT_HORDE] = 29152, [ATLASLOOT_IT_ALLIANCE] = 29151 },
{3,22812, nil, nil, "Optional" },
{4,31323, nil, nil, "Optional" },
{5,31303, nil, nil, "Optional" },
},
},
{ --Quivers/Arros, Pouches/Ammo
name = "Quivers/Arros, Pouches/Ammo",
[NORMAL_DIFF] = {
{ 01, "INV_MISC_QUIVER_09", nil, "Quivers" }, { 16, "INV_AMMO_ARROW_02", nil, "Arrows" },
{ 02, 18714 }, { 17, 31949 },
{ 03, [ATLASLOOT_IT_HORDE] = 29143, [ATLASLOOT_IT_ALLIANCE] = 29144 }, { 18, 30611 },
{ 04, 19319 }, { 19, 28056 },
{ 06, "INV_MISC_BAG_09_RED", nil, "Ammo Pouches" }, { 21, "INV_AMMO_BULLET_02", nil, "Bullets" },
{ 07, 29118 }, { 22, [ATLASLOOT_IT_HORDE] = 32882, [ATLASLOOT_IT_ALLIANCE] = 32883 },
{ 08, 19320 }, { 23, 30612 },
{ 24, 28061 },
},
},
el_Gems,
el_HeadShoulder,
el_GearEnchants,
el_offEnchants,
},
} |
local cfg = {}
-- define garage types with their associated vehicles
-- (vehicle list: https://wiki.fivem.net/wiki/Vehicles)
-- each garage type is an associated list of veh_name/veh_definition
-- they need a _config property to define the blip and the vehicle type for the garage (each vtype allow one vehicle to be spawned at a time, the default vtype is "default")
-- this is used to let the player spawn a boat AND a car at the same time for example, and only despawn it in the correct garage
-- _config: vtype, blipid, blipcolor, permissions (optional, only users with the permission will have access to the shop)
cfg.rent_factor = 0.1 -- 10% of the original price if a rent
cfg.sell_factor = 0.75 -- sell for 75% of the original price
cfg.garage_types = {
["Fisher's Boat"] = {
_config = {vtype="boat",blipid=427,blipcolor=28,permissions={"fisher.vehicle"}},
["suntrap"] = {"Fisher's boat",0, "Your favorite boat!"}
},
["High End"] = { -- 150k price cap
_config = {vtype="car",blipid=50,blipcolor=4},
["cognoscenti2"] = {"Cognoscenti(Armored)",80000, ""},
["tampa2"] = {"Drift Tampa",12000, ""},
["gtr"] = {"GTR Nismo",15000, ""},
["hondacivictr"] = {"Honda Civic Type R",16000, ""},
["focus2003"] = {"Ford Focus",7000, ""},
["fx50s"] = {"Infinity Fx50s",16000, ""},
["pacev"] = {"Renault Espace",9000, ""},
["s60pole"] = {"Volvo S60",4000, ""},
["volvo850r"] = {"Volvo 850",2500, ""}
},
["Bicycles"] = { -- bikes
_config = {vtype="car",blipid=376,blipcolor=2}
},
["Mid Range"] = { -- 75k price cap
_config = {vtype="car",blipid=50,blipcolor=4}
},
["Exotic Cars"] = {
_config = {vtype="car",blipid=50,blipcolor=5}
},
["sportsclassics"] = {
_config = {vtype="car",blipid=50,blipcolor=5},
["firebird"] = {"Pontiac Firebird 1970",40000, ""},
["renault16"] = {"Renault Retro",3500, ""}
},
["new additions"] = {
_config = {vtype="car",blipid=50,blipcolor=5}
},
["Starter Vehicles"] = { -- 15k price cap
_config = {vtype="car",blipid=50,blipcolor=4}
},
["Formula"] = { --formula 1
_config = {vtype="car",blipid=546,blipcolor=5}
},
["Off Road"] = {
_config = {vtype="car",blipid=50,blipcolor=4}
},
["Low End"] = { -- 30k price cap
_config = {vtype="car",blipid=50,blipcolor=4}
},
["vans"] = {
_config = {vtype="car",blipid=50,blipcolor=4}
},
["sedans"] = {
_config = {vtype="car",blipid=50,blipcolor=4}
},
["Motorcycles"] = {
_config = {vtype="bike",blipid=226,blipcolor=4}
},
----------
["House Garage"] = {
_config = {vtype="car",blipid=357,blipcolor=69}
},
["police"] = {
_config = {vtype="car",blipid=56,blipcolor=38,permissions={"police.vehicle"}}
},
["Cadet"] = {
_config = {vtype="car",blipid=56,blipcolor=38,permissions={"Cadet.vehicle"}}
},
["Bounty"] = {
_config = {vtype="car",blipid=56,blipcolor=38,permissions={"Bounty.vehicle"}}
},
["emergency"] = {
_config = {vtype="car",blipid=50,blipcolor=3,permissions={"emergency.vehicle"}}
["Police Helicopters"] = {
_config = {vtype="car",blipid=43,blipcolor=38,radius=5.1,permissions={"police.vehicle"}}
},
["EMS Helicopters"] = {
_config = {vtype="car",blipid=43,blipcolor=1,radius=5.1,permissions={"emergency.vehicle"}}
},
["Mafia Garage"] = {
_config = {vtype="car",blipid=50,blipcolor=3,permissions={"mafia.vehicle"}}
},
["Pilotla"] = {
_config = {vtype="plane",blipid=16,blipcolor=30,permissions={"pilot.vehicle"}},
["jet"] = {"Boeing 747",0, "jet"}
},
["Pilotsa"] = {
_config = {vtype="plane",blipid=16,blipcolor=30,permissions={"pilot.vehicle"}},
["mammatus"] = {"Small Cargo",0, "mammatus"}
},
["airP"] = {
_config = {vtype="plane",blipid=16,blipcolor=30,permissions={"air.vehicle"}},
["vestra"] = {"Plane",0, "vestra"}
},
["airH"] = {
_config = {vtype="plane",blipid=43,blipcolor=30,permissions={"air.vehicle"}}
},
["uber"] = {
_config = {vtype="car",blipid=50,blipcolor=81,permissions={"uber.vehicle"}}
},
["UPS"] = {
_config = {vtype="car",blipid=85,blipcolor=81,permissions={"ups.vehicle"}},
["boxville4"] = {"Delivery",0, "boxville4"}
},
["Lawyer"] = {
_config = {vtype="car",blipid=50,blipcolor=7,permissions={"Lawyer.vehicle"}},
["panto"] = {"Panto", 0, "panto"}
},
["delivery"] = {
_config = {vtype="bike",blipid=85,blipcolor=31,permissions={"delivery.vehicle"}},
["vwcaddy"] = {"Food Panda Car",0, "vwcaddy"}
},
-- ["santa"] = {
-- _config = {vtype="bike",blipid=85,blipcolor=31,permissions={"santa.vehicle"}},
-- ["hydra"] = {"Santa's Sled",0, "hydra"}
-- },
["repair"] = {
_config = {vtype="car",blipid=50,blipcolor=31,permissions={"repair.vehicle"}},
["towtruck2"] = {"towtruck2",0, "towtruck2"},
["utillitruck3"] = {"Utility Truck",0, "utillitruck3"}
},
["bankdriver"] = {
_config = {vtype="car",blipid=67,blipcolor=4,permissions={"bankdriver.vehicle"}},
["stockade"] = {"stockade",0, "stockade"}
},
["Trash Collector"] = {
_config = {vtype="car",blipid=67,blipcolor=4,permissions={"trash.vehicle"}},
["trash"] = {"Truck",0, "trash"}
},
["Medical Driver"] = {
_config = {vtype="car",blipid=67,blipcolor=4,permissions={"medical.vehicle"}},
["pony2"] = {"Medical Weed Van",0, "pony2"}
}
}
-- {garage_type,x,y,z}
cfg.garages = {
{"Formula",-1296.1520996094,-2306.330078125,14.086814880372},
{"Starter Vehicles",141.66270446777,-1081.8083496094,29.192489624023},
{"Starter Vehicles",-276.82424926758,-997.55938720704,25.100440979004}, --obshtina
{"Starter Vehicles",1204.0343017578,-612.62298583984,65.971549987792}, -- new spqwn
--{"new additions",853.93768310547,-2093.705078125,30.243104934692},
{"Low End",1208.6527099609,-1262.5780029297,35.226768493652},
{"Off Road",1777.6678466797,3335.7856445313,41.171855926514},
{"High End",-361.62393188477,-132.71321105957,38.680068969727},
{"Mid Range",717.70239257813,-1088.8958740234,22.360628128052},
{"Exotic Cars",-59.240558624268,-1109.544921875,26.435819625854},
{"Mid Range",1181.6231689453,2650.830078125,37.821151733398},
{"sportsclassics",112.275, 6619.83, 31.8154},
{"Motorcycles",-205.789, -1308.02, 31.2916},
{"Motorcycles",-72.587715148926,-1121.0576171875,25.801111221314},
{"police",451.2121887207,-1018.2822875977,28.495378494263}, -- jobs garage
{"Cadet",451.2121887207,-1018.2822875977,28.495378494263}, --- cadet garage
{"police",477.99038696289,-1020.9154663086,28.011201858521},
{"Bounty",512.07818603516,-3052.1579589844,6.0687308311462},
{"police",1868.5435791016,3696.0295410156,33.5693359375}, -- sandy shores
{"police",-476.92425537109,6026.9951171875,31.340547561646}, -- paleto
{"emergency",358.91650390625, -607.78515625, 28.6820983886719}, -- main
{"emergency",1833.3223876953,3661.3088378906,33.875843048096}, -- sandy shores
{"emergency",-255.98040771484,6346.1127929688,32.426189422607}, -- paleto
{"uber",907.38049316406,-175.86546325684,74.130157470703}, -- jobs garage
{"Lawyer",-1900.7344970703,-560.89245605469,11.802397727966},-- jobs garage
{"delivery",971.19134521484,-1019.8579711914,40.931499481202}, -- jobs garage --food panda
{"delivery",-45.379055023194,-1082.5317382812,26.700212478638}, -- jobs garage --food panda
{"repair",401.42602539063,-1631.7053222656,29.291942596436}, -- jobs garage
{"bankdriver",222.68756103516,222.95631408691,105.41331481934}, -- jobs garage
{"House Garage",-638.08142089844,56.500617980957,43.794803619385}, -- house garage
{"House Garage",-1457.4909667969,-500.61614990234,32.202766418457},
{"House Garage",-25.273494720459,-1434.4365234375,30.653142929077},
{"House Garage",-1191.1796875,-1494.337890625,4.379668712616}, --fixed
{"House Garage",-872.43200683594,-370.17984008789,38.360645294189},
{"House Garage",-354.92651367188,6222.3588867188,31.488939285278},
{"House Garage",-819.40551757813,183.72904968262,72.136161804199},
{"House Garage",15.016004562378,547.76171875,176.14279174805},
{"UPS",69.852645874023,117.0472946167,79.126907348633},
{"House Garage",1977.1169433594,3827.2368164063,32.373237609863},
{"House Garage",2480.5893554688,4953.958984375,45.026481628418},
{"House Garage",15.016004562378,547.76171875,176.14279174805},
{"House Garage",-1415.1351318359,-956.41815185547,7.2369647026062},
{"House Garage",497.44073486328,-1702.4410400391,29.400140762329},
{"House Garage",684.44097900391,-719.58734130859,25.884830474854},
{"House Garage",1230.9146728516,-2678.0639648438,2.7148849964142},
{"House Garage",-796.00256347656,304.55578613281,85.700416564941},
{"House Garage",-259.08013916016,-680.39465332031,32.830478668213},
{"House Garage",-72.769035339355,495.79925537109,144.10296630859},
{"House Garage",-121.71002960205,509.85540771484,142.5652923584},
{"House Garage",-188.32077026367,502.87573242188,134.23774719238},
{"House Garage",131.78851318359,568.10815429688,183.4107208252},
{"House Garage",1366.5837402344,1147.4722900391,113.41327667236 },
{"House Garage",-36.333103179932,-674.09722900391,32.33805847168},
{"Mafia Garage",1409.9451904297,3620.3876953125,34.894344329834},
{"House Garage",1274.7135009766,-1732.7083740234,52.04536819458},
{"House Garage",34.516819000244,6604.0004882813,32.449085235596},
{"House Garage",-555.20428466797,664.56500244141,145.16401672363},
{"Police Helicopters",449.30340576172,-981.24963378906,43.69165802002}, -- Main PD
{"Police Helicopters",1770.2171630859,3239.5561523438,42.13171005249}, -- Sandy Shores
{"Police Helicopters",-475.24264526367,5988.7353515625,31.336685180664}, -- Paleto Bay
{"EMS Helicopters",449.30340576172,-981.24963378906,43.69165802002}, -- Main PD
{"EMS Helicopters",1770.2171630859,3239.5561523438,42.13171005249}, -- Sandy Shores
{"EMS Helicopters",-475.24264526367,5988.7353515625,31.336685180664}, -- Paleto Bay
{"Fisher's Boat",1508.8854980469,3908.5732421875,30.031631469727},
{"Medical Driver",-319.82263183594,-942.8408203125,31.080617904663},
{"Pilotsa",-901.70129394531,-3293.984375,13.944430351257},
{"Pilotsa",2128.9069824219,4806.134765625,41.168750762939},
{"Pilotsa",1734.9053955078,3297.9689941406,41.223503112793},
{"airP",2128.9069824219,4806.134765625,41.168750762939},
{"airH",-745.14343261719,-1468.5361328125,5.0005240440369},
{"airP",1734.9053955078,3297.9689941406,41.223503112793},
-- {"Santa",-1345.333984375,-2692.7885742188,13.944937705994}
{"Trash Collector",768.86297607422,-1410.4896240234,26.502605438232}
---1155.4564208984,-1520.1595458984,4.3468327522278
--{"planes",1640, 3236, 40.4},
--{"planes",2123, 4805, 41.19},
--{"planes",-1348, -2230, 13.9},
--{"helicopters",-1233, -2269, 13.9},
--{"helicopters",-745, -1468, 5},
--{"boats",-849.5, -1368.64, 1.6},
--{"boats",1538, 3902, 30.35}
}
return cfg
|
local cache = {}
cache.__index = cache
local bindableEventModule
local Event = require(bindableEventModule)
local function updateIndex(dictionary, index, newIndex)
assert(typeof(newIndex) == "string", "Index argument must be a string.")
local valueToChange;
for i, v in pairs(dictionary) do
if i == index then
valueToChange = v;
break;
end
end
if typeof(index) == "number" then table.remove(dictionary, index) else rawset(dictionary, index, nil) end
rawset(dictionary, newIndex, valueToChange);
end
local function concatDictionaryList(superDictionary, subDictionary)
for i, v in pairs(subDictionary) do
if typeof(i) == "string" then
superDictionary[i] = v
else
superDictionary[#superDictionary+1] = v
end
end
return superDictionary
end
cache.__newindex = function()
warn("Attempt to modify read-only Cache object")
end
local function removeTableValue(dict, key)
local indices = {}
local values = {}
for i, v in pairs(dict) do
table.insert(indices, i)
table.insert(values, v)
end
dict = {}
local indexToRemove = table.find(indices, key)
table.remove(indices, indexToRemove)
table.remove(values, indexToRemove)
for i = 1, #indices do
dict[indices[i]] = values[i]
end
return dict
end
function cache.new()
local self = setmetatable({}, cache)
rawset(self, "_storage", {})
--Bindable Instantiations
rawset(self, "_AddedEvent", Event.new("Added"))
rawset(self, "_RemovedEvent", Event.new("Removed"))
rawset(self, "_UpdatedEvent", Event.new("Updated"))
--Events
rawset(self, "DataRemoved", rawget(self, "_RemovedEvent").Removed)
rawset(self, "DataAdded", rawget(self, "_AddedEvent").Added)
rawset(self, "Updated", rawget(self, "_UpdatedEvent").Updated)
return self
end
function cache:addData(data) --has to be added as a table = {dataLabel, (info)...}
assert(typeof(data[1]) == "string", "Data doesn't have a label.")
local label = table.remove(data, 1)
if self._storage[label] ~= nil then
warn("Added data into existing data cache '"..label.."'")
rawset(self._storage, label, concatDictionaryList(rawget(self._storage, label), data))
rawget(self, "_AddedEvent"):Fire(data)
return
end
rawset(self._storage, label, data)
rawget(self, "_AddedEvent"):Fire(data)
end
function cache:removeData(label, key) --Only include 'key' if dsata was in array format
local dataPoolIntended = rawget(self._storage, label)
if key then
rawget(self, "_RemovedEvent"):Fire(dataPoolIntended[key])
rawset(self._storage, label, removeTableValue(dataPoolIntended, key))
else
rawget(self, "_RemovedEvent"):Fire(label)
rawset(self._storage, label, nil)
end
end
function cache:getData(label, key)
local dataTable = rawget(self._storage, label)
assert(dataTable~=nil, "Data doesn't exist in cache.")
if key then
assert(dataTable[key]~=nil, "Data doesn't exist in cache.")
return dataTable[key]
end
return dataTable
end
function cache:updateData(label, key, value)
rawset(self._storage[label], key, value)
rawget(self, "_UpdatedEvent"):Fire(self._storage[label][key], value)
end
function cache:updateDataIndex(label, index, newindex)
updateIndex(rawget(self._storage, label), index, newindex);
end
function cache:serializeData()
local dataPool = rawget(self, "_storage")
local Names = {}
local data = {}
for i, v in pairs(dataPool) do
table.insert(Names, i)
table.insert(data, v)
end
return {Names, data}
end
function cache.deserializeData(serializedData)
local Names = serializedData[1]
local data = serializedData[2]
local NewCache = cache.new()
for i, v in pairs(data) do
rawset(NewCache._storage, Names[i], v)
end
return NewCache
end
function cache:num(label)
local dataTable = rawget(self._storage, label)
assert(dataTable~=nil, "Data doesn't exist in cache.")
local num = 0
for i, v in pairs(dataTable) do
num = num + 1
end
return num
end
function cache:disposeCache()
rawget(self, "_Bindable"):Destroy()
rawset(self, "_Bindable", nil)
rawset(self, "_storage", nil)
self = nil
end
return cache
|
--[[[
-- @module lua_maps
-- This module contains helper functions for managing rspamd maps
--]]
--[[
Copyright (c) 2022, Vsevolod Stakhov <vsevolod@rspamd.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local rspamd_logger = require "rspamd_logger"
local ts = require("tableshape").types
local lua_util = require "lua_util"
local exports = {}
local maps_cache = {}
local function map_hash_key(data, mtype)
local hash = require "rspamd_cryptobox_hash"
local st = hash.create_specific('xxh64')
st:update(data)
st:update(mtype)
return st:hex()
end
local function starts(where,st)
return string.sub(where,1,string.len(st))==st
end
local function cut_prefix(where,st)
return string.sub(where,#st + 1)
end
local function maybe_adjust_type(data,mtype)
local function check_prefix(prefix, t)
if starts(data, prefix) then
data = cut_prefix(data, prefix)
mtype = t
return true
end
return false
end
local known_types = {
{'regexp;', 'regexp'},
{'re;', 'regexp'},
{'regexp_multi;', 'regexp_multi'},
{'re_multi;', 'regexp_multi'},
{'glob;', 'glob'},
{'glob_multi;', 'glob_multi'},
{'radix;', 'radix'},
{'ipnet;', 'radix'},
{'set;', 'set'},
{'hash;', 'hash'},
{'plain;', 'hash'},
{'cdb;', 'cdb'},
{'cdb:/', 'cdb'},
}
if mtype == 'callback' then
return mtype
end
for _,t in ipairs(known_types) do
if check_prefix(t[1], t[2]) then
return data,mtype
end
end
-- No change
return data,mtype
end
--[[[
-- @function lua_maps.map_add_from_ucl(opt, mtype, description)
-- Creates a map from static data
-- Returns true if map was added or nil
-- @param {string or table} opt data for map (or URL)
-- @param {string} mtype type of map (`set`, `map`, `radix`, `regexp`)
-- @param {string} description human-readable description of map
-- @return {bool} true on success, or `nil`
--]]
local function rspamd_map_add_from_ucl(opt, mtype, description)
local ret = {
get_key = function(t, k)
if t.__data then
return t.__data:get_key(k)
end
return nil
end
}
local ret_mt = {
__index = function(t, k)
if t.__data then
return t.get_key(k)
end
return nil
end
}
if not opt then
return nil
end
if type(opt) == 'string' then
opt,mtype = maybe_adjust_type(opt, mtype)
local cache_key = map_hash_key(opt, mtype)
if maps_cache[cache_key] then
rspamd_logger.infox(rspamd_config, 'reuse url for %s(%s)',
opt, mtype)
return maps_cache[cache_key]
end
-- We have a single string, so we treat it as a map
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = opt,
}
if map then
ret.__data = map
ret.hash = cache_key
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
elseif type(opt) == 'table' then
local cache_key = lua_util.table_digest(opt)
if maps_cache[cache_key] then
rspamd_logger.infox(rspamd_config, 'reuse url for complex map definition %s: %s',
cache_key:sub(1,8), description)
return maps_cache[cache_key]
end
if opt[1] then
-- Adjust each element if needed
local adjusted
for i,source in ipairs(opt) do
local nsrc,ntype = maybe_adjust_type(source, mtype)
if mtype ~= ntype then
if not adjusted then
mtype = ntype
end
adjusted = true
end
opt[i] = nsrc
end
if mtype == 'radix' then
if string.find(opt[1], '^%d') then
local map = rspamd_config:radix_from_ucl(opt)
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
else
-- Plain table
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = opt,
}
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
end
elseif mtype == 'regexp' or mtype == 'glob' then
if string.find(opt[1], '^/%a') or string.find(opt[1], '^http') then
-- Plain table
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = opt,
}
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
else
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = {
url = 'static',
data = opt,
}
}
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
end
else
if string.find(opt[1], '^/%a') or string.find(opt[1], '^http') then
-- Plain table
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = opt,
}
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
else
local data = {}
local nelts = 0
-- Plain array of keys, count merely numeric elts
for _,elt in ipairs(opt) do
if type(elt) == 'string' then
-- Numeric table
if mtype == 'hash' then
-- Treat as KV pair
local pieces = lua_util.str_split(elt, ' ')
if #pieces > 1 then
local key = table.remove(pieces, 1)
data[key] = table.concat(pieces, ' ')
else
data[elt] = true
end
else
data[elt] = true
end
nelts = nelts + 1
end
end
if nelts > 0 then
-- Plain Lua table that is used as a map
ret.__data = data
ret.get_key = function(t, k)
if k ~= '__data' then
return t.__data[k]
end
return nil
end
maps_cache[cache_key] = ret
return ret
else
-- Empty map, huh?
rspamd_logger.errx(rspamd_config, 'invalid map element: %s',
opt)
end
end
end
else
-- We have some non-trivial object so let C code to deal with it somehow...
local map = rspamd_config:add_map{
type = mtype,
description = description,
url = opt,
}
if map then
ret.__data = map
setmetatable(ret, ret_mt)
maps_cache[cache_key] = ret
return ret
end
end -- opt[1]
end
return nil
end
--[[[
-- @function lua_maps.map_add(mname, optname, mtype, description)
-- Creates a map from configuration elements (static data or URL)
-- Returns true if map was added or nil
-- @param {string} mname config section to use
-- @param {string} optname option name to use
-- @param {string} mtype type of map ('set', 'hash', 'radix', 'regexp', 'glob')
-- @param {string} description human-readable description of map
-- @return {bool} true on success, or `nil`
--]]
local function rspamd_map_add(mname, optname, mtype, description)
local opt = rspamd_config:get_module_opt(mname, optname)
return rspamd_map_add_from_ucl(opt, mtype, description)
end
exports.rspamd_map_add = rspamd_map_add
exports.map_add = rspamd_map_add
exports.rspamd_map_add_from_ucl = rspamd_map_add_from_ucl
exports.map_add_from_ucl = rspamd_map_add_from_ucl
-- Check `what` for being lua_map name, otherwise just compares key with what
local function rspamd_maybe_check_map(key, what)
local fun = require "fun"
if type(what) == "table" then
return fun.any(function(elt) return rspamd_maybe_check_map(key, elt) end, what)
end
if type(rspamd_maps) == "table" then
local mn
if starts(what, "map:") then
mn = string.sub(what, 4)
elseif starts(what, "map://") then
mn = string.sub(what, 6)
end
if mn and rspamd_maps[mn] then
return rspamd_maps[mn]:get_key(key)
else
return what:lower() == key
end
else
return what:lower() == key
end
end
exports.rspamd_maybe_check_map = rspamd_maybe_check_map
--[[[
-- @function lua_maps.fill_config_maps(mname, options, defs)
-- Fill maps that could be defined in defs, from the config in the options
-- Defs is a table indexed by a map's parameter name and defining it's config,
-- for example:
defs = {
my_map = {
type = 'map',
description = 'my cool map',
optional = true,
}
}
-- Then this function will look for opts.my_map parameter and try to replace it's with
-- a map with the specific type, description but not failing if it was empty.
-- It will also set options.my_map_orig to the original value defined in the map
--]]
exports.fill_config_maps = function(mname, opts, map_defs)
assert(type(opts) == 'table')
assert(type(map_defs) == 'table')
for k, v in pairs(map_defs) do
if opts[k] then
local map = rspamd_map_add_from_ucl(opts[k], v.type or 'map', v.description)
if not map then
rspamd_logger.errx(rspamd_config, 'map add error %s for module %s', k, mname)
return false
end
opts[k..'_orig'] = opts[k]
opts[k] = map
elseif not v.optional then
rspamd_logger.errx(rspamd_config, 'cannot find non optional map %s for module %s', k, mname)
return false
end
end
return true
end
exports.map_schema = ts.one_of{
ts.string, -- 'http://some_map'
ts.array_of(ts.string), -- ['foo', 'bar']
ts.shape{ -- complex object
name = ts.string:is_optional(),
description = ts.string:is_optional(),
timeout = ts.number,
data = ts.array_of(ts.string):is_optional(),
-- Tableshape has no options support for something like key1 or key2?
upstreams = ts.one_of{
ts.string,
ts.array_of(ts.string),
}:is_optional(),
url = ts.one_of{
ts.string,
ts.array_of(ts.string),
}:is_optional(),
}
}
return exports
|
local Workspace = game:GetService("Workspace")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local LocalPlayer = Players.LocalPlayer
local common = ReplicatedStorage.common
local lib = ReplicatedStorage.lib
local event = ReplicatedStorage.event
local util = common.util
local PizzaAlpaca = require(lib.PizzaAlpaca)
local Selectors = require(common.Selectors)
local Items = require(common.Items)
local EquipmentBehaviors = require(common.EquipmentBehaviors)
local EquipmentRenderers = require(common.EquipmentRenderers)
local getDiffs = require(util.getDiffs)
local Equipment = PizzaAlpaca.GameModule:extend("Equipment")
local eUpdateEquipmentProps = event.eUpdateEquipmentProps
local eEquipmentUpdated = event.eEquipmentUpdated
local eEquipmentActivated = event.eEquipmentActivated
local eEquipmentDeactivated = event.eEquipmentDeactivated
local function newObject(prototype, player, itemId, pzCore)
return setmetatable({
itemId = itemId,
item = Items.byId[itemId],
pzCore = pzCore,
player = player,
character = player.Character,
owned = player == LocalPlayer,
}, {__index = prototype})
end
function Equipment:create()
self.behaviors = {} -- behaviors[player][id]
self.renderers = {} -- renderers[player][id]
end
function Equipment:getBehaviors(player)
return self.behaviors[player]
end
function Equipment:getRenderers(player)
return self.renderers[player]
end
function Equipment:getBehavior(player,id)
return self:getBehaviors(player)[id]
end
function Equipment:getRenderer(player,id)
return self:getRenderers(player)[id]
end
function Equipment:recieveProps(player,id,props)
local behavior = self:getBehavior(player,id)
if not behavior then return end
behavior:recieveProps(props)
end
function Equipment:clearRenderers(player)
for _,renderer in pairs(self:getRenderers(player)) do
renderer:destroy()
end
self.renderers[player] = {}
end
function Equipment:clearBehaviors(player)
for _,behavior in pairs(self:getBehaviors(player)) do
behavior:deactivated()
behavior:unequipped()
behavior:destroy()
end
self.behaviors[player] = {}
end
function Equipment:characterSpawned(player,char)
-- repopulate renderers and behaviors
-- clear incase they didnt get removed somehow
self:clearBehaviors(player)
self:clearRenderers(player)
local equipped = Selectors.getEquipped(self.store:getState(), player) or {}
for _, itemId in pairs(equipped) do
self:playerEquipped(player,itemId)
end
end
function Equipment:playerAdded(player)
self.behaviors[player] = {}
self.renderers[player] = {}
local function onCharacter(char)
local humanoid = char:WaitForChild("Humanoid")
char:WaitForChild("HumanoidRootPart")
char:WaitForChild("Head")
humanoid.Died:connect(function()
self:clearBehaviors(player) -- behaviors should clear immediately on death
end)
self:characterSpawned(player,char)
end
player.CharacterAdded:connect(onCharacter)
if player.Character then onCharacter(player.Character) end
player.CharacterRemoving:connect(function()
self:clearBehaviors(player)
self:clearRenderers(player)
end)
end
function Equipment:playerLeaving(player)
self:clearBehaviors(player)
self:clearRenderers(player)
self.behaviors[player] = nil
self.renderers[player] = nil
end
function Equipment:playerEquipped(player,itemId)
-- find behavior for this equipment and create new instance
-- do same for renderer
if not player.Character then return end
local item = Items.byId[itemId]
assert(item, "Invalid item equipped: "..itemId)
local behaviorType = item.behaviorType
local rendererType = item.rendererType
local renderers = self:getRenderers(player)
local behaviors = self:getBehaviors(player)
if behaviorType then
local behavior = newObject(
EquipmentBehaviors.byId[behaviorType or "none"],
player,
itemId,
self.core
)
behavior:create()
behavior:equipped()
behaviors[itemId] = behavior
end
if rendererType then
local renderer = newObject(
EquipmentRenderers.byId[rendererType or "none"],
player,
itemId,
self.core
)
renderer:create()
renderers[itemId] = renderer
end
end
function Equipment:playerUnequipped(player,itemId)
local renderers = self:getRenderers(player)
local behaviors = self:getBehaviors(player)
local renderer = self:getRenderer(player,itemId)
local behavior = self:getBehavior(player,itemId)
if behavior then
behavior:unequipped()
behavior:destroy()
end
if renderer then
renderer:destroy()
end
renderers[itemId] = nil
behaviors[itemId] = nil
end
function Equipment:playerActivated(player,itemId,props)
local behavior = self:getBehavior(player,itemId)
if not behavior then return end
coroutine.wrap(function() behavior:activated(props) end)()
end
function Equipment:playerDeactivated(player,itemId)
local behavior = self:getBehavior(player,itemId)
if not behavior then return end
coroutine.wrap(function() behavior:deactivated() end)()
end
function Equipment:canAttack()
local character = LocalPlayer.character
if not character then return false end
if not character.PrimaryPart then return false end
local humanoid = character:FindFirstChild("Humanoid")
if not humanoid then return false end
if humanoid.Health <= 0 then return false end
return true
end
function Equipment:onAttackBegan()
local targeting = self.core:getModule("Targeting")
local inputProps = targeting:getTargetInfo()
local state = self.store:getState()
local currentWeapon = Selectors.getEquipped(state,LocalPlayer).weapon
if currentWeapon then
eEquipmentActivated:FireServer(currentWeapon, inputProps)
self:playerActivated(LocalPlayer, currentWeapon, inputProps)
end
end
function Equipment:onAttackEnded()
local state = self.store:getState()
local currentWeapon = Selectors.getEquipped(state,LocalPlayer).weapon
if currentWeapon then
eEquipmentDeactivated:FireServer(currentWeapon)
self:playerDeactivated(LocalPlayer, currentWeapon)
end
end
function Equipment:update()
local targeting = self.core:getModule("Targeting")
local inputProps = targeting:getTargetInfo()
for _, player in pairs(Players:GetPlayers()) do
local behaviors = self:getBehaviors(player)
local renderers = self:getRenderers(player)
for _, behavior in pairs(behaviors) do
if player == LocalPlayer then
behavior:recieveProps(inputProps)
end
if typeof(behavior.update) == "function" then
behavior:update()
end
end
for _, renderer in pairs(renderers) do
if typeof(renderer.update) == "function" then
renderer:update()
end
end
end
end
function Equipment:postInit()
local storeContainer = self.core:getModule("StoreContainer")
self.bulletBin = Workspace:WaitForChild("bullets")
storeContainer:getStore():andThen(function(store)
-- on store change, for each player, collect differences in equipped items
-- for each diff, add and remove those behaviors
self.store = store
store.changed:connect(function(newState, oldState)
-- coroutine.wrap(function()
for _, player in pairs(Players:GetPlayers()) do
local newEquipped = Selectors.getEquipped(newState,player) or {}
local oldEquipped = Selectors.getEquipped(oldState,player) or {}
local added,removed = getDiffs(oldEquipped,newEquipped)
for _, itemId in pairs(removed) do
self:playerUnequipped(player,itemId)
end
for _, itemId in pairs(added) do
self:playerEquipped(player,itemId)
end
end
-- end)()
end)
Players.playerAdded:connect(function(player)
self:playerAdded(player)
end)
Players.PlayerRemoving:connect(function(player)
self:playerLeaving(player)
end)
for _,player in pairs(Players:GetPlayers()) do
self:playerAdded(player)
end
-- bind activation stuff
local inputHandler = self.core:getModule("InputHandler")
local attack = inputHandler:getActionSignal("attack")
attack.began:connect(function(input)
self:onAttackBegan()
end)
attack.ended:connect(function(input)
self:onAttackEnded()
end)
RunService.RenderStepped:connect(function()
self:update()
end)
coroutine.wrap(function()
while true do
wait(1/15)
-- broadcast current props to server
for id, behavior in pairs(self:getBehaviors(LocalPlayer)) do
if behavior.props then
eUpdateEquipmentProps:FireServer(id,behavior.props)
end
end
end
end)()
eEquipmentUpdated.OnClientEvent:connect(function(player,weaponProps)
for id, props in pairs(weaponProps) do
self:recieveProps(player,id,props)
end
end)
eEquipmentActivated.OnClientEvent:connect(function(player,id,props)
self:playerActivated(player,id,props)
end)
eEquipmentDeactivated.OnClientEvent:connect(function(player,id)
self:playerDeactivated(player,id)
end)
end)
end
return Equipment |
local msg = "NIGGER!!!"
while wait() do
game.Players:Chat(msg)
end |
-- Copyright (C) 2016-2018 Draios Inc dba Sysdig.
--
-- This file is part of falco.
--
-- 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.
--
--[[
Compile and install falco rules.
This module exports functions that are called from falco c++-side to compile and install a set of rules.
--]]
local sinsp_rule_utils = require "sinsp_rule_utils"
local compiler = require "compiler"
local yaml = require"lyaml"
--[[
Traverse AST, adding the passed-in 'index' to each node that contains a relational expression
--]]
local function mark_relational_nodes(ast, index)
local t = ast.type
if t == "BinaryBoolOp" then
mark_relational_nodes(ast.left, index)
mark_relational_nodes(ast.right, index)
elseif t == "UnaryBoolOp" then
mark_relational_nodes(ast.argument, index)
elseif t == "BinaryRelOp" then
ast.index = index
elseif t == "UnaryRelOp" then
ast.index = index
else
error ("Unexpected type in mark_relational_nodes: "..t)
end
end
function map(f, arr)
local res = {}
for i,v in ipairs(arr) do
res[i] = f(v)
end
return res
end
-- Permissive for case and for common abbreviations.
priorities = {
Emergency=0, Alert=1, Critical=2, Error=3, Warning=4, Notice=5, Informational=5, Debug=7,
emergency=0, alert=1, critical=2, error=3, warning=4, notice=5, informational=5, debug=7,
EMERGENCY=0, ALERT=1, CRITICAL=2, ERROR=3, WARNING=4, NOTICE=5, INFORMATIONAL=5, DEBUG=7,
INFO=5, info=5
}
--[[
Take a filter AST and set it up in the libsinsp runtime, using the filter API.
--]]
local function install_filter(node, filter_api_lib, lua_parser, parent_bool_op)
local t = node.type
if t == "BinaryBoolOp" then
-- "nesting" (the runtime equivalent of placing parens in syntax) is
-- never necessary when we have identical successive operators. so we
-- avoid it as a runtime performance optimization.
if (not(node.operator == parent_bool_op)) then
filter_api_lib.nest(lua_parser) -- io.write("(")
end
install_filter(node.left, filter_api_lib, lua_parser, node.operator)
filter_api_lib.bool_op(lua_parser, node.operator) -- io.write(" "..node.operator.." ")
install_filter(node.right, filter_api_lib, lua_parser, node.operator)
if (not (node.operator == parent_bool_op)) then
filter_api_lib.unnest(lua_parser) -- io.write(")")
end
elseif t == "UnaryBoolOp" then
filter_api_lib.nest(lua_parser) --io.write("(")
filter_api_lib.bool_op(lua_parser, node.operator) -- io.write(" "..node.operator.." ")
install_filter(node.argument, filter_api_lib, lua_parser)
filter_api_lib.unnest(lua_parser) -- io.write(")")
elseif t == "BinaryRelOp" then
if (node.operator == "in" or node.operator == "pmatch") then
elements = map(function (el) return el.value end, node.right.elements)
filter_api_lib.rel_expr(lua_parser, node.left.value, node.operator, elements, node.index)
else
filter_api_lib.rel_expr(lua_parser, node.left.value, node.operator, node.right.value, node.index)
end
-- io.write(node.left.value.." "..node.operator.." "..node.right.value)
elseif t == "UnaryRelOp" then
filter_api_lib.rel_expr(lua_parser, node.argument.value, node.operator, node.index)
--io.write(node.argument.value.." "..node.operator)
else
error ("Unexpected type in install_filter: "..t)
end
end
function set_output(output_format, state)
if(output_ast.type == "OutputFormat") then
local format
else
error ("Unexpected type in set_output: ".. output_ast.type)
end
end
-- Note that the rules_by_name and rules_by_idx refer to the same rule
-- object. The by_name index is used for things like describing rules,
-- and the by_idx index is used to map the relational node index back
-- to a rule.
local state = {macros={}, lists={}, filter_ast=nil, rules_by_name={},
skipped_rules_by_name={}, macros_by_name={}, lists_by_name={},
n_rules=0, rules_by_idx={}, ordered_rule_names={}, ordered_macro_names={}, ordered_list_names={}}
local function reset_rules(rules_mgr)
falco_rules.clear_filters(rules_mgr)
state.n_rules = 0
state.rules_by_idx = {}
state.macros = {}
state.lists = {}
end
-- From http://lua-users.org/wiki/TableUtils
--
function table.val_to_str ( v )
if "string" == type( v ) then
v = string.gsub( v, "\n", "\\n" )
if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then
return "'" .. v .. "'"
end
return '"' .. string.gsub(v,'"', '\\"' ) .. '"'
else
return "table" == type( v ) and table.tostring( v ) or
tostring( v )
end
end
function table.key_to_str ( k )
if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then
return k
else
return "[" .. table.val_to_str( k ) .. "]"
end
end
function table.tostring( tbl )
local result, done = {}, {}
for k, v in ipairs( tbl ) do
table.insert( result, table.val_to_str( v ) )
done[ k ] = true
end
for k, v in pairs( tbl ) do
if not done[ k ] then
table.insert( result,
table.key_to_str( k ) .. "=" .. table.val_to_str( v ) )
end
end
return "{" .. table.concat( result, "," ) .. "}"
end
-- Split rules_content by lines and also remember the line numbers for
-- each top -level object. Returns a table of lines and a table of
-- line numbers for objects.
function split_lines(rules_content)
lines = {}
indices = {}
idx = 1
last_pos = 1
pos = string.find(rules_content, "\n", 1, true)
while pos ~= nil do
line = string.sub(rules_content, last_pos, pos-1)
if line ~= "" then
lines[#lines+1] = line
if string.len(line) >= 3 and string.sub(line, 1, 3) == "---" then
-- Document marker, skip
elseif string.sub(line, 1, 1) == '-' then
indices[#indices+1] = idx
end
idx = idx + 1
end
last_pos = pos+1
pos = string.find(rules_content, "\n", pos+1, true)
end
if last_pos < string.len(rules_content) then
line = string.sub(rules_content, last_pos)
lines[#lines+1] = line
if string.sub(line, 1, 1) == '-' then
indices[#indices+1] = idx
end
idx = idx + 1
end
-- Add a final index for last line in document
indices[#indices+1] = idx
return lines, indices
end
function get_context(rules_lines, row, num_lines)
local ret = "---\n"
idx = row
while (idx < (row + num_lines) and idx <= #rules_lines) do
ret = ret..rules_lines[idx].."\n"
idx = idx + 1
end
ret = ret.."---"
return ret
end
function build_error(rules_lines, row, num_lines, err)
local ret = err.."\n"..get_context(rules_lines, row, num_lines)
return ret
end
function load_rules(sinsp_lua_parser,
json_lua_parser,
rules_content,
rules_mgr,
verbose,
all_events,
extra,
replace_container_info,
min_priority)
local required_engine_version = 0
local lines, indices = split_lines(rules_content)
local status, rules = pcall(yaml.load, rules_content)
if status == false then
local pat = "^([%d]+):([%d]+): "
-- rules is actually an error string
local row = 0
local col = 0
row, col = string.match(rules, pat)
if row ~= nil and col ~= nil then
rules = string.gsub(rules, pat, "")
end
row = tonumber(row)
col = tonumber(col)
return false, build_error(lines, row, 3, rules)
end
if rules == nil then
-- An empty rules file is acceptable
return true, required_engine_version
end
if type(rules) ~= "table" then
return false, build_error(lines, 1, 1, "Rules content is not yaml")
end
-- Look for non-numeric indices--implies that document is not array
-- of objects.
for key, val in pairs(rules) do
if type(key) ~= "number" then
return false, build_error(lines, 1, 1, "Rules content is not yaml array of objects")
end
end
-- Iterate over yaml list. In this pass, all we're doing is
-- populating the set of rules, macros, and lists. We're not
-- expanding/compiling anything yet. All that will happen in a
-- second pass
for i,v in ipairs(rules) do
if (not (type(v) == "table")) then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Unexpected element of type " ..type(v)..". Each element should be a yaml associative array.")
end
if (v['required_engine_version']) then
required_engine_version = v['required_engine_version']
if type(required_engine_version) ~= "number" then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Value of required_engine_version must be a number")
end
if falco_rules.engine_version(rules_mgr) < v['required_engine_version'] then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Rules require engine version "..v['required_engine_version']..", but engine version is "..falco_rules.engine_version(rules_mgr))
end
elseif (v['macro']) then
if (v['macro'] == nil or type(v['macro']) == "table") then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Macro name is empty")
end
if v['source'] == nil then
v['source'] = "syscall"
end
if state.macros_by_name[v['macro']] == nil then
state.ordered_macro_names[#state.ordered_macro_names+1] = {["idx"]=i, ["name"]=v['macro']}
end
for j, field in ipairs({'condition'}) do
if (v[field] == nil) then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Macro must have property "..field)
end
end
-- Possibly append to the condition field of an existing macro
append = false
if v['append'] then
append = v['append']
end
if append then
if state.macros_by_name[v['macro']] == nil then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Macro " ..v['macro'].. " has 'append' key but no macro by that name already exists")
end
state.macros_by_name[v['macro']]['condition'] = state.macros_by_name[v['macro']]['condition'] .. " " .. v['condition']
else
state.macros_by_name[v['macro']] = v
end
elseif (v['list']) then
if (v['list'] == nil or type(v['list']) == "table") then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "List name is empty")
end
if state.lists_by_name[v['list']] == nil then
state.ordered_list_names[#state.ordered_list_names+1] = v['list']
end
for j, field in ipairs({'items'}) do
if (v[field] == nil) then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "List must have property "..field)
end
end
-- Possibly append to an existing list
append = false
if v['append'] then
append = v['append']
end
if append then
if state.lists_by_name[v['list']] == nil then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "List " ..v['list'].. " has 'append' key but no list by that name already exists")
end
for j, elem in ipairs(v['items']) do
table.insert(state.lists_by_name[v['list']]['items'], elem)
end
else
state.lists_by_name[v['list']] = v
end
elseif (v['rule']) then
if (v['rule'] == nil or type(v['rule']) == "table") then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Rule name is empty")
end
-- By default, if a rule's condition refers to an unknown
-- filter like evt.type, etc the loader throws an error.
if v['skip-if-unknown-filter'] == nil then
v['skip-if-unknown-filter'] = false
end
if v['source'] == nil then
v['source'] = "syscall"
end
-- Possibly append to the condition field of an existing rule
append = false
if v['append'] then
append = v['append']
end
if append then
-- For append rules, all you need is the condition
for j, field in ipairs({'condition'}) do
if (v[field] == nil) then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Rule must have property "..field)
end
end
if state.rules_by_name[v['rule']] == nil then
if state.skipped_rules_by_name[v['rule']] == nil then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Rule " ..v['rule'].. " has 'append' key but no rule by that name already exists")
end
else
state.rules_by_name[v['rule']]['condition'] = state.rules_by_name[v['rule']]['condition'] .. " " .. v['condition']
end
else
for j, field in ipairs({'condition', 'output', 'desc', 'priority'}) do
if (v[field] == nil) then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Rule must have property "..field)
end
end
-- Convert the priority-as-string to a priority-as-number now
v['priority_num'] = priorities[v['priority']]
if v['priority_num'] == nil then
error("Invalid priority level: "..v['priority'])
end
if v['priority_num'] <= min_priority then
-- Note that we can overwrite rules, but the rules are still
-- loaded in the order in which they first appeared,
-- potentially across multiple files.
if state.rules_by_name[v['rule']] == nil then
state.ordered_rule_names[#state.ordered_rule_names+1] = {["idx"]=i, ["name"]=v['rule']}
end
-- The output field might be a folded-style, which adds a
-- newline to the end. Remove any trailing newlines.
v['output'] = compiler.trim(v['output'])
state.rules_by_name[v['rule']] = v
else
state.skipped_rules_by_name[v['rule']] = v
end
end
else
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Unknown rule object: "..table.tostring(v))
end
end
-- We've now loaded all the rules, macros, and list. Now
-- compile/expand the rules, macros, and lists. We use
-- ordered_rule_{lists,macros,names} to compile them in the order
-- in which they appeared in the file(s).
reset_rules(rules_mgr)
for i, name in ipairs(state.ordered_list_names) do
local v = state.lists_by_name[name]
-- list items are represented in yaml as a native list, so no
-- parsing necessary
local items = {}
-- List items may be references to other lists, so go through
-- the items and expand any references to the items in the list
for i, item in ipairs(v['items']) do
if (state.lists[item] == nil) then
items[#items+1] = item
else
for i, exp_item in ipairs(state.lists[item].items) do
items[#items+1] = exp_item
end
end
end
state.lists[v['list']] = {["items"] = items, ["used"] = false}
end
for _, obj in ipairs(state.ordered_macro_names) do
local i = obj["idx"]
local name = obj["name"]
local v = state.macros_by_name[name]
local status, ast = compiler.compile_macro(v['condition'], state.macros, state.lists)
if status == false then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), ast)
end
if v['source'] == "syscall" then
if not all_events then
sinsp_rule_utils.check_for_ignored_syscalls_events(ast, 'macro', v['condition'])
end
end
state.macros[v['macro']] = {["ast"] = ast.filter.value, ["used"] = false}
end
for _, obj in ipairs(state.ordered_rule_names) do
local i = obj["idx"]
local name = obj["name"]
local v = state.rules_by_name[name]
warn_evttypes = true
if v['warn_evttypes'] ~= nil then
warn_evttypes = v['warn_evttypes']
end
local status, filter_ast, filters = compiler.compile_filter(v['rule'], v['condition'],
state.macros, state.lists)
if status == false then
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), filter_ast)
end
local evtttypes = {}
local syscallnums = {}
if v['source'] == "syscall" then
if not all_events then
sinsp_rule_utils.check_for_ignored_syscalls_events(filter_ast, 'rule', v['rule'])
end
evttypes, syscallnums = sinsp_rule_utils.get_evttypes_syscalls(name, filter_ast, v['condition'], warn_evttypes, verbose)
end
-- If a filter in the rule doesn't exist, either skip the rule
-- or raise an error, depending on the value of
-- skip-if-unknown-filter.
for filter, _ in pairs(filters) do
found = false
if defined_noarg_filters[filter] ~= nil then
found = true
else
bracket_idx = string.find(filter, "[", 1, true)
if bracket_idx ~= nil then
subfilter = string.sub(filter, 1, bracket_idx-1)
if defined_arg_filters[subfilter] ~= nil then
found = true
end
end
if not found then
dot_idx = string.find(filter, ".", 1, true)
while dot_idx ~= nil do
subfilter = string.sub(filter, 1, dot_idx-1)
if defined_arg_filters[subfilter] ~= nil then
found = true
break
end
dot_idx = string.find(filter, ".", dot_idx+1, true)
end
end
end
if not found then
if v['skip-if-unknown-filter'] then
if verbose then
print("Skipping rule \""..v['rule'].."\" that contains unknown filter "..filter)
end
goto next_rule
else
error("Rule \""..v['rule'].."\" contains unknown filter "..filter)
end
end
end
if (filter_ast.type == "Rule") then
state.n_rules = state.n_rules + 1
state.rules_by_idx[state.n_rules] = v
-- Store the index of this formatter in each relational expression that
-- this rule contains.
-- This index will eventually be stamped in events passing this rule, and
-- we'll use it later to determine which output to display when we get an
-- event.
mark_relational_nodes(filter_ast.filter.value, state.n_rules)
if (v['tags'] == nil) then
v['tags'] = {}
end
if v['source'] == "syscall" then
install_filter(filter_ast.filter.value, filter, sinsp_lua_parser)
-- Pass the filter and event types back up
falco_rules.add_filter(rules_mgr, v['rule'], evttypes, syscallnums, v['tags'])
elseif v['source'] == "k8s_audit" then
install_filter(filter_ast.filter.value, k8s_audit_filter, json_lua_parser)
falco_rules.add_k8s_audit_filter(rules_mgr, v['rule'], v['tags'])
end
-- Rule ASTs are merged together into one big AST, with "OR" between each
-- rule.
if (state.filter_ast == nil) then
state.filter_ast = filter_ast.filter.value
else
state.filter_ast = { type = "BinaryBoolOp", operator = "or", left = state.filter_ast, right = filter_ast.filter.value }
end
-- Enable/disable the rule
if (v['enabled'] == nil) then
v['enabled'] = true
end
if (v['enabled'] == false) then
falco_rules.enable_rule(rules_mgr, v['rule'], 0)
else
falco_rules.enable_rule(rules_mgr, v['rule'], 1)
end
-- If the format string contains %container.info, replace it
-- with extra. Otherwise, add extra onto the end of the format
-- string.
if v['source'] == "syscall" then
if string.find(v['output'], "%container.info", nil, true) ~= nil then
-- There may not be any extra, or we're not supposed
-- to replace it, in which case we use the generic
-- "%container.name (id=%container.id)"
if replace_container_info == false then
v['output'] = string.gsub(v['output'], "%%container.info", "%%container.name (id=%%container.id)")
if extra ~= "" then
v['output'] = v['output'].." "..extra
end
else
safe_extra = string.gsub(extra, "%%", "%%%%")
v['output'] = string.gsub(v['output'], "%%container.info", safe_extra)
end
else
-- Just add the extra to the end
if extra ~= "" then
v['output'] = v['output'].." "..extra
end
end
end
-- Ensure that the output field is properly formatted by
-- creating a formatter from it. Any error will be thrown
-- up to the top level.
formatter = formats.formatter(v['source'], v['output'])
formats.free_formatter(v['source'], formatter)
else
return false, build_error(lines, indices[i], (indices[i+1]-indices[i]), "Unexpected type in load_rule: "..filter_ast.type)
end
::next_rule::
end
if verbose then
-- Print info on any dangling lists or macros that were not used anywhere
for name, macro in pairs(state.macros) do
if macro.used == false then
print("Warning: macro "..name.." not refered to by any rule/macro")
end
end
for name, list in pairs(state.lists) do
if list.used == false then
print("Warning: list "..name.." not refered to by any rule/macro/list")
end
end
end
io.flush()
return true, required_engine_version
end
local rule_fmt = "%-50s %s"
-- http://lua-users.org/wiki/StringRecipes, with simplifications and bugfixes
local function wrap(str, limit, indent)
indent = indent or ""
limit = limit or 72
local here = 1
return str:gsub("(%s+)()(%S+)()",
function(sp, st, word, fi)
if fi-here > limit then
here = st
return "\n"..indent..word
end
end)
end
local function describe_single_rule(name)
if (state.rules_by_name[name] == nil) then
error ("No such rule: "..name)
end
-- Wrap the description into an multiple lines each of length ~ 60
-- chars, with indenting to line up with the first line.
local wrapped = wrap(state.rules_by_name[name]['desc'], 60, string.format(rule_fmt, "", ""))
local line = string.format(rule_fmt, name, wrapped)
print(line)
print()
end
-- If name is nil, describe all rules
function describe_rule(name)
print()
local line = string.format(rule_fmt, "Rule", "Description")
print(line)
line = string.format(rule_fmt, "----", "-----------")
print(line)
if name == nil then
for rulename, rule in pairs(state.rules_by_name) do
describe_single_rule(rulename)
end
else
describe_single_rule(name)
end
end
local rule_output_counts = {total=0, by_priority={}, by_name={}}
function on_event(rule_id)
if state.rules_by_idx[rule_id] == nil then
error ("rule_loader.on_event(): event with invalid rule_id: ", rule_id)
end
rule_output_counts.total = rule_output_counts.total + 1
local rule = state.rules_by_idx[rule_id]
if rule_output_counts.by_priority[rule.priority] == nil then
rule_output_counts.by_priority[rule.priority] = 1
else
rule_output_counts.by_priority[rule.priority] = rule_output_counts.by_priority[rule.priority] + 1
end
if rule_output_counts.by_name[rule.rule] == nil then
rule_output_counts.by_name[rule.rule] = 1
else
rule_output_counts.by_name[rule.rule] = rule_output_counts.by_name[rule.rule] + 1
end
-- Prefix output with '*' so formatting is permissive
output = "*"..rule.output
return rule.rule, rule.priority_num, output
end
function print_stats()
print("Events detected: "..rule_output_counts.total)
print("Rule counts by severity:")
for priority, count in pairs(rule_output_counts.by_priority) do
print (" "..priority..": "..count)
end
print("Triggered rules by rule name:")
for name, count in pairs(rule_output_counts.by_name) do
print (" "..name..": "..count)
end
end
|
local path = require "nvim-lsp-installer.path"
local shell = require "nvim-lsp-installer.installers.shell"
local M = {}
local REL_INSTALL_DIR = "venv"
function M.packages(packages)
return shell.raw(("./%s/bin/pip3 install -U %s"):format(REL_INSTALL_DIR, table.concat(packages, " ")), {
prefix = ("set -euo pipefail; python3 -m venv %q;"):format(REL_INSTALL_DIR),
})
end
function M.executable(root_dir, executable)
return path.concat { root_dir, REL_INSTALL_DIR, "bin", executable }
end
return M
|
-- random
space = box.schema.space.create('test', { engine = 'sophia'})
index = space:create_index('primary', { type = 'tree', parts = {1, 'num'} })
dofile('index_random_test.lua')
index_random_test(space, 'primary')
space:drop()
sophia_schedule()
|
-- @brief ...
local DelayLoader = ae.oo.class()
-- @brief Creates a DelayLoader object.
-- @param resourceLoader The resource loader.
-- @return A new DelayLoader object.
function DelayLoader.new(resourceLoader)
local self = ae.oo.new(DelayLoader)
DelayLoader.construct(self,resourceLoader)
return self
end
-- @brief Constructs a DelayLoader object.
-- @param self The object.
-- @param resourceLoader The resource loader.
function DelayLoader.construct(self,resourceLoader)
self.resourceLoader = resourceLoader
end
-- @brief Loads a delay resource.
-- @param millis The amount of time to delay in milliseconds.
function DelayLoader:load(millis)
local id = ae.loader.DelayResource.getNextId()
-- create and add the resource
local delayResource = ae.loader.DelayResource.new(id,millis)
self.resourceLoader:add(delayResource)
return delayResource
end
return DelayLoader |
workspace "WindowsSupervisionSuite"
configurations { "Debug", "Release" }
platforms { "x64" }
language "C++"
location "build"
characterset "MBCS"
flags { "NoPCH", "FatalWarnings", "NoIncrementalLink" }
defines {
"VC_EXTRALEAN",
"WINS32_LEAN_AND_MEAN",
'PROJECT_NAME="$(ProjectName)"',
'YEAR=' .. os.date("%Y")
}
filter "configurations:Debug"
symbols "On"
symbolspath "$(OutDir)$(TargetName).pdb"
filter "configurations:Release"
optimize "On"
filter {}
build_version = os.getenv("BUILD_VERSION")
if not build_version then
build_version = "1.0.0.0"
end
parts = string.explode(build_version, '[.-]+')
if (table.getn(parts) >= 1) then
defines("VERSION_MAJOR=" .. tonumber(parts[1]) .. "")
end
if (table.getn(parts) >= 2) then
defines("VERSION_MINOR=" .. tonumber(parts[2]) .. "")
end
if (table.getn(parts) >= 3) then
defines("VERSION_REVISION=" .. tonumber(parts[3]) .. "")
end
if (table.getn(parts) >= 4) then
defines("VERSION_BUILD=" .. tonumber(parts[4]) .. "")
end
git_commit = os.getenv("GIT_COMMIT")
if git_commit then
defines("GIT_COMMIT=\"" .. git_commit .. "\"")
defines("GIT_COMMIT_SHORT=\"" .. string.sub(git_commit, 1, 7) .. "\"")
end
project "winss"
kind "StaticLib"
includedirs { "lib" }
files { "lib/**.hpp", "lib/**.cpp" }
project "winss-supervise"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-supervise.cpp", "bin/resource/*" }
project "winss-svc"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-svc.cpp", "bin/resource/*" }
project "winss-svok"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-svok.cpp", "bin/resource/*" }
project "winss-svwait"
kind "ConsoleApp"
links { "winss" }
linkoptions { "setargv.obj" }
includedirs { "lib" }
files { "bin/winss-svwait.cpp", "bin/resource/*" }
project "winss-svstat"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-svstat.cpp", "bin/resource/*" }
project "winss-svscan"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-svscan.cpp", "bin/resource/*" }
project "winss-svscanctl"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-svscanctl.cpp", "bin/resource/*" }
project "winss-log"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
files { "bin/winss-log.cpp", "bin/resource/*" }
project "winss-test"
kind "ConsoleApp"
links { "winss" }
includedirs { "lib" }
nuget { "gmock:1.7.0" }
files { "test/**", "bin/resource/*" }
buildoptions { "/bigobj" }
linkoptions { "/OPT:NOREF", "/OPT:NOICF", "/INCREMENTAL:NO" }
|
local Assert = require(script.Parent._Util.Assert)
local assertTypeOf = Assert.prepTypeOf("GetPerceivedBrightness")
return function(colour: Color3): number
assertTypeOf("colour", "Color3", colour)
local red = colour.R * 255
local green = colour.G * 255
local blue = colour.B * 255
local bright = ((red * 299 + green * 587 + blue * 114) / 1000) / 255
return bright
end
|
local ffi = require 'ffi'
local find = {}
find.__index = find
-- default is to get verbose on errors
find.verbose=false
find.verboseError=true
find.verboseFallback=true
-- constants to index array tables below
local Fwd, BwdFilter, BwdData = 1, 2, 3
-- constants to select algo family, to index algoFamilies
local GetFamily, FindFamily, FindExFamily = 1,2,3
local warmupIterations = 0
local Meg = 1024*1024
-- cudnnGetxxx APIs: default, when cudnn.benchmark == false
local getAlgos = {'cudnnGetConvolutionForwardAlgorithm',
'cudnnGetConvolutionBackwardFilterAlgorithm',
'cudnnGetConvolutionBackwardDataAlgorithm'}
local getWSAlgos = {'cudnnGetConvolutionForwardWorkspaceSize',
'cudnnGetConvolutionBackwardFilterWorkspaceSize',
'cudnnGetConvolutionBackwardDataWorkspaceSize'}
-- cudnnFindxxx APIs: default, when cudnn.benchmark == true
local findAlgos = {'cudnnFindConvolutionForwardAlgorithm',
'cudnnFindConvolutionBackwardFilterAlgorithm',
'cudnnFindConvolutionBackwardDataAlgorithm'}
-- cudnnFindxxxEx APIs: default, when cudnn.benchmark == true and cudnn.useFindEx == true
local findExAlgos = {'cudnnFindConvolutionForwardAlgorithmEx',
'cudnnFindConvolutionBackwardFilterAlgorithmEx',
'cudnnFindConvolutionBackwardDataAlgorithmEx'}
local algoFamilies = { getAlgos, findAlgos, findExAlgos}
local fwdAlgoNames = {
"IMPLICIT_GEMM",
"IMPLICIT_PRECOMP_GEMM",
"GEMM",
"DIRECT",
"FFT",
"FFT_TILING",
"WINOGRAD",
"WINOGRAD_NONFUSED"
}
local bwdFilterAlgoNames = {
"ALGO_0",
"ALGO_1",
"FFT",
"ALGO_3",
"WINOGRAD",
"WINOGRAD_NONFUSED"
}
local bwdDataAlgoNames = {
"ALGO_0",
"ALGO_1",
"FFT",
"FFT_TILING",
"WINOGRAD",
"WINOGRAD_NONFUSED"
}
local algoNames = {fwdAlgoNames, bwdFilterAlgoNames, bwdDataAlgoNames}
local function convDataString(layer)
local info = ''
if layer.convDescData then
local desc = layer.convDescData
info = ' convDesc=[mode : ' .. desc.mode .. ' datatype : ' .. desc.dataType .. ']'
end
return info .. ' hash=' .. layer.autotunerHash
end
local function verboseCall(layer, f, ...)
local status = cudnn.call(f, ...)
if (status ~= ffi.C.CUDNN_STATUS_SUCCESS) and (find.verbose or find.verboseError) then
print("\n" .. f .. " failed: ", tonumber(status), convDataString(layer))
end
return status
end
find.verboseCall = verboseCall
local function checkedCall(layer, f, ...)
local status = verboseCall(layer, f, ...)
if status ~= ffi.C.CUDNN_STATUS_SUCCESS then
local str = ffi.string(cudnn.C.cudnnGetErrorString(status))
error('Error in CuDNN: ' .. str .. ' ('..f..')')
end
return status
end
find.checkedCall = checkedCall
local function noFallback(layer)
if find.verbose or find.verboseFallback then
print("\nfind.defaultFallback: verboseCall failed for: ", convDataString(layer))
end
return false
end
local function fallbackWarning(layer, msg)
if find.verbose or find.verboseFallback then
print("\n *** find.verboseFallback: " .. msg ..
"\n *** Falling back to 32-bit math for: " .. convDataString(layer))
print(" *** [ Set cudnn.find.verboseFallback to false to disable this message ] *** ")
print(" *** [ Alternatively, you may force CUDNN to always operate on CudaHalfTensors via 32-bit float conversion, in Lua: ] ***\n"
.." *** cudnn.configureMath({ ['torch.CudaHalfTensor'] = 'CUDNN_DATA_FLOAT'} ) ***")
print(" *** [ Note: result may be faster or slower than native FP16, depending on your GPU and CUDNN operations ] *** ")
end
end
local function defaultFallback(layer, replay)
-- read conv descriptor
local convDescData = layer.convDescData
if convDescData and convDescData.dataType == "CUDNN_DATA_HALF" then
fallbackWarning(layer, replay
and "16->32 bit fallback replay "
or "No native FP16 algo found, will try 32-bit math")
-- update our record with fallback value
convDescData.dataType = "CUDNN_DATA_FLOAT"
-- update the descriptor in CUDNN
cudnn.setConvolutionDescriptor(convDescData, layer.convDesc)
return true
else
return false
end
end
-- Find State and Cache (per device)
local function initState(id)
local finder = {}
setmetatable(finder,find)
finder.id = id
finder:resetAlgorithmCache()
finder.iteration = 0
if cutorch.hasHalf then
finder.fallback = defaultFallback
end
return finder
end
local finders = nil
-- this resets algorithm cache for device
local function setAlgoFamily()
return cudnn.benchmark
and (cudnn.useFindEx and FindExFamily or FindFamily)
or GetFamily
end
function find:resetAlgorithmCache()
self.calculatedWorkspaceSize = {}
self:calculateMaxWorkspaceSize()
self.algoFamily = setAlgoFamily()
self.autotunerCache = {{}, {}, {}}
end
function find.reset(warmup)
cutorch:synchronizeAll()
finders = {}
warmupIterations = warmup or 0
end
function find.get()
local device = cutorch.getDevice()
local it = finders[device]
if not it then
it = initState(device)
finders[device] = it
end
return it
end
function find:lookup(layer, findAPI_idx)
return self.autotunerCache[findAPI_idx][layer.autotunerHash]
end
-- record algo, memory in cache
function find:store(layer, findAPI_idx, cachedAlgo)
if warmupIterations==0 then
self.autotunerCache[findAPI_idx][layer.autotunerHash] = cachedAlgo
end
end
function find:calculateMaxWorkspaceSize(reserve, fraction)
if not reserve or reserve < cudnn.reservedGPUBytes then reserve = cudnn.reservedGPUBytes end
local max_fraction = cudnn.maxWorkspaceGPUMemPercent/100
if not fraction or fraction > max_fraction then fraction = max_fraction end
local buf, curSize = cudnn.getSharedWorkspace()
-- check current usage
local freeMemory, totalMemory = cutorch.getMemoryUsage(self.id)
local newSize= (freeMemory+curSize-reserve) * fraction
self.maxWorkspaceSize = newSize
if find.verbose then
print("calculateMaxWorkspaceSize Memory: ", freeMemory/Meg, "M free, " , totalMemory/Meg, "M total, " , self.maxWorkspaceSize/Meg, "M Workspace" )
end
end
function find:setCalculatedWorkspaceSize(greater)
local device = cutorch.getDevice()
for stream,bytes in pairs (self.calculatedWorkspaceSize) do
cudnn.setSharedWorkspaceSize(bytes, greater, device, stream)
end
end
function find:pickAlgoAndCalculateWorkspaceSize(cachedAlgo)
local stream = cutorch.getStream()
if not self.calculatedWorkspaceSize[stream] then
self.calculatedWorkspaceSize[stream] = 0
end
if self.calculatedWorkspaceSize[stream] > self.maxWorkspaceSize then
self.calculatedWorkspaceSize[stream] = self.maxWorkspaceSize
end
-- find algo with a size that keeps the sum of stream sizes within ws size
for a=1,#cachedAlgo do
local algoSize = cachedAlgo[a].memory
local delta = algoSize - self.calculatedWorkspaceSize[stream]
if delta > 0 then
-- check if we still fit
local totalWS = 0
for s,sz in pairs(self.calculatedWorkspaceSize) do
totalWS = totalWS + sz
end
if totalWS + delta < self.maxWorkspaceSize then
self.calculatedWorkspaceSize[stream] = algoSize
return a
end
else
-- keep previously calculated WS size for the stream
return a
end -- delta
end
return 0
end
function find:reserveBytes(layer)
local reserve = cudnn.reservedGPUBytes
-- todo: implement layer method returning memory allocation size
reserve = reserve + 2*layer.weight:nElement()*layer.weight:elementSize()
return reserve
end
function find:verifyReserveForWeights(layer)
local freeMemory, totalMemory = cutorch.getMemoryUsage(self.id)
local reserve = self:reserveBytes(layer)
if freeMemory < reserve then
-- let's make sure we still have space to reallocate our data
cudnn.adjustSharedWorkspaceSize(freeMemory - reserve)
end
end
function find:checkIteration(layer, findAPI_idx)
if warmupIterations == 0 then return end
if not layer.iteration then layer.iteration = {0,0,0} end
-- find last iteration
local max_iter = 0
for k,v in pairs(layer.iteration) do
if v > max_iter then max_iter = v end
end
if (self.iteration < max_iter and max_iter > 1) then
self.iteration = max_iter
if find.verbose then print ("CUDNN Find SM: iteration #", self.iteration) end
if warmupIterations > 0 then warmupIterations = warmupIterations -1 end
end
layer.iteration[findAPI_idx] = layer.iteration[findAPI_idx] + 1
end
local cachedAlgo
local nAlgos = 10
-- pre-allocated parameters for the APIs: Fwd, Bwd and BwdD use all different enums
local perfResultsArray = { ffi.new('cudnnConvolutionFwdAlgoPerf_t[?]', nAlgos),
ffi.new('cudnnConvolutionBwdFilterAlgoPerf_t[?]', nAlgos),
ffi.new('cudnnConvolutionBwdDataAlgoPerf_t[?]', nAlgos) }
local numPerfResults = ffi.new('int[1]')
local algType = { ffi.new('cudnnConvolutionFwdAlgo_t[?]', 1),
ffi.new('cudnnConvolutionBwdFilterAlgo_t[?]', 1),
ffi.new('cudnnConvolutionBwdDataAlgo_t[?]', 1)}
function find:setupAlgo(layer, findAPI_idx, algSearchMode, params)
local retAlgo
local cacheHit = '[found in cache]'
local useFallback = false
-- Check if it's a new iteration, decrement warmup
self:checkIteration(layer, findAPI_idx)
local curWorkspace, curWorkspaceSize = cudnn.getSharedWorkspace()
local validResults = 0
local API = algoFamilies[self.algoFamily][findAPI_idx]
local perfResults = perfResultsArray[findAPI_idx]
-- try to find algo in the cache first
cachedAlgo = self:lookup(layer, findAPI_idx)
if cachedAlgo then
validResults = #cachedAlgo
useFallback = cachedAlgo[1].fallback
-- need to replay fallback on cache hit
if useFallback then self.fallback(layer, true) end
else
cacheHit = ''
cachedAlgo = {}
--algo family might have changed, reset it
self.algoFamily = setAlgoFamily()
local API = algoFamilies[self.algoFamily][findAPI_idx]
if self.algoFamily == FindExFamily then
-- clone output tensor
local paramstmp = params[7]
params[7] = paramstmp:clone()
-- temporarily set WS size to the max
self:calculateMaxWorkspaceSize()
cudnn.setSharedWorkspaceSize(self.maxWorkspaceSize)
else
if self.algoFamily == FindFamily then
-- Find() APIs use free GPU memory to find algo, release our WS bytes
cudnn.setSharedWorkspaceSize(0)
end
end
local function callCudnn(layer)
local ret = 0
validResults = 0
if not layer.convDesc or not layer.convDesc[0] then
error("No convDesc set on layer!")
end
if self.algoFamily == FindExFamily then
-- query temp workspace size
local tempWorkspace, tempWorkspaceSize = cudnn.getSharedWorkspace()
ret = verboseCall(layer, API,
cudnn.getHandle(),
params[1], params[2]:data(), params[3], params[4]:data(), layer.convDesc[0], params[6], params[7]:data(),
nAlgos, numPerfResults, perfResults, tempWorkspace, tempWorkspaceSize)
params[7]=paramstmp
else
if self.algoFamily == FindFamily then
ret = verboseCall(layer, API,
cudnn.getHandle(),
params[1], params[3], layer.convDesc[0], params[6],
nAlgos, numPerfResults, perfResults)
else
-- GetFamily: emulate findXXX results layout
numPerfResults[0]=1
perfResults[0].algo = 0
perfResults[0].memory = 0
perfResults[0].status = 1
local algWorkspaceLimit = layer.workspace_limit
or (layer.nInputPlane * layer.kH * layer.kW * layer.weight.elementSize())
ret = cudnn.call(API,
cudnn.getHandle(),
params[1], params[3], layer.convDesc[0], params[6],
algSearchMode, algWorkspaceLimit, algType[findAPI_idx])
if ret ~= 0 then
return ret
end
local retAlgo = algType[findAPI_idx][0]
if find.verbose then
print(string.format(
"\n" .. API .. ": %d (ws limit: %d) mode = %s",
tonumber(retAlgo),
algWorkspaceLimit,
algSearchMode))
end
local bufSizeptr = ffi.new("size_t[1]")
ret = cudnn.call(getWSAlgos[findAPI_idx],
cudnn.getHandle(),
params[1], params[3], layer.convDesc[0], params[6],
retAlgo, bufSizeptr)
local bufSize = tonumber(bufSizeptr[0])
if ret ~= 0 then
return ret
end
if find.verbose then
print(string.format(
"\n" .. getWSAlgos[findAPI_idx] .. ": bufSize: %d, current ws: %d",
bufSize, tonumber(curWorkspaceSize)))
end
perfResults[0].algo = retAlgo
perfResults[0].memory = bufSize
perfResults[0].status = ret
end
end
if find.verbose then
print("\ncallCudnn: ", API, "returned ", numPerfResults[0], " results , status = " , ret, "status[0] = " , perfResults[0].status, "\n")
end
if ret ~= 0 then
return ret
end
for r=0,numPerfResults[0]-1 do
local res = perfResults[r]
if res.status == 0 then
validResults = validResults+1
cachedAlgo[validResults] = { algo = tonumber(res.algo),
memory = tonumber(res.memory),
time = tonumber(res.time),
status = tonumber(res.status),
fallback = useFallback}
if find.verbose then
local fallback = ''
if (useFallback) then fallback = "[FALLBACK]" end
print(string.format(
"\n" .. API .. " algo[%d]: %s (%d, status: %d), time: %.04f, memory: %8d, count: %d"
.. " %s " .. cacheHit .. fallback,
validResults,
algoNames[findAPI_idx][cachedAlgo[validResults].algo+1], cachedAlgo[validResults].algo, cachedAlgo[validResults].status,
cachedAlgo[validResults].time, cachedAlgo[validResults].memory, r, convDataString(layer)))
end
end
end
if validResults < 1 then
return 1
end
return 0
end
local function performanceFallback(layer)
-- read conv descriptor
local convDescData = layer.convDescData
if convDescData and convDescData.dataType == "CUDNN_DATA_HALF" then
local savedResults = cachedAlgo
local savedNum = validResults
cachedAlgo = {}
validResults = 0
useFallback = true
-- update our record with fallback value
layer.convDescData.dataType = "CUDNN_DATA_FLOAT"
-- update the descriptor in CUDNN
cudnn.setConvolutionDescriptor(layer.convDescData, layer.convDesc)
-- do the actual call
local status = callCudnn(layer)
-- check if we got better results with float32
if status == 0 and validResults > 0 and cachedAlgo[1].time < savedResults[1].time then
if find.verbose or find.verboseFallback then
local msg = string.format("find.performanceFallback: found 32-bit float op is faster (%f) than FP16(%f), memory increase: %fM",
cachedAlgo[1].time, savedResults[1].time,
(tonumber(cachedAlgo[1].memory)-tonumber(savedResults[1].memory))/Meg)
fallbackWarning(layer, msg)
end
return
end
-- restore if we didn't
cachedAlgo = savedResults
validResults = savedNum
-- update our record with fallback value
layer.convDescData.dataType = "CUDNN_DATA_HALF"
-- update the descriptor in CUDNN
cudnn.setConvolutionDescriptor(layer.convDescData, layer.convDesc)
end
end
-- do the actual call
local status = callCudnn(layer)
if status ~= 0 or validResults < 1 then
if self.fallback and self.fallback(layer) then
useFallback = true
status = callCudnn(layer)
end
-- check again
if status ~= 0 or validResults < 1 then
error (API .. ' failed, sizes: ' .. convDataString(layer))
end
else
-- if we are running Find or FindEx in native fp16, check if this algo is actiually faster in pseudo
if self.algoFamily ~= GetFamily then
performanceFallback(layer)
end
end
self:store(layer, findAPI_idx, cachedAlgo)
-- restore WS size if we fiddled with it
if self.algoFamily ~= GetFamily then
cudnn.setSharedWorkspaceSize(curWorkspaceSize)
end
end
-- this may return different algo if size does not fit
retAlgo = self:pickAlgoAndCalculateWorkspaceSize(cachedAlgo)
if retAlgo > 0 then
self:setCalculatedWorkspaceSize(true)
else
-- TODO: fallback to recalculate
error("No algorithms found that would fit in free GPU memory")
return -1
end
if cudnn.verbose or find.verbose then
local freeMemory, totalMemory = cutorch.getMemoryUsage(self.id)
local fallback = ""
if (useFallback) then fallback = "[FALLBACK]" end
print(string.format(
"\n" .. API .. ": %s(%d)[%d of %d] Workspace: %8fM (current ws size %fM, max: %dM free: %dM) %s" .. cacheHit .. fallback,
algoNames[findAPI_idx][cachedAlgo[retAlgo].algo+1], cachedAlgo[retAlgo].algo, retAlgo, #cachedAlgo,
tonumber(cachedAlgo[retAlgo].memory)/Meg, curWorkspaceSize/Meg, self.maxWorkspaceSize/Meg, freeMemory/Meg, convDataString(layer)))
end
return cachedAlgo[retAlgo].algo
end
function find:prepare(layer, input_slice, output_slice)
local function shape(x)
return table.concat(x:size():totable(),',')
end
local function vals(x)
return table.concat(x,',')
end
layer.autotunerHash =
'-dimA' .. shape(input_slice)
..' -filtA' .. shape(layer.weight)
..' ' .. shape(output_slice)
..' -padA' .. vals(layer.pad)
..' -convStrideA' .. vals(layer.stride)
.. ' ' .. cudnn.configmap(torch.type(layer.weight))
layer.iteration = nil
layer.input_slice = input_slice
layer.output_slice = output_slice
end
local function setupWS(layer, params, algo, fn)
local bufSizeptr = ffi.new("size_t[1]")
cudnn.errcheck(getWSAlgos[fn],
cudnn.getHandle(),
params[1], params[3], layer.convDesc[0], params[6],
algo, bufSizeptr)
local bufSize = tonumber(bufSizeptr[0])
cudnn.setSharedWorkspaceSize(bufSize, true)
end
function find:forwardAlgorithm(layer, params)
if layer.fmode then
setupWS(layer, params, layer.fmode, Fwd)
return layer.fmode
end
local algSearchMode = 'CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT'
if layer.fastest_mode or cudnn.fastest == true then
algSearchMode = 'CUDNN_CONVOLUTION_FWD_PREFER_FASTEST'
end
return self:setupAlgo(layer, Fwd, algSearchMode, params)
end
function find:backwardFilterAlgorithm(layer, params)
-- Check if we are in "sticky" mode
if layer.bwmode then
setupWS(layer, params, layer.bwmode, BwdFilter)
return layer.bwmode
end
local algSearchMode = 'CUDNN_CONVOLUTION_BWD_FILTER_NO_WORKSPACE'
if layer.fastest_mode or cudnn.fastest == true then
algSearchMode = 'CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST'
end
local ret = self:setupAlgo(layer, BwdFilter, algSearchMode, params)
return ret
end
function find:backwardDataAlgorithm(layer, params)
-- Check if we are in "sticky" mode
if layer.bdmode then
setupWS(layer, params, layer.bdmode, BwdData)
return layer.bdmode
end
local algSearchMode = 'CUDNN_CONVOLUTION_BWD_DATA_NO_WORKSPACE'
if layer.fastest_mode or cudnn.fastest == true then
algSearchMode = 'CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST'
end
return self:setupAlgo(layer, BwdData, algSearchMode, params)
end
find.reset()
return find
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('Cargo', {
SortKey = 2001000,
description = T{4477, --[[Cargo RCRover description]] "Remote-controlled vehicle that transports, commands and repairs Drones."},
group = "Rovers",
icon = "UI/Icons/Payload/RCRover.tga",
id = "RCRover",
kg = 10000,
name = T{7678, --[[Cargo RCRover name]] "RC Rover"},
price = 300000000,
})
PlaceObj('Cargo', {
SortKey = 2002000,
description = T{4455, --[[Cargo ExplorerRover description]] "A remote-controlled exploration vehicle that can analyze Anomalies."},
group = "Rovers",
icon = "UI/Icons/Payload/RCExplorer.tga",
id = "ExplorerRover",
kg = 10000,
name = T{1684, --[[Cargo ExplorerRover name]] "RC Explorer"},
price = 400000000,
})
PlaceObj('Cargo', {
SortKey = 2003000,
description = T{4461, --[[Cargo RCTransport description]] "Remote-controlled vehicle that transports resources. Use it to establish permanent supply routes or to gather resources from surface deposits."},
group = "Rovers",
icon = "UI/Icons/Payload/RCTransport.tga",
id = "RCTransport",
kg = 10000,
name = T{1683, --[[Cargo RCTransport name]] "RC Transport"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 2009000,
description = T{4390, --[[Cargo Drone description]] "An automated unit controlled by a Drone Hub, Rocket or RC Rover. Gathers resources, constructs buildings and performs maintenance."},
group = "Rovers",
icon = "UI/Icons/Payload/Drone.tga",
id = "Drone",
name = T{1681, --[[Cargo Drone name]] "Drone"},
price = 30000000,
})
PlaceObj('Cargo', {
SortKey = 3001000,
description = T{7909, --[[Cargo Concrete description]] "Basic construction material often used to construct and maintain Domes and Dome buildings."},
group = "Basic Resources",
id = "Concrete",
kg = 5000,
name = T{3513, --[[Cargo Concrete name]] "Concrete"},
pack = 5,
price = 30000000,
})
PlaceObj('Cargo', {
SortKey = 3002000,
description = T{7910, --[[Cargo Metals description]] "Basic construction materials often used to construct and maintain outside buildings. Required for the creation of Machine Parts."},
group = "Basic Resources",
id = "Metals",
kg = 5000,
name = T{3514, --[[Cargo Metals name]] "Metals"},
pack = 5,
price = 50000000,
})
PlaceObj('Cargo', {
SortKey = 3003000,
description = T{7914, --[[Cargo Food description]] "Colonists arrive with nominal Food supply, but will soon need additional provisions to survive."},
group = "Basic Resources",
id = "Food",
kg = 2000,
name = T{1022, --[[Cargo Food name]] "Food"},
pack = 5,
price = 20000000,
})
PlaceObj('Cargo', {
SortKey = 4001000,
description = T{7911, --[[Cargo Polymers description]] "Advanced materials often used to construct and maintain Power accumulators, advanced Power generators, Domes and Spires."},
group = "Advanced Resources",
id = "Polymers",
kg = 2000,
name = T{3515, --[[Cargo Polymers name]] "Polymers"},
pack = 5,
price = 70000000,
})
PlaceObj('Cargo', {
SortKey = 4002000,
description = T{7913, --[[Cargo MachineParts description]] "Advanced materials often used to construct and maintain Extractors and Factories."},
group = "Advanced Resources",
id = "MachineParts",
kg = 2000,
name = T{3516, --[[Cargo MachineParts name]] "Machine Parts"},
pack = 5,
price = 90000000,
})
PlaceObj('Cargo', {
SortKey = 4003000,
description = T{7912, --[[Cargo Electronics description]] "Advanced materials often used to construct and maintain scientific and infrastructure buildings."},
group = "Advanced Resources",
id = "Electronics",
kg = 2000,
name = T{3517, --[[Cargo Electronics name]] "Electronics"},
pack = 5,
})
PlaceObj('Cargo', {
SortKey = 5001000,
description = T{3679, --[[Cargo OrbitalProbe description]] "Reveals underground deposits in the scanned area."},
group = "Probe",
id = "OrbitalProbe",
name = T{3525, --[[Cargo OrbitalProbe name]] "Orbital Probe"},
})
PlaceObj('Cargo', {
SortKey = 10001000,
description = T{5049, --[[Cargo DroneHub description]] "Controls Drones and allocates them to different tasks."},
group = "Prefabs",
icon = "UI/Icons/Payload/DroneHub.tga",
id = "DroneHub",
kg = 5000,
name = T{3518, --[[Cargo DroneHub name]] "Drone Hub"},
price = 150000000,
})
PlaceObj('Cargo', {
SortKey = 10002000,
description = T{5174, --[[Cargo MoistureVaporator description]] "Produces Water from the atmosphere. Production lowered when placed near other Vaporators. No production during Dust Storms."},
group = "Prefabs",
icon = "UI/Icons/Payload/MoistureVaporator.tga",
id = "MoistureVaporator",
kg = 5000,
name = T{3519, --[[Cargo MoistureVaporator name]] "Moisture Vaporator"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 10003000,
description = T{5076, --[[Cargo FuelFactory description]] "Produces Fuel from Water."},
group = "Prefabs",
icon = "UI/Icons/Payload/FuelFactory.tga",
id = "FuelFactory",
kg = 5000,
name = T{5074, --[[Cargo FuelFactory name]] "Fuel Refinery"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 10004000,
description = T{5289, --[[Cargo StirlingGenerator description]] "Generates Power. While closed the generator is protected from dust, but produces less power."},
group = "Prefabs",
icon = "UI/Icons/Payload/StirlingGenerator.tga",
id = "StirlingGenerator",
kg = 2000,
name = T{3521, --[[Cargo StirlingGenerator name]] "Stirling Generator"},
price = 400000000,
})
PlaceObj('Cargo', {
SortKey = 10005000,
description = T{5132, --[[Cargo MachinePartsFactory description]] "Produces Machine Parts from Metals."},
group = "Prefabs",
icon = "UI/Icons/Payload/MachinePartsFactory.tga",
id = "MachinePartsFactory",
kg = 10000,
name = T{3522, --[[Cargo MachinePartsFactory name]] "Machine Parts Factory"},
price = 400000000,
})
PlaceObj('Cargo', {
SortKey = 10005500,
description = T{5200, --[[Cargo PolymerPlant description]] "Produces Polymers from Water and Fuel."},
group = "Prefabs",
icon = "UI/Icons/Payload/PolymerPlant.tga",
id = "PolymerPlant",
kg = 10000,
name = T{3524, --[[Cargo PolymerPlant name]] "Polymer Factory"},
price = 300000000,
})
PlaceObj('Cargo', {
SortKey = 10006000,
description = T{5060, --[[Cargo ElectronicsFactory description]] "Creates Electronics from Rare Metals."},
group = "Prefabs",
icon = "UI/Icons/Payload/ElectronicsFactory.tga",
id = "ElectronicsFactory",
kg = 10000,
name = T{3523, --[[Cargo ElectronicsFactory name]] "Electronics Factory"},
price = 600000000,
})
PlaceObj('Cargo', {
SortKey = 14000000,
description = T{5261, --[[Cargo ShuttleHub description]] "Houses and refuels Shuttles that facilitate long-range resource transportation between Depots and resettling of Colonists between Domes."},
group = "Locked",
id = "ShuttleHub",
kg = 10000,
locked = true,
name = T{3526, --[[Cargo ShuttleHub name]] "Shuttle Hub"},
price = 1000000000,
})
PlaceObj('Cargo', {
SortKey = 14001000,
description = T{5160, --[[Cargo MetalsExtractor description]] "Extracts Metals from underground deposits. All extractors contaminate nearby buildings with dust."},
group = "Locked",
id = "MetalsExtractor",
kg = 5000,
locked = true,
name = T{3527, --[[Cargo MetalsExtractor name]] "Metals Extractor"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 14002000,
description = T{5034, --[[Cargo RegolithExtractor description]] "Extracts sulfurous rich regolith from Concrete deposits and produces Concrete. All extractors contaminate nearby buildings with dust."},
group = "Locked",
id = "RegolithExtractor",
kg = 5000,
locked = true,
name = T{5032, --[[Cargo RegolithExtractor name]] "Concrete Extractor"},
price = 150000000,
})
PlaceObj('Cargo', {
SortKey = 14003000,
description = T{5307, --[[Cargo WaterExtractor description]] "Extracts Water from underground deposits. All extractors contaminate nearby buildings with dust."},
group = "Locked",
id = "WaterExtractor",
kg = 5000,
locked = true,
name = T{3529, --[[Cargo WaterExtractor name]] "Water Extractor"},
price = 150000000,
})
PlaceObj('Cargo', {
SortKey = 14004000,
description = T{5224, --[[Cargo PreciousMetalsExtractor description]] "Extracts Rare Metals from underground deposits. All extractors contaminate nearby buildings with dust."},
group = "Locked",
id = "PreciousMetalsExtractor",
kg = 5000,
locked = true,
name = T{3530, --[[Cargo PreciousMetalsExtractor name]] "Rare Metals Extractor"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 15001000,
description = T{5007, --[[Cargo Apartments description]] "Provides living space for Colonists. Cramped quarters grant less Comfort during rest."},
group = "Locked",
id = "Apartments",
kg = 10000,
locked = true,
name = T{3531, --[[Cargo Apartments name]] "Apartments"},
price = 200000000,
})
PlaceObj('Cargo', {
SortKey = 15002000,
description = T{5122, --[[Cargo LivingQuarters description]] "Provides living space. Resting residents recover Comfort faster compared to other Residences."},
group = "Locked",
id = "LivingQuarters",
kg = 10000,
locked = true,
name = T{3532, --[[Cargo LivingQuarters name]] "Living Quarters"},
})
PlaceObj('Cargo', {
SortKey = 15003000,
description = T{5273, --[[Cargo SmartHome description]] "Provide a very comfortable living space for Colonists. Residents will recover additional Sanity when resting."},
group = "Locked",
id = "SmartHome",
kg = 10000,
locked = true,
name = T{7800, --[[Cargo SmartHome name]] "Smart Complex"},
price = 300000000,
})
PlaceObj('Cargo', {
SortKey = 16001000,
description = T{5009, --[[Cargo Arcology description]] "Provides living space for numerous Colonists, granting high Comfort."},
group = "Locked",
id = "Arcology",
kg = 20000,
locked = true,
name = T{3534, --[[Cargo Arcology name]] "Arcology"},
price = 700000000,
})
PlaceObj('Cargo', {
SortKey = 16002000,
description = T{5099, --[[Cargo HangingGardens description]] "A beautiful park complex. Increases the Comfort of all Residences in the Dome."},
group = "Locked",
id = "HangingGardens",
kg = 20000,
locked = true,
name = T{3535, --[[Cargo HangingGardens name]] "Hanging Gardens"},
price = 400000000,
})
PlaceObj('Cargo', {
SortKey = 16003000,
description = T{5309, --[[Cargo WaterReclamationSystem description]] "Recycles up to 70% of the Water used in the Dome."},
group = "Locked",
id = "WaterReclamationSystem",
kg = 20000,
locked = true,
name = T{3536, --[[Cargo WaterReclamationSystem name]] "Water Reclamation System"},
price = 500000000,
})
PlaceObj('Cargo', {
SortKey = 16004000,
description = T{5025, --[[Cargo CloningVats description]] "Creates Clones over time. Cloned Colonists grow and age twice as fast."},
group = "Locked",
id = "CloningVats",
kg = 20000,
locked = true,
name = T{3537, --[[Cargo CloningVats name]] "Cloning Vats"},
price = 700000000,
})
PlaceObj('Cargo', {
SortKey = 16005000,
description = T{5178, --[[Cargo NetworkNode description]] "Increases the overall Research output of the Dome."},
group = "Locked",
id = "NetworkNode",
kg = 20000,
locked = true,
name = T{3538, --[[Cargo NetworkNode name]] "Network Node"},
price = 600000000,
})
PlaceObj('Cargo', {
SortKey = 16006000,
description = T{5143, --[[Cargo MedicalCenter description]] "Visitors will recover Health and Sanity as long as they are not starving, dehydrated, freezing or suffocating. Larger capacity and more effective than the Infirmary. A Dome with a Medical Building has lower minimum Comfort requirement for births."},
group = "Locked",
id = "MedicalCenter",
kg = 20000,
locked = true,
name = T{3539, --[[Cargo MedicalCenter name]] "Medical Center"},
price = 500000000,
})
PlaceObj('Cargo', {
SortKey = 16007000,
description = T{5246, --[[Cargo Sanatorium description]] "Treats Colonists for flaws through advanced and (mostly humane) medical practices."},
group = "Locked",
id = "Sanatorium",
kg = 20000,
locked = true,
name = T{3540, --[[Cargo Sanatorium name]] "Sanatorium"},
price = 600000000,
})
|
require("prototypes.entities")
|
--
-- Seed the rand!
--
math.randomseed( os.time() )
--
-- Alias string.Format to global Format
--
Format = string.format
--
-- Send C the flags for any materials we want to create
--
local C_Material = Material
function Material( name, words )
if ( !words ) then return C_Material( name ) end
local str = (words:find("vertexlitgeneric") and "1" or "0")
str = str .. (words:find("nocull") and "1" or "0")
str = str .. (words:find("alphatest") and "1" or "0")
str = str .. (words:find("mips") and "1" or "0")
str = str .. (words:find("noclamp") and "1" or "0")
str = str .. (words:find("smooth") and "1" or "0")
str = str .. (words:find("ignorez") and "1" or "0")
return C_Material( name, str )
end
--[[---------------------------------------------------------
IsTableOfEntitiesValid
-----------------------------------------------------------]]
function IsTableOfEntitiesValid( tab )
if ( !tab ) then return false end
for k, v in pairs( tab ) do
if ( !IsValid( v ) ) then return false end
end
return true
end
--[[---------------------------------------------------------
Color related functions - they now have their own
metatable so better put them in their own separate
file
-----------------------------------------------------------]]
include( "util/color.lua" )
--[[---------------------------------------------------------
Prints a table to the console
-----------------------------------------------------------]]
function PrintTable( t, indent, done )
local Msg = Msg
done = done or {}
indent = indent or 0
local keys = table.GetKeys( t )
table.sort( keys, function( a, b )
if ( isnumber( a ) && isnumber( b ) ) then return a < b end
return tostring( a ) < tostring( b )
end )
done[ t ] = true
for i = 1, #keys do
local key = keys[ i ]
local value = t[ key ]
Msg( string.rep( "\t", indent ) )
if ( istable( value ) && !done[ value ] ) then
done[ value ] = true
Msg( key, ":\n" )
PrintTable ( value, indent + 2, done )
done[ value ] = nil
else
Msg( key, "\t=\t", value, "\n" )
end
end
end
--[[---------------------------------------------------------
Returns a random vector
-----------------------------------------------------------]]
function VectorRand( min, max )
min = min || -1
max = max || 1
return Vector( math.Rand( min, max ), math.Rand( min, max ), math.Rand( min, max ) )
end
--[[---------------------------------------------------------
Returns a random angle
-----------------------------------------------------------]]
function AngleRand( min, max )
return Angle( math.Rand( min || -90, max || 90 ), math.Rand( min || -180, max || 180 ), math.Rand( min || -180, max || 180 ) )
end
--[[---------------------------------------------------------
Returns a random color
-----------------------------------------------------------]]
function ColorRand( alpha )
if ( alpha ) then
return Color( math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ) )
end
return Color( math.random( 0, 255 ), math.random( 0, 255 ), math.random( 0, 255 ) )
end
--[[---------------------------------------------------------
Convenience function to precache a sound
-----------------------------------------------------------]]
function Sound( name )
util.PrecacheSound( name )
return name
end
--[[---------------------------------------------------------
Convenience function to precache a model
-----------------------------------------------------------]]
function Model( name )
util.PrecacheModel( name )
return name
end
--[[---------------------------------------------------------
Convenience function to precache a particle
-----------------------------------------------------------]]
function Particle( name )
if ( CLIENT ) then
game.AddParticles( name )
end
return name
end
-- Some nice globals so we don't keep creating objects for no reason
vector_origin = Vector( 0, 0, 0 )
vector_up = Vector( 0, 0, 1 )
angle_zero = Angle( 0, 0, 0 )
color_white = Color( 255, 255, 255, 255 )
color_black = Color( 0, 0, 0, 255 )
color_transparent = Color( 255, 255, 255, 0 )
--[[---------------------------------------------------------
Includes the file - and adds it so the CS file list
-----------------------------------------------------------]]
function IncludeCS( filename )
include( filename )
if ( SERVER ) then
AddCSLuaFile( filename )
end
end
-- Globals
FORCE_STRING = 1
FORCE_NUMBER = 2
FORCE_BOOL = 3
--[[---------------------------------------------------------
AccessorFunc
Quickly make Get/Set accessor fuctions on the specified table
-----------------------------------------------------------]]
function AccessorFunc( tab, varname, name, iForce )
if ( !tab ) then debug.Trace() end
tab[ "Get" .. name ] = function( self ) return self[ varname ] end
if ( iForce == FORCE_STRING ) then
tab[ "Set" .. name ] = function( self, v ) self[ varname ] = tostring( v ) end
return end
if ( iForce == FORCE_NUMBER ) then
tab[ "Set" .. name ] = function( self, v ) self[ varname ] = tonumber( v ) end
return end
if ( iForce == FORCE_BOOL ) then
tab[ "Set" .. name ] = function( self, v ) self[ varname ] = tobool( v ) end
return end
tab[ "Set" .. name ] = function( self, v ) self[ varname ] = v end
end
--[[---------------------------------------------------------
Returns true if object is valid (is not nil and IsValid)
-----------------------------------------------------------]]
function IsValid( object )
if ( !object ) then return false end
local isvalid = object.IsValid
if ( !isvalid ) then return false end
return isvalid( object )
end
--[[---------------------------------------------------------
Safely remove an entity
-----------------------------------------------------------]]
function SafeRemoveEntity( ent )
if ( !IsValid( ent ) || ent:IsPlayer() ) then return end
ent:Remove()
end
--[[---------------------------------------------------------
Safely remove an entity (delayed)
-----------------------------------------------------------]]
function SafeRemoveEntityDelayed( ent, timedelay )
if ( !IsValid( ent ) || ent:IsPlayer() ) then return end
timer.Simple( timedelay, function() SafeRemoveEntity( ent ) end )
end
--[[---------------------------------------------------------
Simple lerp
-----------------------------------------------------------]]
function Lerp( delta, from, to )
if ( delta > 1 ) then return to end
if ( delta < 0 ) then return from end
return from + ( to - from ) * delta
end
--[[---------------------------------------------------------
Convert Var to Bool
-----------------------------------------------------------]]
function tobool( val )
if ( val == nil || val == false || val == 0 || val == "0" || val == "false" ) then return false end
return true
end
--[[---------------------------------------------------------
Universal function to filter out crappy models by name
-----------------------------------------------------------]]
local UselessModels = {
"_gesture", "_anim", "_gst", "_pst", "_shd", "_ss", "_posture", "_anm",
"ghostanim","_paths", "_shared", "anim_", "gestures_", "shared_ragdoll_"
}
function IsUselessModel( modelname )
local modelname = modelname:lower()
if ( !modelname:find( ".mdl", 1, true ) ) then return true end
for k, v in pairs( UselessModels ) do
if ( modelname:find( v, 1, true ) ) then
return true
end
end
return false
end
UTIL_IsUselessModel = IsUselessModel
--[[---------------------------------------------------------
Given a number, returns the right 'th
-----------------------------------------------------------]]
local STNDRD_TBL = { "st", "nd", "rd" }
function STNDRD( num )
num = num % 100
if ( num > 10 and num < 20 ) then
return "th"
end
return STNDRD_TBL[ num % 10 ] or "th"
end
--[[---------------------------------------------------------
From Simple Gamemode Base (Rambo_9)
-----------------------------------------------------------]]
function TimedSin( freq, min, max, offset )
return math.sin( freq * math.pi * 2 * CurTime() + offset ) * ( max - min ) * 0.5 + min
end
--[[---------------------------------------------------------
From Simple Gamemode Base (Rambo_9)
-----------------------------------------------------------]]
function TimedCos( freq, min, max, offset )
return math.cos( freq * math.pi * 2 * CurTime() + offset ) * ( max - min ) * 0.5 + min
end
--[[---------------------------------------------------------
IsEnemyEntityName
-----------------------------------------------------------]]
local EnemyNames = {
npc_antlion = true, npc_antlionguard = true, npc_antlionguardian = true, npc_barnacle = true,
npc_breen = true, npc_clawscanner = true, npc_combine_s = true, npc_cscanner = true, npc_fastzombie = true,
npc_fastzombie_torso = true, npc_headcrab = true, npc_headcrab_fast = true, npc_headcrab_poison = true,
npc_hunter = true, npc_metropolice = true, npc_manhack = true, npc_poisonzombie = true,
npc_strider = true, npc_stalker = true, npc_zombie = true, npc_zombie_torso = true, npc_zombine = true
}
function IsEnemyEntityName( victimtype )
return EnemyNames[ victimtype ] or false
end
--[[---------------------------------------------------------
IsFriendEntityName
-----------------------------------------------------------]]
local FriendlyNames = {
npc_alyx = true, npc_barney = true, npc_citizen = true, npc_dog = true, npc_eli = true,
npc_fisherman = true, npc_gman = true, npc_kleiner = true, npc_magnusson = true,
npc_monk = true, npc_mossman = true, npc_odessa = true, npc_vortigaunt = true
}
function IsFriendEntityName( victimtype )
return FriendlyNames[ victimtype ] or false
end
--[[---------------------------------------------------------
Is content mounted?
IsMounted( "cstrike" )
IsMounted( 4010 )
-----------------------------------------------------------]]
function IsMounted( name )
local games = engine.GetGames()
for k, v in pairs( games ) do
if ( !v.mounted ) then continue end
if ( v.depot == name ) then return true end
if ( v.folder == name ) then return true end
end
return false
end
--[[---------------------------------------------------------
Replacement for C++'s iff ? aa : bb
-----------------------------------------------------------]]
function Either( iff, aa, bb )
if ( iff ) then return aa end
return bb
end
--
-- You can use this function to add your own CLASS_ var.
-- Adding in this way will ensure your CLASS_ doesn't collide with another
--
-- ie Add_NPC_Class( "MY_CLASS" )
function Add_NPC_Class( name )
_G[ name ] = NUM_AI_CLASSES
NUM_AI_CLASSES = NUM_AI_CLASSES + 1
end
if ( CLIENT ) then
--[[---------------------------------------------------------
Remember/Restore cursor position..
Clientside only
If you have a system where you hold a key to show the cursor
Call RememberCursorPosition when the key is released and call
RestoreCursorPosition to restore the cursor to where it was
when the key was released.
If you don't the cursor will appear in the middle of the screen
-----------------------------------------------------------]]
local StoredCursorPos = {}
function RememberCursorPosition()
local x, y = gui.MousePos()
-- If the cursor isn't visible it will return 0,0 ignore it.
if ( x == 0 && y == 0 ) then return end
StoredCursorPos.x, StoredCursorPos.y = x, y
end
function RestoreCursorPosition()
if ( !StoredCursorPos.x || !StoredCursorPos.y ) then return end
input.SetCursorPos( StoredCursorPos.x, StoredCursorPos.y )
end
end
--
-- This is supposed to be clientside, but was exposed to both states for years due to a bug.
--
function CreateClientConVar( name, default, shouldsave, userdata, helptext, min, max )
local iFlags = 0
if ( shouldsave || shouldsave == nil ) then
iFlags = bit.bor( iFlags, FCVAR_ARCHIVE )
end
if ( userdata ) then
iFlags = bit.bor( iFlags, FCVAR_USERINFO )
end
return CreateConVar( name, default, iFlags, helptext, min, max )
end
--[[---------------------------------------------------------
Convar access functions
-----------------------------------------------------------]]
local ConVarCache = {}
function GetConVar( name )
local c = ConVarCache[ name ]
if not c then
c = GetConVar_Internal( name )
if not c then
return
end
ConVarCache[ name ] = c
end
return c
end
function GetConVarNumber( name )
if ( name == "maxplayers" ) then return game.MaxPlayers() end -- Backwards compatibility
local c = GetConVar( name )
return ( c and c:GetFloat() ) or 0
end
function GetConVarString( name )
if ( name == "maxplayers" ) then return tostring( game.MaxPlayers() ) end -- ew
local c = GetConVar( name )
return ( c and c:GetString() ) or ""
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.