content stringlengths 5 1.05M |
|---|
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
--
-- This file is compatible with Lua 5.3
local class = require("class")
require("kaitaistruct")
local enum = require("enum")
EnumForUnknownId = class.class(KaitaiStruct)
EnumForUnknownId.Animal = enum.Enum {
dog = 4,
cat = 7,
chicken = 12,
}
function EnumForUnknownId:_init(io, parent, root)
KaitaiStruct._init(self, io)
self._parent = parent
self._root = root or self
self:_read()
end
function EnumForUnknownId:_read()
self.one = EnumForUnknownId.Animal(self._io:read_u1())
end
|
---
-- Created by IntelliJ IDEA.
-- @author callin2@gmail.com
-- @copyright 2012 임창진
--
require 'Coat'
---------------------------------------------------------------------------------------------
class 'classes.Emitter'
has.name = {is="rw", isa="string"}
has.x = {is="rw", isa="number"}
has.y = {is="rw", isa="number"}
has.rotation = {is="rw", isa="number"}
has.visible = {is="rw", isa="boolean", default=true}
has.loop = {is="rw", isa="boolean", default=false}
has.autoDestroy = {is="rw", isa="boolean", default=false}
has.emitterScale= {is="rw", isa="number",default=1}
has.active = {is="rw", isa="boolean", default=false}
has.group = {is="rw"}
has._activePtCount = {is="rw", isa="number",default=0}
has._rateTable = {is="rw", isa="table", default=function() return {} end}
--[[
em.followObjInfo = {
target = dispObj,
autoRotate = autoRotate ,
rotationOffset = rotationOffset,
xOffset = xOffset,
yOffset = yOffset,
}
--]]
has.followObjInfo = {is="rw", isa="table"}
function method:BUILD()
end
function method:setParentGroup(grp)
self.group = grp
end
function method:changeEmissionRate(particleTypeName, rate)
self._rateTable[particleTypeName] = rate
end
-- todo change x accroding to emittionShape
function method:getNewX()
if self.followObjInfo and self.followObjInfo.target then
return self.followObjInfo.target.x + self.followObjInfo.xOffset
else
return self.x
end
end
-- todo change x accroding to emittionShape
function method:getNewY()
if self.followObjInfo and self.followObjInfo.target then
return self.followObjInfo.target.y + self.followObjInfo.yOffset
else
return self.y
end
end
function method:DEMOLISH()
print('emitter DEMOLISH')
for i=#(self._rateTable),1,-1 do
self._rateTable[i] = nil
end
self._rateTable = nil
self.group = nil
end
|
DONATOR_COLOR = {}
DONATOR_COLOR[0] = {33, 39, 47} -- Not a donator
DONATOR_COLOR[1] = {135, 20, 20} -- IMBA Lead-Developer
DONATOR_COLOR[2] = {100, 20, 20} -- IMBA Developer
DONATOR_COLOR[3] = {0, 102, 255} -- Administrator
DONATOR_COLOR[4] = {220, 40, 40} -- Ember Donator
DONATOR_COLOR[5] = {218, 165, 32} -- Golden Donator
DONATOR_COLOR[6] = {0, 204, 0} -- Green Donator (basic)
DONATOR_COLOR[8] = {47, 91, 151} -- Salamander Donator (blue)
DONATOR_COLOR[7] = {153, 51, 153} -- Icefrog Donator (purple)
DONATOR_COLOR[9] = {185, 75, 10} -- Gaben Donator
DONATOR_COLOR[10] = {255, 255, 255}
|
local UNICORN = KEYS[1]
redis.call('del', 'sexp:' .. UNICORN)
redis.call('hdel', 'sess:' .. UNICORN, 'kill') |
spells = {}
function spells.get_simulation_env(path_to_data, gun_actions)
local env = {}
setmetatable(env,{__index=_G})
env._G = env
loadfile("spells/env.lua", "t", env)()
env.load_symbols(path_to_data, gun_actions)
return env
end
function spells.simulate_action(path_to_data, env, formatter)
dofile("spells/exec.lua")
if formatter.pre_format then
formatter:pre_format()
end
for i,v in ipairs(env.actions) do
action = exec_action(path_to_data, env,i)
formatter:format(action, i, #env.actions)
end
if formatter.post_format then
formatter:post_format()
end
end
return spells |
cddcdm = ""
local file = io.open("scripts/chat.txt", "a")
function OnChat_Command(event, player, message, type, language)
swm = string.lower(message)
if (swm:find(cddcdm.." ") == false) then
else
pg = player:GetGuildName()
msgtype = MSG(type)
tom = type
local plrname = player:GetName()
local giddy = message:gsub(cddcdm.."","")
if (tom == 10) then
file:write("("..GetGameTime()..") "..plrname.." "..giddy"\n")
else
file:write("("..GetGameTime()..") ["..plrname.."] "..msgtype..": "..giddy.."\n")
file:flush()
end
end
end
RegisterServerHook(16, "OnChat_Command")
function MSG(type)
if (type == 1) then
return("says")
elseif (type == 4) then
return("guild("..pg..")")
elseif (type == 6) then
return("yells")
elseif (type == 51) then
return("party")
elseif (type == 17) then
return("(General/trade/LocalDefense/custom)")
elseif (type == 39) then
return("raid")
elseif (type == 45) then
return("Battleground")
elseif (type == 7) then
return("Whispers")
else
return(type)
end
end |
local resource_autoplace = require("resource-autoplace")
data:extend(
{
{
type = "fluid",
name = "eridium",
default_temperature = 18,
heat_capacity = "0.1KJ",
base_color = {r=0.5, g=0, b=0.5},
flow_color = {r=0.5, g=0, b=0.5},
max_temperature = 100,
icon = "__dark-tech__/graphics/icons/eridium.png",
icon_size = 32,
order = "a[fluid]-b[crude-oil]"
},
{
type = "resource",
name = "eridium",
icon = "__dark-tech__/graphics/icons/eridium.png",
icon_size = 32,
flags = {"placeable-neutral"},
category = "basic-fluid",
order="a-b-a",
infinite = true,
highlight = true,
minimum = 60000,
normal = 300000,
infinite_depletion_amount = 10,
resource_patch_search_radius = 12,
tree_removal_probability = 0.7,
tree_removal_max_distance = 32 * 32,
minable =
{
mining_time = 0.5,
results =
{
{
type = "fluid",
name = "eridium",
amount_min = 50,
amount_max = 100,
probability = 1
}
}
},
collision_box = {{ -1.4, -1.4}, {1.4, 1.4}},
selection_box = {{ -0.5, -0.5}, {0.5, 0.5}},
-- autoplace = oil_old_autoplace,
autoplace = resource_autoplace.resource_autoplace_settings{
name = "eridium",
order = "c", -- Other resources are "b"; oil won't get placed if something else is already there.
base_density = 8.2,
base_spots_per_km2 = 5.8,
random_probability = 1/48,
random_spot_size_minimum = 1,
random_spot_size_maximum = 1, -- don't randomize spot size
additional_richness = 220000, -- this increases the total everywhere, so base_density needs to be decreased to compensate
has_starting_area_placement = true,
regular_rq_factor_multiplier = 1
},
stage_counts = {0},
stages =
{
sheet =
{
filename = "__dark-tech__/graphics/entity/eridium.png",
priority = "extra-high",
width = 75,
height = 61,
frame_count = 4,
variation_count = 1
}
},
map_color = {r=0.5, g=0, b=0.5},
map_grid = false
},
{
type = "autoplace-control",
name = "eridium",
richness = true,
order = "b-f",
category = "resource"
},
}) |
-- 游戏列表
local GameListLayer = class("GameListLayer", ccui.ScrollView)
local ClientUpdate = appdf.req(appdf.BASE_SRC.."app.controllers.ClientUpdate")
local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
function GameListLayer:ctor(scene)
print("============= 游戏列表界面创建 =============")
self._scene = scene
self:setDirection(ccui.ScrollViewDir.horizontal)
self:setScrollBarEnabled(false)
self:setBounceEnabled(true)
end
--------------------------------------------------------------------------------------------------------------------
-- 功能方法
--更新游戏列表
function GameListLayer:updateGameList(gamelist)
print("更新游戏列表")
--保存游戏列表
self._gameList = gamelist
--清空子视图
self:removeAllChildren()
if #gamelist == 0 then
return
end
for i = 1, #gamelist do
-- --游戏图标
-- local filestr
-- if i == 1 then filestr = "GameList/game_"..gamelist[i].."_big.png"
-- else filestr = "GameList/game_"..gamelist[i]..".png"
-- end
-- local p
-- if i == 1 then
-- p = cc.p(256, 256)
-- else
-- p = cc.p(256 + math.modf(i / 2) * 392, (i % 2 == 0) and 384 or 125)
-- end
-- --游戏图标按钮
-- local btnGameIcon = ccui.Button:create(filestr, filestr, filestr)
-- btnGameIcon:setPosition(p)
-- btnGameIcon:setTag(gamelist[i]) --游戏KindID做为Tag
-- btnGameIcon:addTo(self)
-- -- btnGameIcon:addTouchEventListener(function(ref, type)
-- -- --改变按钮点击颜色
-- -- if type == ccui.TouchEventType.began then
-- -- ref:setColor(cc.c3b(200, 200, 200))
-- -- elseif type == ccui.TouchEventType.ended or ccui.TouchEventType.canceled then
-- -- ref:setColor(cc.WHITE)
-- -- end
-- -- end)
-- btnGameIcon:addClickEventListener(function()
-- self:onClickGame(self._gameList[i])
-- end)
-- F:\GitHub\762yx\Phone316Game\client\client\res\spine\GameList\27
-- 添加动画
-- if gamelist[i] ~= 200 then
local j = i - 1
local p = cc.p(125 + math.modf(j / 2) * 250, (i % 2 == 0) and 0 or 235)
local json = "spine/GameList/%d/%d.json"
local atlas = "spine/GameList/%d/%d.atlas"
local id = self._gameList[i]
json = string.format(json,id,id)
atlas = string.format(atlas,id,id)
print(json,atlas)
local spine = sp.SkeletonAnimation:create(json, atlas, 1)
spine:addTo(self)
spine:setPosition(p)
spine:setAnimation(0, "animation", true)
--游戏图标按钮
local btnurl = "GameList/sp_none.png"
local btnGameIcon = ccui.Button:create(btnurl,btnurl,btnurl)
btnGameIcon:setPosition(0,120)
btnGameIcon:setScale(180)
btnGameIcon:setTag(gamelist[i]) --游戏KindID做为Tag
btnGameIcon:addTo(spine)
btnGameIcon:addTouchEventListener(function(ref, type)
--改变按钮点击颜色
if type == ccui.TouchEventType.began then
ref:setColor(cc.c3b(200, 200, 200))
elseif type == ccui.TouchEventType.ended or ccui.TouchEventType.canceled then
ref:setColor(cc.WHITE)
end
end)
btnGameIcon:addClickEventListener(function()
self:onClickGame(self._gameList[i])
end)
-- end
end
--设置内容宽度
local contentSize = self:getContentSize()
local containerWidth = 256 + math.modf(#gamelist / 2) * 392 + 384 / 2 + 40
local containerHeiget = contentSize.height
if containerWidth < contentSize.width then
containerWidth = contentSize.width
end
self:setInnerContainerSize(cc.size(containerWidth, containerHeiget))
--滚动的到前面
self:jumpToLeft()
end
--下载游戏
function GameListLayer:downloadGame(gameinfo)
if self._updategame then
showToast(nil, "正在更新 “" .. self._updategame._GameName .. "” 请稍后", 2)
return
end
--保存更新的游戏
self._updategame = gameinfo
local app = self._scene:getApp()
local updateUrl = app:getUpdateUrl()
--下载地址
local fileurl = updateUrl .. "/game/" .. string.sub(gameinfo._Module, 1, -2) .. ".zip"
--文件名
local pos = string.find(gameinfo._Module, "/")
local savename = string.sub(gameinfo._Module, pos + 1, -2) .. ".zip"
--保存路径
local savepath = nil
local unzippath = nil
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if cc.PLATFORM_OS_WINDOWS == targetPlatform then
savepath = device.writablePath .. "download/game/" .. gameinfo._Type .. "/"
unzippath = device.writablePath .. "download/"
else
savepath = device.writablePath .. "game/" .. gameinfo._Type .. "/"
unzippath = device.writablePath
end
print("savepath: " .. savepath)
print("savename: " .. savename)
print("unzippath: " .. unzippath)
--下载游戏压缩包
downFileAsync(fileurl, savename, savepath, function(main, sub)
--对象已经被销毁
if not appdf.isObject(self) then
return
end
--下载回调
if main == appdf.DOWN_PRO_INFO then --进度信息
self:showGameProgress(gameinfo._KindID, sub)
elseif main == appdf.DOWN_COMPELETED then --下载完毕
local zipfile = savepath .. savename
--解压
unZipAsync(zipfile, unzippath, function(result)
--删除压缩文件
os.remove(zipfile)
--清空正在更新的游戏状态
self._updategame = nil
self:hideGameProgress(gameinfo._KindID)
if result == 1 then
--保存版本记录
app:getVersionMgr():setResVersion(gameinfo._ServerResVersion, gameinfo._KindID)
showToast(nil, "“" .. gameinfo._GameName .. "” 下载完毕", 2)
--播放音效
self:playFinishEffect()
else
showToast(nil, "“" .. gameinfo._GameName .. "” 解压失败", 2)
end
end)
else
--清空正在更新的游戏状态
self._updategame = nil
self:hideGameProgress(gameinfo._KindID)
showToast(nil, "“" .. gameinfo._GameName .. "” 下载失败,错误码:" .. main .. ", " .. sub, 2)
end
end)
end
--更新游戏
function GameListLayer:updateGame(gameinfo)
if self._updategame then
showToast(nil, "正在更新 “" .. self._updategame._GameName .. "” 请稍后", 2)
return
end
--保存更新的游戏
self._updategame = gameinfo
local app = self._scene:getApp()
local updateUrl = app:getUpdateUrl()
local newfileurl = updateUrl.."/game/"..gameinfo._Module.."/res/filemd5List.json"
local src = nil
local dst = nil
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if cc.PLATFORM_OS_WINDOWS == targetPlatform then
dst = device.writablePath .. "download/game/" .. gameinfo._Type .. "/"
src = device.writablePath.."download/game/"..gameinfo._Module.."/res/filemd5List.json"
print("PC 更新游戏 "..dst)
print("PC 更新游戏 "..src)
else
dst = device.writablePath .. "game/" .. gameinfo._Type .. "/"
src = device.writablePath.."game/"..gameinfo._Module.."/res/filemd5List.json"
end
local downurl = updateUrl .. "/game/" .. gameinfo._Type .. "/"
--创建更新
self._update = ClientUpdate:create(newfileurl,dst,src,downurl)
self._update:upDateClient(self)
end
--显示游戏进度
function GameListLayer:showGameProgress(wKindID, nPercent)
--游戏图标
local gameicon = self:getChildByTag(wKindID)
if not gameicon then
return
end
local contentSize = gameicon:getContentSize()
--遮罩
local mask = gameicon:getChildByTag(1)
if mask == nil then
mask = ccui.Layout:create()
:setClippingEnabled(true)
:setAnchorPoint(cc.p(0, 0))
:setPosition(0, 0)
:setTag(1)
:addTo(gameicon)
gameicon:clone()
:setColor(cc.c3b(150, 150, 150))
:setAnchorPoint(cc.p(0, 0))
:setPosition(0, 0)
:addTo(mask)
end
mask:setContentSize(contentSize.width, contentSize.height * (100 - nPercent) / 100)
--进度
local progress = gameicon:getChildByTag(2)
if progress == nil then
progress = cc.Label:createWithTTF("0%", "fonts/round_body.ttf", 32)
:enableOutline(cc.c4b(0,0,0,255), 1)
:setPosition(contentSize.width / 2, contentSize.height / 2)
:setTag(2)
:addTo(gameicon)
end
if nPercent == 100 then
progress:setString("正在安装...")
else
progress:setString(nPercent .. "%")
end
end
--隐藏游戏进度
function GameListLayer:hideGameProgress(wKindID)
--游戏图标
local gameicon = self:getChildByTag(wKindID)
if not gameicon then
return
end
gameicon:removeAllChildren()
end
--播放完成音效
function GameListLayer:playFinishEffect()
--播放音效
ExternalFun.playPlazaEffect("gameDownFinish.mp3")
end
--------------------------------------------------------------------------------------------------------------------
-- 事件处理
--点击游戏
function GameListLayer:onClickGame(wKindID)
print("点击游戏图标", wKindID)
--播放按钮音效
ExternalFun.playClickEffect()
local app = self._scene:getApp()
-- --判断游戏是否存在
local gameinfo = app:getGameInfo(wKindID)
if not gameinfo then
showToast(nil, "亲,人家还没准备好呢!", 2)
return
end
-- 暂时屏蔽正式代码 2018.01.01
-- local version = tonumber(app:getVersionMgr():getResVersion(gameinfo._KindID))
-- if version == nil then --下载游戏
-- print("下载游戏")
-- self:downloadGame(gameinfo)
-- elseif gameinfo._ServerResVersion > version then --更新游戏
-- print("更新游戏")
-- self:updateGame(gameinfo)
-- else
-- print("--判断是否开放房间")
-- --判断是否开放房间
-- if GlobalUserItem.getRoomCount(wKindID) == 0 then
-- showToast(nil, "抱歉,游戏房间暂未开放,请稍后再试!", 2)
-- return
-- end
-- print("--通知进入游戏类型")
-- --通知进入游戏类型
-- if self._scene and self._scene.onClickGame then
-- self._scene:onClickGame(wKindID)
-- end
-- end
-- 测试代码 2018.01.01
print("--判断是否开放房间")
--判断是否开放房间
if GlobalUserItem.getRoomCount(wKindID) == 0 then
showToast(nil, "抱歉,游戏房间暂未开放,请稍后再试!", 2)
return
end
print("--通知进入游戏类型")
--通知进入游戏类型
if self._scene and self._scene.onClickGame then
self._scene:onClickGame(wKindID)
end
end
--------------------------------------------------------------------------------------------------------------------
-- ClientUpdate 回调
--更新进度
function GameListLayer:onUpdateProgress(sub, msg, mainpersent)
if self._updategame then
self:showGameProgress(self._updategame._KindID, math.ceil(mainpersent))
end
end
--更新结果
function GameListLayer:onUpdateResult(result,msg)
self:hideGameProgress(self._updategame._KindID)
if result == true then
msg = "“" .. self._updategame._GameName .. "” 更新完毕"
--保存版本记录
self._scene:getApp():getVersionMgr():setResVersion(self._updategame._ServerResVersion, self._updategame._KindID)
--播放音效
self:playFinishEffect()
else
msg = "“" .. self._updategame._GameName .. "” " .. msg
end
--清空正在更新的游戏状态
self._updategame = nil
self._update = nil
showToast(nil, msg, 2)
end
return GameListLayer |
-- Return intersect angles in radians where 0 = right, pi/2 = down etc.
-- Adapted from https://github.com/williamfiset/Algorithms/blob/master/Geometry/CircleCircleIntersectionPoints.js
function intersectAngles(c1, c2)
r1 = c1.radius
r2 = c2.radius
-- Compute the vector
dx = r1 >= r2 and c2.x - c1.x or c1.x - c2.x
dy = r1 >= r2 and c2.y - c1.y or c1.y - c2.y
d = math.sqrt(dx * dx + dy * dy)
eps = 0.00001
if d < eps and math.abs(r1 - r2) < eps then
-- Same circle at same location - infinite solutions.
return null
end
gap = d - (r1 + r2)
nested_gap = math.max(r1, r2) - (math.min(r1, r2) + d)
if gap > eps or nested_gap > eps then
-- No intersection. Either the small circle contained within
-- big circle or circles are simply disjoint.
return {}
end
-- Modern atan is not a direct replacement, see https://pgl.yoyo.org/luai/i/math.atan2
angle = math.atan2(dy, dx)
-- print('base angle', angle)
-- Distance at which the intersection points 'flip' onto the opposite side of the circle
-- I'm sure there must be better math for this :S
flip_d = math.abs(r1 - r2) < eps and 0 or math.sqrt(math.pow(math.max(r1, r2), 2) - math.pow(math.min(r1, r2) / 2, 2))
c1_fudge = 0
c2_fudge = 0
if flip_d <= d then
c1_fudge = r1 >= r2 and 0 or math.pi
c2_fudge = r1 >= r2 and math.pi or 0
end
-- print('flip flop', d, flip_d, c1_fudge, c2_fudge)
-- Single intersection (kissing circles)
c1_angle = angle + c1_fudge
c2_angle = angle + c2_fudge
if math.abs(gap) < eps or math.abs(nested_gap) < eps then
return { { normalizeAngle(c1_angle), normalizeAngle(c2_angle) } }
end
r_small = math.min(r1, r2)
r_big = math.max(r1, r2)
delta_big = math.acos((r_small*r_small-d*d-r_big*r_big)/(-2.0*d*r_big))
delta_small = math.asin(math.sin(delta_big) * r_big / r_small)
if r1 >= r2 then
c1_angle_1 = c1_angle + delta_big
c2_angle_1 = c2_angle - delta_small
c1_angle_2 = c1_angle - delta_big
c2_angle_2 = c2_angle + delta_small
else
c1_angle_1 = c1_angle + delta_small
c2_angle_1 = c2_angle - delta_big
c1_angle_2 = c1_angle - delta_small
c2_angle_2 = c2_angle + delta_big
end
return {
{ normalizeAngle(c1_angle_1), normalizeAngle(c2_angle_1) },
{ normalizeAngle(c1_angle_2), normalizeAngle(c2_angle_2) }
}
end
function normalizeAngle(angle)
return angle % (math.pi * 2)
end
|
-----------------------------------
-- Area: The Eldieme Necropolis (S)
-- NPC: Sarcophagus
-- Type: Quest NPC
-- !pos 336.594, -33.500, -56.728 175
-----------------------------------
local ID = require("scripts/zones/The_Eldieme_Necropolis_[S]/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/settings")
require("scripts/globals/quests")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if
player:getQuestStatus(CRYSTAL_WAR, tpz.quest.id.crystalWar.LOST_IN_TRANSLOCATION) == QUEST_ACCEPTED
and not player:hasKeyItem(tpz.ki.RIGHT_MAP_PIECE)
then
player:startEvent(5)
else
player:messageSpecial(ID.text.SARCOPHAGUS_SEALED)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 5 then
npcUtil.giveKeyItem(player, tpz.ki.RIGHT_MAP_PIECE)
end
end
|
return function()
local Loop = require(script.Parent.Loop)
local BindableEvent = Instance.new("BindableEvent")
describe("Loop", function()
it("should call systems", function()
local NewLoop = Loop.new(1, 2, 3)
local CallCount = 0
NewLoop:ScheduleSystem(function(A, B, C)
CallCount += 1
expect(A).to.equal(1)
expect(B).to.equal(2)
expect(C).to.equal(3)
end)
local Connection = NewLoop:Begin({Default = BindableEvent.Event})
expect(CallCount).to.equal(0)
BindableEvent:Fire()
expect(CallCount).to.equal(1)
Connection.Default:Disconnect()
expect(CallCount).to.equal(1)
end)
it("should call systems in order", function()
local NewLoop = Loop.new()
local Order = {}
local SystemA = {
After = {},
System = function()
table.insert(Order, "a")
end,
}
local SystemB = {
After = {SystemA},
System = function()
table.insert(Order, "b")
end,
}
local SystemC = {
After = {SystemA, SystemB},
System = function()
table.insert(Order, "c")
end,
}
NewLoop:ScheduleSystems({SystemC, SystemB, SystemA})
local Connection = NewLoop:Begin({Default = BindableEvent.Event})
expect(#Order).to.equal(0)
BindableEvent:Fire()
expect(#Order).to.equal(3)
expect(Order[1]).to.equal("a")
expect(Order[2]).to.equal("b")
expect(Order[3]).to.equal("c")
Connection.Default:Disconnect()
end)
it("should call systems with priority in order", function()
local NewLoop = Loop.new()
local Order = {}
local function CleanupStartReplication()
table.insert(Order, "e")
end
local function ReplicateEnemies()
table.insert(Order, "d")
end
local function SpawnSwords()
table.insert(Order, "c")
end
local function SpawnEnemies()
table.insert(Order, "b")
end
local function Neutral()
table.insert(Order, "a")
end
NewLoop:ScheduleSystems({
{
System = SpawnEnemies,
Priority = 0,
},
Neutral,
{
System = ReplicateEnemies,
Priority = 100,
},
{
System = SpawnSwords,
Priority = 1,
},
{
System = CleanupStartReplication,
Priority = 5000,
},
})
local Connection = NewLoop:Begin({Default = BindableEvent.Event})
expect(#Order).to.equal(0)
BindableEvent:Fire()
expect(#Order).to.equal(5)
expect(Order[1]).to.equal("a")
expect(Order[2]).to.equal("b")
expect(Order[3]).to.equal("c")
expect(Order[4]).to.equal("d")
expect(Order[5]).to.equal("e")
Connection.Default:Disconnect()
end)
it("should call middleware", function()
local NewLoop = Loop.new(1, 2, 3)
local Called = {}
NewLoop:AddMiddleware(function(NextFunction)
return function()
table.insert(Called, 2)
NextFunction()
end
end):AddMiddleware(function(NextFunction)
return function()
table.insert(Called, 1)
NextFunction()
end
end):ScheduleSystem(function()
table.insert(Called, 3)
end)
local Connection = NewLoop:Begin({Default = BindableEvent.Event})
expect(#Called).to.equal(0)
BindableEvent:Fire()
expect(#Called).to.equal(3)
expect(Called[1]).to.equal(1)
expect(Called[2]).to.equal(2)
expect(Called[3]).to.equal(3)
Connection.Default:Disconnect()
end)
end)
end
|
local PLUGIN = PLUGIN;
local Clockwork = Clockwork;
Clockwork.config:AddToSystem("[IS] Minimum Spawned Items", "itemspawner_min_items", "The minimum amount of spawned items that are allowed at one time.", 0, 128, 0);
Clockwork.config:AddToSystem("[IS] Maximum Spawned Items", "itemspawner_max_items", "The maximum amount of spawned items that are allowed at one time.", 0, 256, 0);
Clockwork.config:AddToSystem("[IS] Items per Player", "itemspawner_items_per_player", "The amount of spawned items that are allowed per player on the server.", 0, 10, 1);
Clockwork.config:AddToSystem("[IS] Item Spawn Interval", "itemspawner_spawn_interval", "The interval in seconds between spawning items.", 0, 7200, 0);
Clockwork.config:AddToSystem("[IS] Item Spawn Interval Variation", "itemspawner_spawn_interval_variation", "The percentage of variation to allow in the spawn interval.", 0, 1, 2);
Clockwork.config:AddToSystem("[IS] Minimum Items per Interval", "itemspawner_min_items_per_interval", "The minimum amount of items to spawn every interval.", 0, 256, 0);
Clockwork.config:AddToSystem("[IS] Maximum Items per Interval", "itemspawner_max_items_per_interval", "The maximum amount of items to spawn every interval.", 256, 0);
Clockwork.config:AddToSystem("[IS] Items per Interval", "itemspawner_items_per_interval", "The amount of items to spawn on average per interval.", 0, 256, 0);
Clockwork.config:AddToSystem("[IS] Items per Interval Variation", "itemspawner_items_per_interval_variation", "How much the items spawned per interval should vary depending on how high/low the target amount is.", 0, 1, 2);
Clockwork.config:AddToSystem("[IS] Rare Spawn Chance", "itemspawner_rare_spawn_chance", "The chance to select a rare item from the rare spawn list every time an item is spawned.", 0, 1, 3);
Clockwork.config:AddToSystem("[IS] Spawned Item Decay Time", "itemspawner_decay_time", "The amount of hours it takes for an item to be considered decayed if it doesn't get picked up. Decayed items get removed after a map reload.", 0, 256, 0);
Clockwork.config:AddToSystem("[IS] Minimum Players Online", "itemspawner_min_players", "The minimum amount of players that have to be online for items to be spawned.", 0, 80, 0);
Clockwork.config:AddToSystem("[IS] Enable Logging", "itemspawner_logging_enabled", "Turns the logging on and off.", 0, 1, 0); |
--機巧鳥-常世宇受賣長鳴
--
--Script by XyleN5967
function c101105016.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(101105016,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,101105016)
e1:SetCost(c101105016.spcost)
e1:SetTarget(c101105016.sptg)
e1:SetOperation(c101105016.spop)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(101105016,1))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(aux.bfgcost)
e2:SetCountLimit(1,101105016+100)
e2:SetTarget(c101105016.thtg)
e2:SetOperation(c101105016.thop)
c:RegisterEffect(e2)
end
if Auxiliary.AtkEqualsDef==nil then
function Auxiliary.AtkEqualsDef(c)
if not c:IsType(TYPE_MONSTER) or c:IsType(TYPE_LINK) then return false end
if c:GetAttack()~=c:GetDefense() then return false end
return c:IsLocation(LOCATION_MZONE) or c:GetTextAttack()>=0 and c:GetTextDefense()>=0
end
end
function c101105016.costfilter(c,e,tp)
return aux.AtkEqualsDef(c) and c:IsRace(RACE_MACHINE) and c:GetLevel()>1
and Duel.GetMZoneCount(tp,c)>0 and (c:IsControler(tp) or c:IsFaceup())
and Duel.IsExistingMatchingCard(c101105016.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetLevel())
end
function c101105016.spfilter(c,e,tp,lv)
return aux.AtkEqualsDef(c) and c:IsRace(RACE_MACHINE)
and c:GetLevel()<lv and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101105016.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c101105016.costfilter,1,nil,e,tp) end
local sg=Duel.SelectReleaseGroup(tp,c101105016.costfilter,1,1,nil,e,tp)
e:SetLabel(sg:GetFirst():GetLevel())
Duel.Release(sg,REASON_COST)
end
function c101105016.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c101105016.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<1 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c101105016.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,e:GetLabel())
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
function c101105016.thfilter(c)
return c:IsFacedown() and aux.AtkEqualsDef(c)
and c:IsRace(RACE_MACHINE) and c:IsAbleToHand()
end
function c101105016.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101105016.thfilter,tp,LOCATION_REMOVED,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_REMOVED)
end
function c101105016.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c101105016.thfilter,tp,LOCATION_REMOVED,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
|
-- SEC Set Carry, Implied, 1 Bytes, 2 Cycles
local mem = require(script.Parent.Parent.Memory)
local statusRegisters = require(script.Parent.Parent.Registers)
local internal = require(script.Parent.Parent.Internal)
return function()
statusRegisters.carryFlag = true
internal:Cycle()
end |
-----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hadahda
-- Type: Standard NPC
-- !pos -112.029 -6.999 -66.114 50
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
player:startEvent(518)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
|
local json = require('arken.json')
local url = require('arken.net.url')
local test = {}
test.should_return_table_form_url = function()
local url1 = "http://username:password@hostname/path?arg=value#anchor"
local url2 = "http://username:password@hostname/path?arg=1234"
local result = url.parse(url1)
assert( result:resolve("?arg=1234"):build() == url2, result:resolve("?arg=1234"):build() )
end
test.should_return_table_change_params = function()
local result = url.parse("http://username:password@hostname:2345/path?arg=value#anchor")
assert( result:build() == "http://username:password@hostname:2345/path?arg=value#anchor", result:build() )
end
test.should_return_new_url_if_scheme_if_different = function()
local url1 = "http://username:password@hostname/path?arg=value#anchor"
local url2 = "http://username:password@hostname/path?arg=1234"
local result = url.parse(url1)
assert( result:resolve("https://newlink"):build() == "https://newlink" )
end
test.should_return_without_query_string = function()
local url1 = "http://newlink/path"
local url2 = "http://newlink/path?id=1234"
local result = url.parse(url1)
assert( result:resolve("path?id=1234"):build() == url2 )
end
test.should_return_without_path_and_only_querystring = function()
local url1 = "http://newlink/path"
local url2 = "http://newlink/?id=1234"
local result = url.parse(url1)
assert( result:resolve("/?id=1234"):build() == url2, result:resolve("/?id=1234"):build() )
end
test.should_return_domain = function()
local url1 = "http://newlink.org?id=1234"
local url2 = "http://newlink.org/mypath?id=1234"
local result = url.parse(url1)
assert( result:resolve("/mypath"):build() == url2, result:resolve("/mypath"):build() )
end
test.should_return_with_relative_path = function()
local url1 = "http://newlink.org/path?id=1234"
local url2 = "http://newlink.org/mypath?id=1234"
local result = url.parse(url1)
assert( result:resolve("./mypath"):build() == url2, result:resolve("/mypath"):build() )
end
test.should_return_remove_path = function()
local url1 = "http://newlink.org/path?id=1234"
local url2 = "http://newlink.org/?id=1234"
local result = url.parse(url1)
assert( result:resolve("./"):build() == url2, result:resolve("./"):build() )
end
test.should_return_dot_path_example_1 = function()
local url1 = "http://newlink.org/../../?id=1234"
local url2 = "http://newlink.org/path?id=1234"
local result = url.parse(url1)
assert( result:resolve("path"):build() == url2, result:resolve("path"):build() )
end
test.should_return_dot_path_example_3 = function()
local url1 = "http://newlink.org/../../mycustom?id=1234"
local url2 = "http://newlink.org/mycustom?id=1234"
local result = url.parse(url1)
assert( result:resolve("../../mycustom"):build() == url2, result:resolve("../../mycustom"):build() )
end
test.should_return_dot_path_example_4 = function()
local url1 = "http://newlink.org/mycustom?id=1234"
local url2 = "http://newlink.org/?id=1234"
local result = url.parse(url1)
assert( result:resolve("../.."):build() == url2, result:resolve("../.."):build() )
end
test.should_return_dot_path_example_5 = function()
local url1 = "http://newlink.org/../?id=1234"
local url2 = "http://newlink.org/..?id=1234"
local result = url.parse(url1)
assert( result:resolve("../../.."):build() == url2, result:resolve("../../.."):build() )
end
return test
|
function is_nan(n)
return n ~= n
end
function is_err(f)
return pcall(f) == false
end
function is_integer(n)
return is_err(function() return n % 0 end)
end
function test1()
return math.abs( 1) == 1 and
math.abs( -1) == 1 and
math.abs( 1.0) == 1.0 and
math.abs( -1.0) == 1.0 and
is_integer(math.abs(1 )) and
not is_integer(math.abs(1.0))
end
function test2()
return math.acos(1) == 0.0 and
math.abs(math.acos(0) - math.pi/2) < 1e-7 and
math.abs(math.acos(0.5) - math.pi/3) < 1e-7 and
math.abs(math.acos(-1) - math.pi) < 1e-7 and
is_nan(math.acos( 2)) and
is_nan(math.acos(-2)) and
not is_integer(math.acos(1))
end
function test3()
return math.asin(0) == 0.0 and
math.abs(math.asin(1) - math.pi/2) < 1e-7 and
math.abs(math.asin(0.5) - math.pi/6) < 1e-7 and
math.abs(math.asin(-1) + math.pi/2) < 1e-7 and
is_nan(math.asin( 2)) and
is_nan(math.asin(-2)) and
not is_integer(math.asin(0))
end
function test4()
return math.atan(0) == 0.0 and
math.abs(math.atan(1) - math.pi/4) < 1e-7 and
math.abs(math.atan(0.5) - 0.46364760900081) < 1e-7 and
math.abs(math.atan(-1) + math.pi/4) < 1e-7 and
math.abs(math.atan(2) - 1.1071487177941) < 1e-7 and
math.abs(math.atan(-2) + 1.1071487177941) < 1e-7 and
math.abs(math.atan(math.huge) - math.pi/2) < 1e-7 and
math.abs(math.atan(-math.huge) + math.pi/2) < 1e-7 and
not is_integer(math.atan(0))
end
function test5()
return math.atan2(0, 0) == 0.0 and
math.atan2(0, 1) == 0.0 and
math.abs(math.atan2( 1, 0) - math.pi/2) < 1e-7 and
math.abs(math.atan2( 1, 1) - math.pi/4) < 1e-7 and
math.abs(math.atan2(-1, 1) + math.pi/4) < 1e-7 and
math.abs(math.atan2( 1, -1) - 3*math.pi/4) < 1e-7 and
math.abs(math.atan2(-1, -1) + 3*math.pi/4) < 1e-7 and
math.abs(math.atan2(math.huge, 1) - math.pi/2) < 1e-7 and
not is_integer(math.atan2(0, 0))
end
function test6()
return math.ceil( 1.0) == 1 and
math.ceil(-1.0) == -1 and
math.ceil( 1.1) == 2 and
math.ceil(-1.1) == -1 and
is_integer(math.ceil(1.0))
end
function test7()
return math.cos(0) == 1.0 and
math.abs(math.cos(math.pi) + 1.0) < 1e-7 and
math.abs(math.cos(math.pi/6) - math.sqrt(3)/2) < 1e-7 and
math.abs(math.cos(1) - 0.5403023058681398) < 1e-7 and
is_nan(math.cos(math.huge)) and
not is_integer(math.cos(0))
end
function test8()
return math.cosh(0) == 1.0 and
math.abs(math.cosh( 1) - 1.543080634815244) < 1e-7 and
math.abs(math.cosh(-1) - 1.543080634815244) < 1e-7 and
math.cosh(math.huge) == math.huge and
not is_integer(math.cosh(0))
end
function test9()
return math.abs(math.deg(math.pi) - 180) < 1e-7 and
math.abs(math.deg(1) - 180/math.pi) < 1e-7 and
not is_integer(math.deg(math.pi))
end
function test10()
return math.abs(math.exp(1) - 2.718281828459) < 1e-7 and
math.exp(0) == 1 and
math.abs(math.exp(-1) - 0.36787944117144) < 1e-7 and
math.exp(-math.huge) == 0 and
math.exp(math.huge) == math.huge and
not is_integer(math.exp(0))
end
function test11()
return math.floor( 1.0) == 1 and
math.floor(-1.0) == -1 and
math.floor( 1.1) == 1 and
math.floor(-1.1) == -2 and
is_integer(math.ceil(1.0))
end
function test12()
return math.abs(math.fmod( 6.2, 3.4) - 2.8) < 1e-7 and
math.abs(math.fmod(-6.2, 3.4) + 2.8) < 1e-7 and
math.abs(math.fmod( 6.2, -3.4) - 2.8) < 1e-7 and
math.abs(math.fmod(-6.2, -3.4) + 2.8) < 1e-7 and
not is_integer(math.fmod(1.0, 1.0))
end
function test13()
return
math.abs(math.frexp(87573.1902197) - 0.6681304185463) < 1e-7 and
select(2, math.frexp(87573.1902197)) == 17 and
math.abs(math.frexp(16723.61465171) - 0.51036421666595) < 1e-7 and
select(2, math.frexp(16723.61465171)) == 15 and
math.abs(math.frexp(-171089.69623223) + 0.6526553963937) < 1e-7 and
select(2, math.frexp(-171089.69623223)) == 18 and
math.abs(math.frexp(152965.60153365) - 0.5835174619051) < 1e-7 and
select(2, math.frexp(152965.60153365)) == 18 and
math.abs(math.frexp(-491699.40967113) + 0.93784219679094) < 1e-7 and
select(2, math.frexp(-491699.40967113)) == 19 and
math.abs(math.frexp(-90102.646965533) + 0.68742864200999) < 1e-7 and
select(2, math.frexp(-90102.646965533)) == 17 and
math.abs(math.frexp(-182550.06847903) + 0.69637324706662) < 1e-7 and
select(2, math.frexp(-182550.06847903)) == 18 and
math.abs(math.frexp(327863.1796129) - 0.62534938738423) < 1e-7 and
select(2, math.frexp(327863.1796129)) == 19 and
math.abs(math.frexp(404005.37056848) - 0.77057909120271) < 1e-7 and
select(2, math.frexp(404005.37056848)) == 19 and
math.abs(math.frexp(-314283.14419463) + 0.59944752539565) < 1e-7 and
select(2, math.frexp(-314283.14419463)) == 19 and
math.abs(math.frexp(1.6586243640632e-08) - 0.556541984375) < 1e-7 and
select(2, math.frexp(1.6586243640632e-08)) == -25 and
math.abs(math.frexp(-3.6877257842571e-07) + 0.77337215039063) < 1e-7 and
select(2, math.frexp(-3.6877257842571e-07)) == -21 and
math.abs(math.frexp(1.6591683961452e-09) - 0.89075925000003) < 1e-7 and
select(2, math.frexp(1.6591683961452e-09)) == -29 and
math.abs(math.frexp(-3.9305121637881e-08) + 0.659430515625) < 1e-7 and
select(2, math.frexp(-3.9305121637881e-08)) == -24 and
math.abs(math.frexp(-4.7698671976104e-07) + 0.50015682666016) < 1e-7 and
select(2, math.frexp(-4.7698671976104e-07)) == -20 and
math.abs(math.frexp(-2.3943610163406e-07) + 0.50213389941406) < 1e-7 and
select(2, math.frexp(-2.3943610163406e-07)) == -21 and
math.abs(math.frexp(-4.9012135714292e-09) + 0.65782974999999) < 1e-7 and
select(2, math.frexp(-4.9012135714292e-09)) == -27 and
math.abs(math.frexp(-4.9168974207714e-07) + 0.51557406298828) < 1e-7 and
select(2, math.frexp(-4.9168974207714e-07)) == -20 and
math.abs(math.frexp(-4.7032095026225e-08) + 0.7890676171875) < 1e-7 and
select(2, math.frexp(-4.7032095026225e-08)) == -24 and
math.abs(math.frexp(4.8018892854452e-07) - 0.5035145859375) < 1e-7 and
select(2, math.frexp(4.8018892854452e-07)) == -20 and
select(2, math.frexp(math.huge)) == 0 and
math.frexp(-math.huge) == -math.huge and
select(2, math.frexp(math.huge)) == 0 and
is_nan(math.frexp(0.0 % 0.0)) and
select(2, math.frexp(0.0 % 0.0)) == 0
end
function test14()
return
math.abs(math.ldexp(0.6681304185463, 17) - 87573.1902197) < 1e-7 * 2^17 and
math.abs(math.ldexp(0.51036421666595, 15) - 16723.61465171) < 1e-7 * 2^15 and
math.abs(math.ldexp(-0.6526553963937, 18) + 171089.69623223) < 1e-7 * 2^18 and
math.abs(math.ldexp(0.5835174619051, 18) - 152965.60153365) < 1e-7 * 2^18 and
math.abs(math.ldexp(-0.93784219679094, 19) + 491699.40967113) < 1e-7 * 2^19 and
math.abs(math.ldexp(-0.68742864200999, 17) + 90102.646965533) < 1e-7 * 2^17 and
math.abs(math.ldexp(-0.69637324706662, 18) + 182550.06847903) < 1e-7 * 2^18 and
math.abs(math.ldexp(0.62534938738423, 19) - 327863.1796129) < 1e-7 * 2^19 and
math.abs(math.ldexp(0.77057909120271, 19) - 404005.37056848) < 1e-7 * 2^19 and
math.abs(math.ldexp(-0.59944752539565, 19) + 314283.14419463) < 1e-7 * 2^19 and
math.abs(math.ldexp(0.556541984375, -25) - 1.6586243640632e-08) < 1e-7 * 2^-25 and
math.abs(math.ldexp(-0.77337215039063, -21) + 3.6877257842571e-07) < 1e-7 * 2^-21 and
math.abs(math.ldexp(0.89075925000003, -29) - 1.6591683961452e-09) < 1e-7 * 2^-29 and
math.abs(math.ldexp(-0.659430515625, -24) + 3.9305121637881e-08) < 1e-7 * 2^-24 and
math.abs(math.ldexp(-0.50015682666016, -20) + 4.7698671976104e-07) < 1e-7 * 2^-20 and
math.abs(math.ldexp(-0.50213389941406, -21) + 2.3943610163406e-07) < 1e-7 * 2^-21 and
math.abs(math.ldexp(-0.65782974999999, -27) + 4.9012135714292e-09) < 1e-7 * 2^-27 and
math.abs(math.ldexp(-0.51557406298828, -20) + 4.9168974207714e-07) < 1e-7 * 2^-20 and
math.abs(math.ldexp(-0.7890676171875, -24) + 4.7032095026225e-08) < 1e-7 * 2^-24 and
math.abs(math.ldexp(0.5035145859375, -20) - 4.8018892854452e-07) < 1e-7 * 2^-20
end
function test15()
return math.log(0) == -math.huge and
math.log(1) == 0.0 and
math.abs(math.log(10) - 2.302585092994) < 1e-7 and
is_nan(math.log(-1))
end
function test16()
return math.log10(0) == -math.huge and
math.log10(1) == 0.0 and
math.log10(10) == 1.0 and
math.abs(math.log10(3.1622776601684) - 0.5) < 1e-7 and
is_nan(math.log10(-1))
end
function test17()
return math.max(1, 2, 3) == 3 and
is_integer(math.max(1, 2, 3)) and
math.max(1.0, 2.0, 3.0) == 3.0 and
not is_integer(math.max(1.0, 2.0, 3.0)) and
math.max(3, 3.0, 3.0) == 3 and
is_integer(math.max(3, 3.0, 3.0)) and
math.max(-5, -4, -3, -2, -1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1) == 10
-- Tests we do not currently pass due to incompatibility with PUC-Rio Lua
-- is_err(math.max(1, "2", 1))
end
function test18()
return math.min(3, 2, 1) == 1 and
is_integer(math.min(3, 2, 1)) and
math.min(3.0, 2.0, 1.0) == 1.0 and
not is_integer(math.min(3.0, 2.0, 1.0)) and
math.min(3, 3.0, 3.0) == 3 and
is_integer(math.min(3, 3.0, 3.0)) and
math.min(5, 4, 3, 2, 1, 0, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1) == -10
-- Tests we do not currently pass due to incompatibility with PUC-Rio Lua
-- is_err(math.min(1, "2", 1))
-- is_nan(math.min(0.0 % 0.0, 1, 2))
end
function test19()
return
math.modf(216.57550707459) == 216 and
math.abs(select(2, math.modf(216.57550707459)) - 0.5755070745945) < 1e-7 and
math.modf(-356.93994024768) == -356 and
math.abs(select(2, math.modf(-356.93994024768)) + 0.93994024768472) < 1e-7 and
math.modf(-230.78241851181) == -230 and
math.abs(select(2, math.modf(-230.78241851181)) + 0.78241851180792) < 1e-7 and
math.modf(-184.36720222235) == -184 and
math.abs(select(2, math.modf(-184.36720222235)) + 0.36720222234726) < 1e-7 and
math.modf(95.250256825238) == 95 and
math.abs(select(2, math.modf(95.250256825238)) - 0.25025682523847) < 1e-7 and
math.modf(-383.47252598032) == -383 and
math.abs(select(2, math.modf(-383.47252598032)) + 0.47252598032355) < 1e-7 and
math.modf(480.07427062839) == 480 and
math.abs(select(2, math.modf(480.07427062839)) - 0.074270628392696) < 1e-7 and
math.modf(123.98638017476) == 123 and
math.abs(select(2, math.modf(123.98638017476)) - 0.98638017475605) < 1e-7 and
math.modf(365.17379572615) == 365 and
math.abs(select(2, math.modf(365.17379572615)) - 0.17379572615027) < 1e-7 and
math.modf(-271.84157492593) == -271 and
math.abs(select(2, math.modf(-271.84157492593)) + 0.84157492592931) < 1e-7 and
math.modf(347.25950565189) == 347 and
math.abs(select(2, math.modf(347.25950565189)) - 0.25950565189123) < 1e-7 and
math.modf(406.10403195024) == 406 and
math.abs(select(2, math.modf(406.10403195024)) - 0.10403195023537) < 1e-7 and
math.modf(365.7353548333) == 365 and
math.abs(select(2, math.modf(365.7353548333)) - 0.73535483330488) < 1e-7 and
math.modf(352.64282440767) == 352 and
math.abs(select(2, math.modf(352.64282440767)) - 0.64282440766692) < 1e-7 and
math.modf(256.04179827496) == 256 and
math.abs(select(2, math.modf(256.04179827496)) - 0.041798274964094) < 1e-7 and
math.modf(-278.28463632613) == -278 and
math.abs(select(2, math.modf(-278.28463632613)) + 0.2846363261342) < 1e-7 and
math.modf(-206.89806248993) == -206 and
math.abs(select(2, math.modf(-206.89806248993)) + 0.89806248992682) < 1e-7 and
math.modf(-76.712315436453) == -76 and
math.abs(select(2, math.modf(-76.712315436453)) + 0.71231543645263) < 1e-7 and
math.modf(205.99580463022) == 205 and
math.abs(select(2, math.modf(205.99580463022)) - 0.99580463021994) < 1e-7 and
math.modf(-13.91322305426) == -13 and
math.abs(select(2, math.modf(-13.91322305426)) + 0.91322305426002) < 1e-7
end
function test20()
return math.abs(math.rad(180) - math.pi) < 1e-7 and
math.abs(math.rad(360) - 2*math.pi) < 1e-7 and
math.abs(math.rad(15) - math.pi/12) < 1e-7
end
function test21()
local good = true
for i=1,10000,1 do
local rand = math.random()
good = good and rand >= 0 and rand < 1
end
for i=1,10000,1 do
local rand = math.random(4, 20)
good = good and rand >= 4 and rand <= 20
end
for i=1,10000,1 do
local rand = math.random(35)
good = good and rand >= 1 and rand <= 35
end
local numbers1 = {}
math.randomseed(8675309)
for i=1,10000,1 do
numbers1[#numbers1 + 1] = math.random()
end
local numbers2 = {}
math.randomseed(8675309)
for i=1,10000,1 do
numbers2[#numbers2 + 1] = math.random()
end
for i=1,10000,1 do
good = good and numbers1[i] == numbers2[i]
end
return good
end
function test22()
return math.sin(0) == 0.0 and
math.abs(math.sin(math.pi) - 0.0) < 1e-7 and
math.abs(math.sin(math.pi/6) - 0.5) < 1e-7 and
math.abs(math.sin(1) - 0.8414709848079) < 1e-7 and
is_nan(math.sin(math.huge)) and
not is_integer(math.sin(0))
end
function test23()
return math.abs(math.sqrt(1.0) - 1.0) < 1e-7 and
math.abs(math.sqrt(4.0) - 2.0) < 1e-7 and
math.abs(math.sqrt(0.09) - 0.3) < 1e-7 and
is_nan(math.sqrt(-3))
end
function test24()
return math.tan(0) == 0.0 and
math.abs(math.tan(math.pi) - 0.0) < 1e-7 and
math.abs(math.tan(math.pi/6) - 0.57735026918963) < 1e-7 and
math.abs(math.tan(1) - 1.5574077246549) < 1e-7 and
is_nan(math.tan(math.huge)) and
not is_integer(math.tan(0))
end
function test25()
return math.tointeger(1.0) == 1 and
math.tointeger(1.1) == nil and
math.tointeger(-3.0) == -3 and
math.tointeger(4.00000002) == nil and
is_integer(math.tointeger(8.0))
end
function test26()
return math.type(1) == "integer" and
math.type(1.0) == "float" and
math.type("1.0") == nil
end
function test27()
return not math.ult(-3, 2) and
math.ult(-3, -2) and
math.ult(1, 2)
end
return test1() and
test2() and
test3() and
test4() and
test5() and
test6() and
test7() and
test8() and
test9() and
test10() and
test11() and
test12() and
test13() and
test14() and
test15() and
test16() and
test17() and
test18() and
test19() and
test20() and
test21() and
test22() and
test23() and
test24() and
test25() and
test26() and
test27()
|
function onCreate()
precacheSound('hitsounds/SNAP')
end
function goodNoteHit(id, noteData, noteType, isSustainNote)
if not isSustainNote then
playSound('hitsounds/SNAP', 3)
end
end |
function fadeIn(name, time, volume_)
if soundExists(name) then
volumeType(name, 0)
local addVolume = (volume_ / time) * 100
local called = 0
local volume = volume_
while true do
volume = volume - addVolume
if volume < 0 then volume = 0 end
if volume == 0 then break end
called = called + 1
end
volume = getVolume(name)
while true do
Citizen.Wait(time / called)
volume = volume + addVolume
if volume > volume_ then
volume = volume_
volumeType(name, volume)
break
end
volumeType(name, volume)
end
end
end
exports('fadeIn', fadeIn)
function fadeOut(name, time)
if soundExists(name) then
local volume = getVolume(name)
local addVolume = (volume / time) * 100
local called = 0
while true do
volume = volume - addVolume
if volume < 0 then volume = 0 end
if volume == 0 then break end
called = called + 1
end
volume = getVolume(name)
while true do
Citizen.Wait(time / called)
volume = volume - addVolume
if volume < 0 then
volume = 0
volumeType(name, volume)
break
end
volumeType(name, volume)
end
end
end
exports('fadeOut', fadeOut)
function fadeVolume(name, time, volume_)
if soundExists(name) then
local fadeId = math.random(99999)
soundInfo[name].fadeId = fadeId
local initVol = soundInfo[name].volume
local toFade = volume_ - initVol
local repeats = time / 25
local toChange = toFade / repeats
for i = 1, repeats do
Citizen.Wait(25)
if soundInfo[name].fadeId ~= fadeId then
return
end
volumeType(name, initVol + (toChange * i))
end
end
end
exports('fadeVolume', fadeVolume)
function volumeType(name, volume)
if isDynamic(name) then
setVolumeMax(name,volume)
setVolume(name,volume)
else
setVolume(name,volume)
end
end |
local sirenTable = {
[411] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,1.2,0.25}, ["phases"]={true,true,false,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,1.2,0.25}, ["phases"]={false,false,true,true}},
},
[451] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.8,0.25}, ["phases"]={true,false,false,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.8,0.25}, ["phases"]={false,true,true,false}},
},
[415] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.8,0.25}, ["phases"]={true,false,false,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.8,0.25}, ["phases"]={false,true,true,false}},
},
[506] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.7,0.25}, ["phases"]={true,true,false,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.7,0.25}, ["phases"]={false,false,true,true}},
},
[495] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.5,1,0.4}, ["phases"]={false,true,true,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.5,1,0.4}, ["phases"]={true,false,false,true}},
},
[402] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.7,0.25}, ["phases"]={false,false,true,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.7,0.25}, ["phases"]={true,true,false,false}},
},
[541] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.35,0.85,0.3}, ["phases"]={true,false,false,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.35,0.85,0.3}, ["phases"]={false,true,true,false}},
},
[565] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.8,0.25}, ["phases"]={true,true,false,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.8,0.25}, ["phases"]={false,false,true,true}},
},
[560] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,1,0.35}, ["phases"]={false,true,true,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,1,0.35}, ["phases"]={true,false,false,true}},
},
[480] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.45,0.25}, ["phases"]={false,false,true,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.45,0.25}, ["phases"]={true,true,false,false}},
},
[559] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.75,0.25}, ["phases"]={true,false,false,true}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.75,0.25}, ["phases"]={false,true,true,false}},
},
[562] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.75,0.35}, ["phases"]={true,true,false,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.75,0.35}, ["phases"]={false,false,true,true}},
},
[429] = {
[1] = {["color"]={255,0,0}, ["pos"]={-0.4,0.35,0.25}, ["phases"]={false,true,true,false}},
[2] = {["color"]={0,0,255}, ["pos"]={0.4,0.35,0.25}, ["phases"]={true,false,false,true}},
},
}
local playerSirens = {}
local globalTimer = false
local current = 0
-- const
local phases = 4
addEvent('vip_startSirenForPlayer', true)
addEventHandler('vip_startSirenForPlayer', root,
function (player, status)
if status then
playerSirens[player] = true
else
local temp = playerSirens[player]
if temp ~= true and temp.active then
local sirens = playerSirens[player].active
local dummies = playerSirens[player].dummies
playerSirens[player] = nil
if sirens then
for i, s in ipairs(sirens) do
if s then
destroyCorona(s)
destroyElement(dummies[i])
end
end
end
else
playerSirens[player] = nil
end
end
end)
function timer()
current = current + 1
if current > phases then
current = 1
end
local playerVeh = false
local vehID = false
local activeSirens = {}
local siren = false
local temp = nil
for i,p in ipairs(getElementsByType("player")) do
activeSirens = {}
if playerSirens[p] then
playerVeh = getPedOccupiedVehicle(p)
if playerVeh then
vehID = getElementModel(playerVeh)
if isVehicleCompatible(vehID) then
if playerSirens[p] == true or playerSirens[p]["vehicle"] ~= vehID then
temp = playerSirens[p]
if temp ~= true and temp["active"] then
for c, s in ipairs(playerSirens[p].active) do
if s then
destroyElement(playerSirens[p].dummies[c])
destroyCorona(s)
end
end
end
playerSirens[p] = {["vehicle"]=vehID,["active"]={},["dummies"]={}}
for v=1,#sirenTable[vehID] do
table.insert(playerSirens[p].active, false)
table.insert(playerSirens[p].dummies, false)
end
end
for c, s in ipairs(sirenTable[vehID]) do
if s.phases[current] then
activeSirens[c] = true
end
end
for c, s in ipairs(playerSirens[p].active) do
if s then
if not activeSirens[c] then
destroyCorona(s)
destroyElement(playerSirens[p].dummies[c])
playerSirens[p].dummies[c] = false
playerSirens[p].active[c] = false
end
else
if activeSirens[c] then
siren = createCorona(0,0,0,0.5,sirenTable[vehID][c].color[1],sirenTable[vehID][c].color[2],sirenTable[vehID][c].color[3],255,false)
local dummy = createMarker(0,0,0,"cylinder",0.1)
setElementAlpha(dummy, 0)
playerSirens[p].dummies[c] = dummy
attachElements(dummy, playerVeh, sirenTable[vehID][c].pos[1], sirenTable[vehID][c].pos[2], sirenTable[vehID][c].pos[3])
playerSirens[p].active[c] = siren
end
end
end
else
temp = playerSirens[p]
if temp ~= true and temp["active"] then
for c, s in ipairs(playerSirens[p].active) do
if s then
destroyElement(playerSirens[p].dummies[c])
destroyCorona(s)
playerSirens[p].active[c] = false
end
end
end
end
end
end
end
end
addEventHandler('onClientPreRender', root,
function()
pcall( -- pcall so lua stops spamming some bs errors
function()
for i, p in ipairs(getElementsByType('player')) do
if p and playerSirens[p] and type(playerSirens[p]["active"]) ~= nil then
local vehicle = getPedOccupiedVehicle(p)
if vehicle then
local vehID = getElementModel(vehicle)
if isVehicleCompatible(vehID) then
for c, s in ipairs(playerSirens[p].active) do
if s then
local x,y,z = getElementPosition(playerSirens[p].dummies[c])
setCoronaPosition(s, x, y, z)
end
end
end
end
end
end
end)
end)
function isVehicleCompatible(vehicleid)
if not sirenTable[vehicleid] or sirenTable[vehicleid] == false or sirenTable[vehicleid] == nil then return false else return true end
end
addEventHandler('onClientResourceStart', resourceRoot,
function()
globalTimer = setTimer(timer, 100, 0)
end)
addEventHandler('onClientResourceStop', resourceRoot,
function()
for i, p in ipairs(getElementsByType('player')) do
pcall(function(p)
if playerSirens[p] and playerSirens[p]["active"] then
for c, s in ipairs(playerSirens[p].active) do
if s then
destroyCorona(s)
end
end
end
end, p)
end
end)
|
require 'nn'
-- thanks to https://github.com/soumith/imagenet-multiGPU.torch for this example
nGPU = 4
nClasses = 10
-- from https://code.google.com/p/cuda-convnet2/source/browse/layers/layers-imagenet-1gpu.cfg
-- this is AlexNet that was presented in the One Weird Trick paper. http://arxiv.org/abs/1404.5997
local features = nn.Sequential()
features:add(nn.SpatialConvolution(3,64,11,11,4,4,2,2)) -- 224 -> 55
features:add(nn.SpatialBatchNormalization(64,1e-3))
features:add(nn.ReLU(true))
features:add(nn.SpatialMaxPooling(3,3,2,2)) -- 55 -> 27
features:add(nn.SpatialConvolution(64,192,5,5,1,1,2,2)) -- 27 -> 27
features:add(nn.SpatialBatchNormalization(192,1e-3))
features:add(nn.ReLU(true))
features:add(nn.SpatialMaxPooling(3,3,2,2)) -- 27 -> 13
features:add(nn.SpatialConvolution(192,384,3,3,1,1,1,1)) -- 13 -> 13
features:add(nn.SpatialBatchNormalization(384,1e-3))
features:add(nn.ReLU(true))
features:add(nn.SpatialConvolution(384,256,3,3,1,1,1,1)) -- 13 -> 13
features:add(nn.SpatialBatchNormalization(256,1e-3))
features:add(nn.ReLU(true))
features:add(nn.SpatialConvolution(256,256,3,3,1,1,1,1)) -- 13 -> 13
features:add(nn.SpatialBatchNormalization(256,1e-3))
features:add(nn.ReLU(true))
features:add(nn.SpatialMaxPooling(3,3,2,2)) -- 13 -> 6
-- features:cuda()
-- features = makeDataParallel(features, nGPU) -- defined in util.lua
local classifier = nn.Sequential()
classifier:add(nn.View(256*6*6))
classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(256*6*6, 4096))
classifier:add(nn.BatchNormalization(4096, 1e-3))
classifier:add(nn.ReLU())
classifier:add(nn.Dropout(0.5))
classifier:add(nn.Linear(4096, 4096))
classifier:add(nn.BatchNormalization(4096, 1e-3))
classifier:add(nn.ReLU())
classifier:add(nn.Linear(4096, nClasses))
classifier:add(nn.LogSoftMax())
-- classifier:cuda()
local model = nn.Sequential():add(features):add(classifier)
model.imageSize = 256
model.imageCrop = 224
return model
|
Types = require("types")
function dump(o)
if type(o) == "table" then
local s = "{ "
for k, v in pairs(o) do
if type(k) ~= "number" then
k = '"' .. k .. '"'
end
s = s .. "[" .. k .. "] = " .. dump(v) .. ","
end
return s .. "} "
else
return tostring(o)
end
end
function add(a, b)
return {x = a.x + b.x, y = a.y + b.y}
end
function math.clamp(val, lower, upper)
assert(val and lower and upper, "not very useful error message here")
if lower > upper then
lower, upper = upper, lower
end -- swap if boundaries supplied the wrong way
return math.max(lower, math.min(upper, val))
end
width, height = love.graphics.getDimensions()
cell_size = 2
width_cells = math.floor(width / cell_size)
height_cells = math.floor(height / cell_size)
cells = {} -- create the matrix
function make_particle(pos, type)
local p = {
type = type,
rA = 0.5 + math.random() * 0.1,
rB = 0
}
if (cells[pos.x][pos.y] == 0) then
cells[pos.x][pos.y] = p
end
end
function neighborGetter(pos)
return function(offset)
local oX = math.clamp(offset.x, -1, 1)
local oY = math.clamp(offset.y, -1, 1)
local rX = pos.x + oX
local rY = pos.y + oY
if (rX < 1 or rX >= width_cells + 1 or rY < 1 or rY >= height_cells) then
return nil
end
return cells[rX][rY]
end
end
function neighborSetter(pos)
return function(offset, v)
local oX = math.clamp(offset.x, -1, 1)
local oY = math.clamp(offset.y, -1, 1)
local rX = pos.x + oX
local rY = pos.y + oY
if (rX < 1 or rX >= width_cells + 1 or rY < 1 or rY >= height_cells) then
print("oob set")
return nil
end
cells[rX][rY] = v
if (v ~= 0) then
imageData:setPixel(rX - 1, rY - 1, v.type / 10., v.rA, v.rB, 1)
else
imageData:setPixel(rX - 1, rY - 1, 0, 0, 0, 1)
end
end
end
for i = 1, width_cells do
cells[i] = {} -- create a new row
for j = 1, height_cells do
cells[i][j] = 0
-- make_particle({x = i, y = j})
end
end
for i = 0, 100 do
local pos = {
x = math.random(1, width_cells),
y = math.random(1, height_cells - 1)
}
make_particle(pos, 1)
end
|
local function calc_len(a)
return #a
end
return function(types)
return {
handler = calc_len,
args = {types.NUMBER, types.STRING},
argc = 1,
help = "Returns the length of the supplied string",
type_helper = {},
}
end
|
local m = {} -- <<< Don't touch this!
-----------[ SETTINGS ]---------------------------------------------------
-- Delay in minutes between messages
m.delay = 35
-- Prefix appears in front of each message.
-- Suffix appears on the end of each message.
-- Leave a prefix/suffix empty ( '' ) to disable them.
m.prefix = '[^7Правителство]:'
m.suffix = ''
-- You can make as many messages as you want.
-- You can use ^0-^9 in your messages to change text color.
m.messages = {
' ^1Напишете /help преди да започнете да играете Задължително!'
}
-- Player identifiers on this list will not receive any messages.
-- Simply remove all identifiers if you don't want an ignore list.
m.ignorelist = {
'ip:127.0.1.5',
'steam:123456789123456',
'license:1654687313215747944131321',
}
--------------------------------------------------------------------------
-----[ CODE, DON'T TOUCH THIS ]-------------------------------------------
local playerIdentifiers
local enableMessages = true
local timeout = m.delay * 1000 * 60 -- from ms, to sec, to min
local playerOnIgnoreList = false
RegisterNetEvent('va:setPlayerIdentifiers')
AddEventHandler('va:setPlayerIdentifiers', function(identifiers)
playerIdentifiers = identifiers
end)
Citizen.CreateThread(function()
while playerIdentifiers == {} or playerIdentifiers == nil do
Citizen.Wait(1000)
TriggerServerEvent('va:getPlayerIdentifiers')
end
for iid in pairs(m.ignorelist) do
for pid in pairs(playerIdentifiers) do
if m.ignorelist[iid] == playerIdentifiers[pid] then
playerOnIgnoreList = true
break
end
end
end
if not playerOnIgnoreList then
while true do
for i in pairs(m.messages) do
if enableMessages then
chat(i)
print('[vAnnouncer] Message #' .. i .. ' sent.')
end
Citizen.Wait(timeout)
end
Citizen.Wait(0)
end
else
print('[vAnnouncer] Player is on ignorelist, no announcements will be received.')
end
end)
function chat(i)
TriggerEvent('chatMessage', '', {255,255,255}, m.prefix .. m.messages[i] .. m.suffix)
end
RegisterCommand('automessage', function()
enableMessages = not enableMessages
if enableMessages then
status = '^2enabled^5.'
else
status = '^1disabled^5.'
end
TriggerEvent('chatMessage', '', {255, 255, 255}, '^5[vAnnouncer] automessages are now ' .. status)
end, false)
--------------------------------------------------------------------------
|
local M = {}
M.base_30 = {
white = "#d6deeb",
darker_black = "#010f20",
black = "#011627",
black2 = "#091e2f",
one_bg = "#112637", -- real bg of onedark
one_bg2 = "#1b3041",
one_bg3 = "#253a4b",
grey = "#2c4152",
grey_fg = "#34495a",
grey_fg2 = "#3c5162",
light_grey = "#495e6f",
red = "#f78c6c",
baby_pink = "#ff6cca",
pink = "#fa58b6",
line = "#182d3e",
green = "#29E68E",
vibrant_green = "#22da6e",
blue = "#82aaff",
nord_blue = "#78a0f5",
yellow = "#ffcb8b",
sun = "#ffe9a9",
purple = "#c792ea",
dark_purple = "#a974cc",
teal = "#96CEB4",
orange = "#FFAD60",
cyan = "#aad2ff",
statusline_bg = "#051a2b",
lightbg = "#1a2f40",
pmenu_bg = "#82aaff",
folder_bg = "#82aaff",
}
M.base_16 = {
base00 = "#011627",
base01 = "#0c2132",
base02 = "#172c3d",
base03 = "#223748",
base04 = "#2c4152",
base05 = "#ced6e3",
base06 = "#d6deeb",
base07 = "#feffff",
base08 = "#ecc48d",
base09 = "#f78c6c",
base0A = "#c792ea",
base0B = "#29E68E",
base0C = "#aad2ff",
base0D = "#82aaff",
base0E = "#c792ea",
base0F = "#f78c6c",
}
M.polish_hl = {
TSParameter = {
fg = M.base_30.orange,
},
TSKeywordReturn = {
fg = M.base_30.cyan,
},
TSConditional = {
fg = M.base_30.cyan,
},
PmenuSel = {
bg = M.base_30.blue,
},
}
M.type = "dark"
M = require("base46").override_theme(M, "nightowl")
return M
|
local ga = gajosframework
ga.VehicleView = classExtends(View, function()
end)
|
require "config"
local floor = math.floor
local ChunkSize = 32
local RegionSizeInChunks = math.min(math.max(2, RegionSize), 256)
local RegionOffsetInChunks = floor(RegionSizeInChunks / 2)
local RegionSizeInTiles = RegionSizeInChunks * ChunkSize
local RegionOffsetInTiles = RegionOffsetInChunks * ChunkSize
local SearchRadius = math.min(math.max(2, ResourceFieldSearchRadius), 20)
local SearchMin = -SearchRadius
local SearchMax = ResourceFieldSearchAllDirections and SearchRadius or 0
local function ResourceNameToDisplayName(resourceName)
local s = ResourceDisplayName[resourceName]
if not s then
s, _ = string.gsub(resourceName, "(%W+)", " ")
s, _ = string.gsub(s, "^(%w)", string.upper)
end
return s
end
local function AddChunkToRegions( chunk, regions )
local regionX = floor((chunk.x - RegionOffsetInChunks) / RegionSizeInChunks)
local regionY = floor((chunk.y - RegionOffsetInChunks) / RegionSizeInChunks)
local regionKey = regionX .. "|" .. regionY
local region = regions[regionKey]
if not region then
region = {x = regionX, y = regionY, chunks = {}}
regions[regionKey] = region
end
local chunkX = chunk.x - RegionOffsetInChunks - regionX * RegionSizeInChunks
local chunkY = chunk.y - RegionOffsetInChunks - regionY * RegionSizeInChunks
local chunkKey = RegionSizeInChunks * chunkX + chunkY
region.chunks[chunkKey] = true
end
local function AddTileToRegion(originX, originY, entity, tiles, fields)
local tileX = floor(entity.position.x + 0.5) - originX
local tileY = floor(entity.position.y + 0.5) - originY
local tileKey = RegionSizeInTiles * tileX + tileY
if tiles[tileKey] then return end
local field = nil
for dx = SearchMin, SearchMax do
for dy = SearchMin, SearchMax do
if dx ~= 0 or dy ~= 0 then
local neighborKey = tileKey + RegionSizeInTiles * dx + dy
local neighborField = tiles[neighborKey]
if neighborField then
if not field then
field = neighborField
field[#field + 1] = tileKey
tiles[tileKey] = field
elseif field ~= neighborField then
for i = 1, #neighborField do
local otherKey = neighborField[i]
field[#field + 1] = otherKey
tiles[otherKey] = field
neighborField.ignore = true
end
end
end
end
end
end
if not field then
field = {tileKey}
tiles[tileKey] = field
fields[#fields + 1] = field
end
end
local function CreateMapLabelsForRegion(surface, region, resourceName, displayName)
local originX = RegionSizeInTiles * region.x + RegionOffsetInTiles
local originY = RegionSizeInTiles * region.y + RegionOffsetInTiles
local tiles = {}
local fields = {}
for chunkKey,_ in pairs(region.chunks) do
local chunkX = floor(chunkKey / RegionSizeInChunks)
local chunkY = chunkKey - RegionSizeInChunks * chunkX
local x = originX + ChunkSize * chunkX
local y = originY + ChunkSize * chunkY
for _, entity in ipairs(surface.find_entities_filtered({name = resourceName, area = {{x, y}, {x + ChunkSize - 1, y + ChunkSize - 1}}})) do
AddTileToRegion(originX, originY, entity, tiles, fields)
end
end
for i = 1, #fields do
local field = fields[i]
if not field.ignore then
local centroidX = 0
local centroidY = 0
local tileCount = #field
for j = 1, tileCount do
local tileKey = field[j]
local tileX = floor(tileKey / RegionSizeInTiles)
local tileY = tileKey - RegionSizeInTiles * tileX
centroidX = centroidX + tileX
centroidY = centroidY + tileY
end
local position = {originX + floor(centroidX / tileCount + 0.5), originY + floor(centroidY / tileCount + 0.5)}
local chartTag = {position = position}
local showResourceIcon = settings.global["map-labels-show-resource-icon"].value
local showResourceName = settings.global["map-labels-show-resource-name"].value
if showResourceIcon then
local prototype = game.entity_prototypes[resourceName]
local signalType = nil
if prototype then
if prototype.type == "resource" then
if prototype.resource_category == "basic-fluid" and game.fluid_prototypes[resourceName] ~= nil then
signalType = "fluid"
elseif prototype.resource_category == "basic-solid" and game.item_prototypes[resourceName] ~= nil then
signalType = "item"
end
end
end
if signalType ~= nil then
local signalID = {type = signalType, name = resourceName}
chartTag.icon = signalID
end
end
if showResourceName then
chartTag.text = displayName
end
if showResourceIcon or showResourceName then
game.forces.player.add_chart_tag(surface.name, chartTag)
end
end
end
end
local function CreateMapLabels()
for _, surface in pairs(game.surfaces) do
local regions = {}
for chunk in surface.get_chunks() do
if game.forces.player.is_chunk_charted(surface, chunk) then
AddChunkToRegions(chunk, regions)
end
end
for _, proto in pairs(game.entity_prototypes) do
if proto.type == "resource" then
local resourceName = proto.name
local displayName = ResourceNameToDisplayName(resourceName)
if displayName ~= "" then
for _, region in pairs(regions) do
CreateMapLabelsForRegion(surface, region, resourceName, displayName)
end
end
end
end
end
end
local function DestroyMapLabels()
for _, surface in pairs(game.surfaces) do
for chunk in surface.get_chunks() do
local x = ChunkSize * chunk.x
local y = ChunkSize * chunk.y
for _, chartTag in ipairs(game.forces.player.find_chart_tags(surface.name, {{x,y}, {x + ChunkSize, y + ChunkSize}})) do
if not chartTag.last_user then
chartTag.destroy()
end
end
end
end
end
local function InitPlayer(player)
local gui = player.gui
if settings.get_player_settings(player)["map-labels-show-button"].value then
if not gui.top.MapLabelButton then
gui.top.add{type="button", name = "MapLabelButton", caption = "Map Labels"}
end
else
if gui.top.MapLabelButton then
gui.top.MapLabelButton.destroy()
end
end
end
script.on_init( function(event)
global.HaveMapLabels = false
for _, player in ipairs(game.players) do
InitPlayer(player)
end
end)
script.on_event(defines.events.on_player_created, function(event)
InitPlayer(game.players[event.player_index])
end)
script.on_configuration_changed(function(event)
global.HaveMapLabels = false
for _, player in pairs(game.players) do
InitPlayer(player)
end
end)
script.on_event(defines.events.on_runtime_mod_setting_changed, function(event)
if event.setting == "map-labels-show-button" then
InitPlayer(game.players[event.player_index])
end
end)
local function toggleMapLables()
if global.HaveMapLabels then
DestroyMapLabels()
global.HaveMapLabels = false
else
CreateMapLabels()
global.HaveMapLabels = true
end
end
script.on_event("map-labels-hotkey-toggle", function(event)
toggleMapLables()
end)
script.on_event(defines.events.on_gui_click, function(event)
if event.element.name == "MapLabelButton" then
toggleMapLables()
end
end)
|
--[[
LUA MODULE
optparse - Lua-based partial reimplementation of Python's
optparse [2-3] command-line parsing module.
SYNOPSIS
local OptionParser = require "optparse" . OptionParser
local opt = OptionParser{usage="%prog [options] [gzip-file...]",
version="foo 1.23", add_help_option=false}
opt.add_option{"-h", "--help", action="store_true", dest="help",
help="give this help"}
opt.add_option{
"-f", "--force", dest="force", action="store_true",
help="force overwrite of output file"}
local options, args = opt.parse_args()
if options.help then opt.print_help(); os.exit(1) end
if options.force then print 'f' end
for _, name in ipairs(args) do print(name) end
DESCRIPTION
This library provides a command-line parsing[1] similar to Python optparse [2-3].
Note: Python also supports getopt [4].
STATUS
This module is fairly basic but could be expanded.
API
See source code and also compare to Python's docs [2,3] for details because
the following documentation is incomplete.
opt = OptionParser {usage=usage, version=version, add_help_option=add_help_option}
Create command line parser.
opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help}
Add command line option specification. This may be called multiple times.
opt.parse_args() --> options, args
Perform argument parsing.
DEPENDENCIES
None (other than Lua 5.1 or 5.2)
REFERENCES
[1] http://lua-users.org/wiki/CommandLineParsing
[2] http://docs.python.org/lib/optparse-defining-options.html
[3] http://blog.doughellmann.com/2007/08/pymotw-optparse.html
[4] http://docs.python.org/lib/module-getopt.html
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
(end license)
--]]
local M = {_TYPE='module', _NAME='optparse', _VERSION='0.3.20111128'}
local ipairs = ipairs
local unpack = unpack
local io = io
local table = table
local os = os
local arg = arg
local function OptionParser(t)
local usage = t.usage
--local version = t.version
local o = {}
local option_descriptions = {}
local option_of = {}
function o.fail(s) -- extension
io.stderr:write(s .. '\n')
os.exit(1)
end
function o.add_option(optdesc)
option_descriptions[#option_descriptions+1] = optdesc
for _,v in ipairs(optdesc) do
option_of[v] = optdesc
end
end
function o.parse_args()
-- expand options (e.g. "--input=file" -> "--input", "file")
local arg = {unpack(arg)}
for i=#arg,1,-1 do local v = arg[i]
local flag, val = v:match('^(%-%-%w+)=(.*)')
if flag then
arg[i] = flag
table.insert(arg, i+1, val)
end
end
local options = {}
local args = {}
local i = 1
while i <= #arg do local v = arg[i]
local optdesc = option_of[v]
if optdesc then
local action = optdesc.action
local val
if action == 'store' or action == nil then
i = i + 1
val = arg[i]
if not val then o.fail('option requires an argument ' .. v) end
elseif action == 'store_true' then
val = true
elseif action == 'store_false' then
val = false
end
options[optdesc.dest] = val
else
if v:match('^%-') then o.fail('invalid option ' .. v) end
args[#args+1] = v
end
i = i + 1
end
if options.help then
o.print_help()
os.exit()
end
if options.version then
io.stdout:write(t.version .. "\n")
os.exit()
end
return options, args
end
local function flags_str(optdesc)
local sflags = {}
local action = optdesc.action
for _,flag in ipairs(optdesc) do
local sflagend
if action == nil or action == 'store' then
local metavar = optdesc.metavar or optdesc.dest:upper()
sflagend = #flag == 2 and ' ' .. metavar
or '=' .. metavar
else
sflagend = ''
end
sflags[#sflags+1] = flag .. sflagend
end
return table.concat(sflags, ', ')
end
function o.print_help()
io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n")
io.stdout:write("\n")
io.stdout:write("Options:\n")
local maxwidth = 0
for _,optdesc in ipairs(option_descriptions) do
maxwidth = math.max(maxwidth, #flags_str(optdesc))
end
for _,optdesc in ipairs(option_descriptions) do
io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc))
.. optdesc.help .. "\n")
end
end
if t.add_help_option == nil or t.add_help_option == true then
o.add_option{"--help", action="store_true", dest="help",
help="show this help message and exit"}
end
if t.version then
o.add_option{"--version", action="store_true", dest="version",
help="output version info"}
end
return o
end
M.OptionParser = OptionParser
return M
|
Weapon.PrettyName = "Winchester 87"
Weapon.WeaponID = "m9k_1887winchester"
Weapon.DamageMultiplier = 1.0
Weapon.WeaponType = WEAPON_PRIMARY |
local T = Tetromino:extend()
local state = 1
-- this block is initially looking like a upside down T. they are aligned like this:
-- block_two block_three block_four
-- block_one
-- the passed parameters will be assigned to block_one.
-- the values for block_three, block_four and block_two will be calculated from the passed parameters
function T:new(x, y)
T.super.new(self)
self.block_one = Block(x, y)
self.block_two = Block(x - block_size, y - block_size)
self.block_three = Block(x, y - block_size)
self.block_four = Block(x + block_size, y - block_size)
end
function T:up()
local success = self:rotateClockwise(self.block_three, self.block_one, self.block_two, self.block_four)
end
function T:update(dt)
end
function T:draw()
love.graphics.setColor(1.0, 0.239, 0.474)
T.super.draw(self)
end
return T
|
local modules = {
Audio = {
Deps = {"NazaraCore"},
Packages = {"dr_wav", "libflac", "libvorbis", "minimp3"},
Custom = function ()
add_packages("openal-soft", {links = {}}) -- Don't link OpenAL (it will be loaded dynamically)
end
},
Core = {
Custom = function ()
-- NazaraMath is header-only, make it part of the core project
add_headerfiles("include/(Nazara/Math/**.hpp)", "include/(Nazara/Math/**.inl)")
if is_plat("linux") then
add_syslinks("dl", "pthread")
end
end,
Packages = {"entt"}
},
Graphics = {
Deps = {"NazaraRenderer"},
Packages = {"entt"}
},
Network = {
Deps = {"NazaraCore"},
Custom = function()
if is_plat("windows") then
add_syslinks("ws2_32")
end
if is_plat("linux") then
del_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp")
del_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp")
end
end
},
OpenGLRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
if is_plat("windows") then
add_syslinks("gdi32", "user32")
else
del_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp")
del_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp")
end
if not is_plat("linux") then
del_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp")
end
end
},
Physics2D = {
Deps = {"NazaraUtility"},
Packages = {"chipmunk2d"}
},
Physics3D = {
Deps = {"NazaraUtility"},
Packages = {"entt", "newtondynamics"}
},
Platform = {
Deps = {"NazaraUtility"},
Packages = {"libsdl"},
Custom = function()
if is_plat("windows") then
add_defines("SDL_VIDEO_DRIVER_WINDOWS=1")
elseif is_plat("linux") then
add_defines("SDL_VIDEO_DRIVER_X11=1")
add_defines("SDL_VIDEO_DRIVER_WAYLAND=1")
elseif is_plat("macosx") then
add_defines("SDL_VIDEO_DRIVER_COCOA=1")
end
end
},
Renderer = {
Deps = {"NazaraPlatform", "NazaraShader"}
},
Shader = {
Deps = {"NazaraUtility"}
},
Utility = {
Deps = {"NazaraCore"},
Packages = {"entt", "freetype", "stb"}
},
VulkanRenderer = {
Deps = {"NazaraRenderer"},
Custom = function()
add_defines("VK_NO_PROTOTYPES")
if is_plat("windows") then
add_defines("VK_USE_PLATFORM_WIN32_KHR")
add_syslinks("user32")
elseif is_plat("linux") then
add_defines("VK_USE_PLATFORM_XLIB_KHR")
add_defines("VK_USE_PLATFORM_WAYLAND_KHR")
elseif is_plat("macosx") then
add_defines("VK_USE_PLATFORM_MACOS_MVK")
end
end
}
}
set_xmakever("2.5.6")
add_repositories("local-repo xmake-repo")
add_requires("chipmunk2d", "dr_wav", "entt", "freetype", "libflac", "libsdl", "minimp3", "stb")
add_requires("libvorbis", { configs = { with_vorbisenc = false } })
add_requires("openal-soft", { configs = { shared = true }})
add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux
set_project("NazaraEngine")
add_rules("mode.asan", "mode.debug", "mode.releasedbg")
add_rules("plugin.vsxmake.autoupdate")
add_rules("build_rendererplugins")
set_allowedmodes("asan", "debug", "releasedbg")
set_allowedplats("windows", "linux", "macosx")
set_allowedarchs("windows|x64", "linux|x86_64", "macosx|x86_64")
set_defaultmode("debug")
if is_mode("debug") then
add_rules("debug_suffix")
elseif is_mode("asan") then
set_optimize("none") -- by default xmake will optimize asan builds
end
add_includedirs("include")
add_sysincludedirs("thirdparty/include")
set_languages("c89", "cxx17")
set_rundir("./bin/$(os)_$(arch)_$(mode)")
set_symbols("debug", "hidden")
set_targetdir("./bin/$(os)_$(arch)_$(mode)")
set_warnings("allextra")
if is_mode("releasedbg") then
set_fpmodels("fast")
add_vectorexts("sse", "sse2", "sse3", "ssse3")
end
if is_plat("windows") then
set_runtimes(is_mode("debug") and "MDd" or "MD")
add_defines("_CRT_SECURE_NO_WARNINGS")
add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:referenceBinding", "/Zc:throwingNew")
add_cxflags("/w44062") -- Enable warning: switch case not handled
add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah
end
for name, module in pairs(modules) do
target("Nazara" .. name)
set_kind("shared")
set_group("Modules")
add_rules("embed_resources")
if module.Deps then
add_deps(table.unpack(module.Deps))
end
if module.Packages then
add_packages(table.unpack(module.Packages))
end
if module.Custom then
module.Custom()
end
add_defines("NAZARA_BUILD")
add_defines("NAZARA_" .. name:upper() .. "_BUILD")
if is_mode("debug") then
add_defines("NAZARA_DEBUG")
add_defines("NAZARA_" .. name:upper() .. "_DEBUG")
end
for _, ext in ipairs({".h", ".hpp", ".inl", ".natvis"}) do
add_headerfiles("include/(Nazara/" .. name .. "/**" .. ext .. ")")
add_headerfiles("src/Nazara/" .. name .. "/**" .. ext)
end
add_files("src/Nazara/" .. name .. "/**.cpp")
add_includedirs("src")
for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h")) do
add_files(filepath, {rule = "embed_resources"})
end
if is_plat("windows") then
del_files("src/Nazara/" .. name .. "/Posix/**.cpp")
else
del_files("src/Nazara/" .. name .. "/Win32/**.cpp")
end
if not is_plat("linux") then
del_files("src/Nazara/" .. name .. "/Linux/**.cpp")
end
end
includes("xmake/actions/*.lua")
includes("tools/xmake.lua")
includes("tests/xmake.lua")
includes("plugins/*/xmake.lua")
includes("examples/*/xmake.lua")
-- Adds -d as a debug suffix
rule("debug_suffix")
on_load(function (target)
if target:kind() ~= "binary" then
target:set("basename", target:basename() .. "-d")
end
end)
-- Builds renderer plugins if linked to NazaraRenderer
rule("build_rendererplugins")
after_load(function (target)
if target:kind() == "binary" and target:dep("NazaraRenderer") then
for name, _ in pairs(modules) do
local depName = "Nazara" .. name
if name:match("^.+Renderer$") and target:dep(depName) == nil then -- don't overwrite dependency
target:add("deps", depName, {inherit = false})
end
end
end
end)
-- Turns resources into includables headers
rule("embed_resources")
before_build(function (target, opt)
import("core.base.option")
import("private.utils.progress")
local function GenerateEmbedHeader(filepath, targetpath)
local bufferSize = 1024 * 1024
progress.show(opt.progress, "${color.build.object}embedding %s", filepath)
local resource = assert(io.open(filepath, "rb"))
local targetFile = assert(io.open(targetpath, "w+"))
local resourceSize = resource:size()
local remainingSize = resourceSize
local headerSize = 0
while remainingSize > 0 do
local readSize = math.min(remainingSize, bufferSize)
local data = resource:read(readSize)
remainingSize = remainingSize - readSize
local headerContentTable = {}
for i = 1, #data do
table.insert(headerContentTable, string.format("%d,", data:byte(i)))
end
local content = table.concat(headerContentTable)
headerSize = headerSize + #content
targetFile:write(content)
end
resource:close()
targetFile:close()
end
for _, sourcebatch in pairs(target:sourcebatches()) do
if sourcebatch.rulename == "embed_resources" then
for _, sourcefile in ipairs(sourcebatch.sourcefiles) do
local targetpath = sourcefile .. ".h"
if option.get("rebuild") or os.mtime(sourcefile) >= os.mtime(targetpath) then
GenerateEmbedHeader(sourcefile, targetpath)
end
end
end
end
end)
|
workspace "Liatris"
architecture "x64"
startproject "Liatris Editor"
configurations
{
"Debug",
"Release",
"Dist"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["GLFW"] = "Liatris/vendor/GLFW/include"
IncludeDir["Glad"] = "Liatris/vendor/Glad/include"
IncludeDir["ImGui"] = "Liatris/vendor/imgui"
IncludeDir["glm"] = "Liatris/vendor/glm"
IncludeDir["entt"] = "Liatris/vendor/entt/include"
IncludeDir["ImGuizmo"] = "Liatris/vendor/ImGuizmo"
IncludeDir["tinygltf"] = "Liatris/vendor/tinygltf"
group "Dependencies"
include "Liatris/vendor/GLFW"
include "Liatris/vendor/Glad"
include "Liatris/vendor/imgui"
group ""
project "Liatris"
location "Liatris"
kind "StaticLib"
cppdialect "C++17"
language "C++"
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
pchheader "liapch.h"
pchsource "Liatris/src/liapch.cpp"
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp",
"%{prj.name}/vendor/ImGuizmo/ImGuizmo.h",
"%{prj.name}/vendor/ImGuizmo/ImGuizmo.cpp"
}
defines
{
"_CRT_SECURE_NO_WARNINGS"
}
includedirs
{
"%{prj.name}/src",
"%{prj.name}/vendor/spdlog/include",
"%{IncludeDir.GLFW}",
"%{IncludeDir.Glad}",
"%{IncludeDir.ImGui}",
"%{IncludeDir.glm}",
"%{IncludeDir.entt}",
"%{IncludeDir.ImGuizmo}",
"%{IncludeDir.tinygltf}"
}
links
{
"GLFW",
"Glad",
"ImGui",
"opengl32.lib"
}
filter "files:Liatris/vendor/ImGuizmo/**.cpp"
flags { "NoPCH" }
filter "system:windows"
systemversion "latest"
defines
{
"LIA_PLATFORM_WINDOWS",
"LIA_BUILD_DLL",
"GLFW_INCLUDE_NONE"
}
filter "configurations:Debug"
defines "LIA_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LIA_RELEASE"
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines "LIA_DIST"
runtime "Release"
optimize "on"
project "Liatris Editor"
location "Liatris Editor"
kind "ConsoleApp"
cppdialect "C++17"
language "C++"
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Liatris/vendor/spdlog/include",
"Liatris/src",
"Liatris/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.entt}",
"%{IncludeDir.ImGuizmo}",
"%{IncludeDir.tinygltf}"
}
links
{
"Liatris"
}
filter "system:windows"
systemversion "latest"
defines
{
"LIA_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "LIA_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LIA_RELEASE"
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines "LIA_DIST"
runtime "Release"
optimize "on"
project "Sandbox"
location "Sandbox"
kind "ConsoleApp"
cppdialect "C++17"
language "C++"
staticruntime "on"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files
{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs
{
"Liatris/vendor/spdlog/include",
"Liatris/src",
"Liatris/vendor",
"%{IncludeDir.glm}",
"%{IncludeDir.entt}"
}
links
{
"Liatris"
}
filter "system:windows"
systemversion "latest"
defines
{
"LIA_PLATFORM_WINDOWS"
}
filter "configurations:Debug"
defines "LIA_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LIA_RELEASE"
runtime "Release"
optimize "on"
filter "configurations:Dist"
defines "LIA_DIST"
runtime "Release"
optimize "on" |
local mod = EPGP:NewModule("points")
local L = LibStub("AceLocale-3.0"):GetLocale("EPGP")
local GP = LibStub("LibGearPoints-1.3")
local LN = LibStub("LibLocalConstant-1.0")
local Utils = LibStub("LibUtils-1.0")
local LOCAL_NAME = LN:LocalName()
local DISPLAY_NAME = {}
DISPLAY_NAME.OneHWeapon = L["%s %s"]:format(_G.INVTYPE_WEAPON, _G.WEAPON)
DISPLAY_NAME.TwoHWeapon = L["%s %s"]:format(_G.INVTYPE_2HWEAPON, _G.WEAPON)
DISPLAY_NAME.MainHWeapon = L["%s %s"]:format(_G.INVTYPE_WEAPONMAINHAND, _G.WEAPON)
DISPLAY_NAME.OffHWeapon = L["%s %s"]:format(_G.INVTYPE_WEAPONOFFHAND, _G.WEAPON)
local profileDefault = {
enabled = true,
baseGP = 1000,
standardIlvl = 66,
ilvlDenominator = 10,
legendaryScale = 3,
headScale1 = 1,
headComment1 = _G.INVTYPE_HEAD,
neckScale1 = 0.56,
neckComment1 = _G.INVTYPE_NECK,
shoulderScale1 = 0.75,
shoulderComment1 = _G.INVTYPE_SHOULDER,
-- bodyScale1 = 0,
-- bodyComment1 = _G.INVTYPE_BODY,
chestScale1 = 1,
chestComment1 = _G.INVTYPE_CHEST,
waistScale1 = 0.75,
waistComment1 = _G.INVTYPE_WAIST,
legsScale1 = 1,
legsComment1 = _G.INVTYPE_LEGS,
feetScale1 = 0.75,
feetComment1 = _G.INVTYPE_FEET,
wristScale1 = 0.56,
wristComment1 = _G.INVTYPE_WRIST,
handScale1 = 0.75,
handComment1 = _G.INVTYPE_HAND,
fingerScale1 = 0.56,
fingerComment1 = _G.INVTYPE_FINGER,
trinketScale1 = 1.25,
trinketComment1 = _G.INVTYPE_TRINKET,
cloakScale1 = 0.56,
cloakComment1 = _G.INVTYPE_CLOAK,
weaponScale1 = 1.5,
weaponComment1 = DISPLAY_NAME.MainHWeapon,
weaponScale2 = 0.5,
weaponComment2 = DISPLAY_NAME.OffHWeapon .. " / " .. L["%s %s"]:format(_G.TANK, DISPLAY_NAME.MainHWeapon),
weaponScale3 = 0.25,
weaponComment3 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
shieldScale1 = 1.5,
shieldComment1 = L["%s %s"]:format(_G.TANK, _G.SHIELDSLOT),
shieldScale2 = 0.5,
shieldComment2 = L["%s %s"]:format(L["Non-tank"], _G.SHIELDSLOT),
weapon2HScale1 = 2,
weapon2HComment1 = DISPLAY_NAME.TwoHWeapon,
weapon2HScale2 = 0.5,
weapon2HComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.TwoHWeapon),
weaponMainHScale1 = 1.5,
weaponMainHComment1 = DISPLAY_NAME.MainHWeapon,
weaponMainHScale2 = 0.25,
weaponMainHComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
weaponOffHScale1 = 0.5,
weaponOffHComment1 = DISPLAY_NAME.OffHWeapon,
weaponOffHScale2 = 0.25,
weaponOffHComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
holdableScale1 = 0.5,
holdableComment1 = _G.INVTYPE_HOLDABLE,
rangedScale1 = 2,
rangedComment1 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, _G.INVTYPE_RANGED),
rangedScale2 = 0.5,
rangedComment2 = L["%s %s"]:format(L["Non-hunter"], _G.INVTYPE_RANGED),
wandScale1 = 0.5,
wandComment1 = LOCAL_NAME.Wand,
thrownScale1 = 0.5,
thrownComment1 = LOCAL_NAME.Thrown,
relicScale1 = 0.667,
relicComment1 = _G.INVTYPE_RELIC,
-- bagScale1 = 0,
-- bagComment1 = _G.INVTYPE_BAG,
}
mod.dbDefaults = {
profile = profileDefault
}
local function HelpPlate(desc, order)
help = {
order = order or 1,
type = "description",
name = desc,
fontSize = "medium",
}
return help
end
local function ScalePlate(index)
scalePlate = {
name = L["Multiplier %d"]:format(index),
type = "range",
min = 0,
max = 5,
step = 0.01,
order = index * 2,
}
return scalePlate
end
local function CommentPlate(index)
local s = L["Comment %d"]:format(index)
commentPlate = {
name = s,
desc = s,
type = "input",
order = index * 2 + 1,
}
return commentPlate
end
local function RecommendParamsString()
local s = ""
local standardIlvl, _, _, ilvlDenominator = GP:GetRecommendIlvlParams()
if standardIlvl then
s = s .. string.format("standard_ilvl = %d ", standardIlvl)
end
if standardIlvl then
s = s .. string.format("ilvl_denominator = %d", ilvlDenominator)
end
if s ~= "" then
s = L["Recommend value in current tier:"] .. "\n" .. s
end
return s
end
mod.optionsName = L["Gear Points"]
mod.optionsDesc = L["Gear Points"]
mod.optionsArgs = {
help = HelpPlate(L["Set gear points (GP multiplier). Each slot could set up to 3 points. Each points has a custom comment."]),
headerEquation = {
order = 10,
type = "header",
name = L["Equation"],
},
equation = {
order = 11,
type = "group",
inline = true,
name = "",
args = {
equationHelp = HelpPlate("GP = base_gp * 2 ^ [(level - standard_ilvl) / ilvl_denominator] * slot_scale"),
baseGP = {
order = 2,
type = "range",
name = "base_gp",
min = 1,
max = 10000,
step = 0.01,
},
standardIlvl = {
order = 3,
type = "range",
name = "standard_ilvl",
min = 0,
max = 1000,
step = 0.01,
},
ilvlDenominator = {
order = 4,
type = "range",
name = "ilvl_denominator",
min = 1,
max = 100,
step = 0.01,
},
legendaryScale = {
order = 5,
type = "range",
name = L["Legendary Scale"],
min = 1,
max = 10,
step = 0.01,
},
recommend = HelpPlate(RecommendParamsString(), 6)
},
},
headerSlots = {
order = 20,
type = "header",
name = L["Slots"],
},
head = {
order = 21,
type = "group",
name = _G.INVTYPE_HEAD,
args = {
help = HelpPlate(_G.INVTYPE_HEAD),
headScale1 = ScalePlate(1),
headComment1 = CommentPlate(1),
headScale2 = ScalePlate(2),
headComment2 = CommentPlate(2),
headScale3 = ScalePlate(3),
headComment3 = CommentPlate(3),
},
},
neck = {
order = 22,
type = "group",
name = _G.INVTYPE_NECK,
args = {
help = HelpPlate(_G.INVTYPE_NECK),
neckScale1 = ScalePlate(1),
neckComment1 = CommentPlate(1),
neckScale2 = ScalePlate(2),
neckComment2 = CommentPlate(2),
neckScale3 = ScalePlate(3),
neckComment3 = CommentPlate(3),
},
},
shoulder = {
order = 23,
type = "group",
name = _G.INVTYPE_SHOULDER,
args = {
help = HelpPlate(_G.INVTYPE_SHOULDER),
shoulderScale1 = ScalePlate(1),
shoulderComment1 = CommentPlate(1),
shoulderScale2 = ScalePlate(2),
shoulderComment2 = CommentPlate(2),
shoulderScale3 = ScalePlate(3),
shoulderComment3 = CommentPlate(3),
},
},
-- body = {
-- order = 24,
-- type = "group",
-- name = _G.INVTYPE_BODY, -- Shirt
-- args = {
-- help = HelpPlate(_G.INVTYPE_BODY),
-- bodyScale1 = ScalePlate(1),
-- bodyComment1 = CommentPlate(1),
-- bodyScale2 = ScalePlate(2),
-- bodyComment2 = CommentPlate(2),
-- bodyScale3 = ScalePlate(3),
-- bodyComment3 = CommentPlate(3),
-- },
-- },
chest = {
order = 25,
type = "group",
name = _G.INVTYPE_CHEST, -- also _G.INVTYPE_ROBE
args = {
help = HelpPlate(_G.INVTYPE_CHEST),
chestScale1 = ScalePlate(1),
chestComment1 = CommentPlate(1),
chestScale2 = ScalePlate(2),
chestComment2 = CommentPlate(2),
chestScale3 = ScalePlate(3),
chestComment3 = CommentPlate(3),
},
},
waist = {
order = 26,
type = "group",
name = _G.INVTYPE_WAIST,
args = {
help = HelpPlate(_G.INVTYPE_WAIST),
waistScale1 = ScalePlate(1),
waistComment1 = CommentPlate(1),
waistScale2 = ScalePlate(2),
waistComment2 = CommentPlate(2),
waistScale3 = ScalePlate(3),
waistComment3 = CommentPlate(3),
},
},
legs = {
order = 27,
type = "group",
name = _G.INVTYPE_LEGS,
args = {
help = HelpPlate(_G.INVTYPE_LEGS),
legsScale1 = ScalePlate(1),
legsComment1 = CommentPlate(1),
legsScale2 = ScalePlate(2),
legsComment2 = CommentPlate(2),
legsScale3 = ScalePlate(3),
legsComment3 = CommentPlate(3),
},
},
feet = {
order = 28,
type = "group",
name = _G.INVTYPE_FEET,
args = {
help = HelpPlate(_G.INVTYPE_FEET),
feetScale1 = ScalePlate(1),
feetComment1 = CommentPlate(1),
feetScale2 = ScalePlate(2),
feetComment2 = CommentPlate(2),
feetScale3 = ScalePlate(3),
feetComment3 = CommentPlate(3),
},
},
wrist = {
order = 29,
type = "group",
name = _G.INVTYPE_WRIST,
args = {
help = HelpPlate(_G.INVTYPE_WRIST),
wristScale1 = ScalePlate(1),
wristComment1 = CommentPlate(1),
wristScale2 = ScalePlate(2),
wristComment2 = CommentPlate(2),
wristScale3 = ScalePlate(3),
wristComment3 = CommentPlate(3),
},
},
hand = {
order = 30,
type = "group",
name = _G.INVTYPE_HAND,
args = {
help = HelpPlate(_G.INVTYPE_HAND),
handScale1 = ScalePlate(1),
handComment1 = CommentPlate(1),
handScale2 = ScalePlate(2),
handComment2 = CommentPlate(2),
handScale3 = ScalePlate(3),
handComment3 = CommentPlate(3),
},
},
finger = {
order = 31,
type = "group",
name = _G.INVTYPE_FINGER,
args = {
help = HelpPlate(_G.INVTYPE_FINGER),
fingerScale1 = ScalePlate(1),
fingerComment1 = CommentPlate(1),
fingerScale2 = ScalePlate(2),
fingerComment2 = CommentPlate(2),
fingerScale3 = ScalePlate(3),
fingerComment3 = CommentPlate(3),
},
},
trinket = {
order = 32,
type = "group",
name = _G.INVTYPE_TRINKET,
args = {
help = HelpPlate(_G.INVTYPE_TRINKET),
trinketScale1 = ScalePlate(1),
trinketComment1 = CommentPlate(1),
trinketScale2 = ScalePlate(2),
trinketComment2 = CommentPlate(2),
trinketScale3 = ScalePlate(3),
trinketComment3 = CommentPlate(3),
},
},
cloak = {
order = 33,
type = "group",
name = _G.INVTYPE_CLOAK,
args = {
help = HelpPlate(_G.INVTYPE_CLOAK),
cloakScale1 = ScalePlate(1),
cloakComment1 = CommentPlate(1),
cloakScale2 = ScalePlate(2),
cloakComment2 = CommentPlate(2),
cloakScale3 = ScalePlate(3),
cloakComment3 = CommentPlate(3),
},
},
shield = {
order = 34,
type = "group",
name = _G.SHIELDSLOT,
args = {
help = HelpPlate(_G.SHIELDSLOT),
shieldScale1 = ScalePlate(1),
shieldComment1 = CommentPlate(1),
shieldScale2 = ScalePlate(2),
shieldComment2 = CommentPlate(2),
shieldScale3 = ScalePlate(3),
shieldComment3 = CommentPlate(3),
},
},
weapon = {
order = 35,
type = "group",
name = DISPLAY_NAME.OneHWeapon, -- one-handed weapon
args = {
help = HelpPlate(DISPLAY_NAME.OneHWeapon),
weaponScale1 = ScalePlate(1),
weaponComment1 = CommentPlate(1),
weaponScale2 = ScalePlate(2),
weaponComment2 = CommentPlate(2),
weaponScale3 = ScalePlate(3),
weaponComment3 = CommentPlate(3),
},
},
weapon2H = {
order = 36,
type = "group",
name = DISPLAY_NAME.TwoHWeapon,
args = {
help = HelpPlate(DISPLAY_NAME.TwoHWeapon),
weapon2HScale1 = ScalePlate(1),
weapon2HComment1 = CommentPlate(1),
weapon2HScale2 = ScalePlate(2),
weapon2HComment2 = CommentPlate(2),
weapon2HScale3 = ScalePlate(3),
weapon2HComment3 = CommentPlate(3),
},
},
weaponMainH = {
order = 37,
type = "group",
name = DISPLAY_NAME.MainHWeapon,
args = {
help = HelpPlate(DISPLAY_NAME.MainHWeapon),
weaponMainHScale1 = ScalePlate(1),
weaponMainHComment1 = CommentPlate(1),
weaponMainHScale2 = ScalePlate(2),
weaponMainHComment2 = CommentPlate(2),
weaponMainHScale3 = ScalePlate(3),
weaponMainHComment3 = CommentPlate(3),
},
},
weaponOffH = {
order = 38,
type = "group",
name = DISPLAY_NAME.OffHWeapon,
args = {
help = HelpPlate(DISPLAY_NAME.OffHWeapon),
weaponOffHScale1 = ScalePlate(1),
weaponOffHComment1 = CommentPlate(1),
weaponOffHScale2 = ScalePlate(2),
weaponOffHComment2 = CommentPlate(2),
weaponOffHScale3 = ScalePlate(3),
weaponOffHComment3 = CommentPlate(3),
},
},
holdable = {
order = 39,
type = "group",
name = _G.INVTYPE_HOLDABLE, -- Held in Off-Hand
args = {
help = HelpPlate(_G.INVTYPE_HOLDABLE),
holdableScale1 = ScalePlate(1),
holdableComment1 = CommentPlate(1),
holdableScale2 = ScalePlate(2),
holdableComment2 = CommentPlate(2),
holdableScale3 = ScalePlate(3),
holdableComment3 = CommentPlate(3),
},
},
ranged = {
order = 40,
type = "group",
name = _G.INVTYPE_RANGED,
args = {
help = HelpPlate(L["%s, %s, %s"]:format(
LOCAL_NAME.Bow,
LOCAL_NAME.Gun,
LOCAL_NAME.Crossbow)),
rangedScale1 = ScalePlate(1),
rangedComment1 = CommentPlate(1),
rangedScale2 = ScalePlate(2),
rangedComment2 = CommentPlate(2),
rangedScale3 = ScalePlate(3),
rangedComment3 = CommentPlate(3),
},
},
wand = {
order = 41,
type = "group",
name = LOCAL_NAME.Wand,
args = {
help = HelpPlate(LOCAL_NAME.Wand),
wandScale1 = ScalePlate(1),
wandComment1 = CommentPlate(1),
wandScale2 = ScalePlate(2),
wandComment2 = CommentPlate(2),
wandScale3 = ScalePlate(3),
wandComment3 = CommentPlate(3),
},
},
thrown = {
order = 42,
type = "group",
name = LOCAL_NAME.Thrown,
args = {
help = HelpPlate(LOCAL_NAME.Thrown),
thrownScale1 = ScalePlate(1),
thrownComment1 = CommentPlate(1),
thrownScale2 = ScalePlate(2),
thrownComment2 = CommentPlate(2),
thrownScale3 = ScalePlate(3),
thrownComment3 = CommentPlate(3),
},
},
relic = {
order = 43,
type = "group",
name = _G.INVTYPE_RELIC,
args = {
help = HelpPlate(L["%s, %s, %s"]:format(
LOCAL_NAME.Idol, -- 神像
LOCAL_NAME.Libram, -- 圣契
LOCAL_NAME.Totem)),-- 图腾
relicScale1 = ScalePlate(1),
relicComment1 = CommentPlate(1),
relicScale2 = ScalePlate(2),
relicComment2 = CommentPlate(2),
relicScale3 = ScalePlate(3),
relicComment3 = CommentPlate(3),
},
},
-- bag = {
-- order = 100,
-- type = "group",
-- name = _G.INVTYPE_BAG,
-- args = {
-- help = HelpPlate(_G.INVTYPE_BAG),
-- bagScale1 = ScalePlate(1),
-- bagComment1 = CommentPlate(1),
-- bagScale2 = ScalePlate(2),
-- bagComment2 = CommentPlate(2),
-- bagScale3 = ScalePlate(3),
-- bagComment3 = CommentPlate(3),
-- },
-- },
-- Not available in WOW Classic v1.13
-- customMultislotTier = {
-- type = "group",
-- name = _G.INVTYPE_CUSTOM_MULTISLOT_TIER,
-- args = {
-- help = HelpPlate(_G.INVTYPE_CUSTOM_MULTISLOT_TIER),
-- customMultislotTierScale1 = ScalePlate(1),
-- customMultislotTierComment1 = CommentPlate(1),
-- customMultislotTierScale2 = ScalePlate(2),
-- customMultislotTierComment2 = CommentPlate(2),
-- customMultislotTierScale3 = ScalePlate(3),
-- customMultislotTierComment3 = CommentPlate(3),
-- },
-- },
}
local profileOOR = {
enabled = true,
baseGP = 80,
standardIlvl = 66,
ilvlDenominator = 10,
legendaryScale = 3,
headScale1 = 1,
headComment1 = _G.INVTYPE_HEAD,
neckScale1 = 1,
neckComment1 = _G.INVTYPE_NECK,
shoulderScale1 = 1,
shoulderComment1 = _G.INVTYPE_SHOULDER,
-- bodyScale1 = 0,
-- bodyComment1 = _G.INVTYPE_BODY,
chestScale1 = 1,
chestComment1 = _G.INVTYPE_CHEST,
waistScale1 = 1,
waistComment1 = _G.INVTYPE_WAIST,
legsScale1 = 1,
legsComment1 = _G.INVTYPE_LEGS,
feetScale1 = 1,
feetComment1 = _G.INVTYPE_FEET,
wristScale1 = 1,
wristComment1 = _G.INVTYPE_WRIST,
handScale1 = 1,
handComment1 = _G.INVTYPE_HAND,
fingerScale1 = 1,
fingerComment1 = _G.INVTYPE_FINGER,
trinketScale1 = 1.5,
trinketComment1 = _G.INVTYPE_TRINKET,
cloakScale1 = 1,
cloakComment1 = _G.INVTYPE_CLOAK,
weaponScale1 = 1.5,
weaponComment1 = DISPLAY_NAME.MainHWeapon,
weaponScale2 = 0.5,
weaponComment2 = DISPLAY_NAME.OffHWeapon,
weaponScale3 = 0.15,
weaponComment3 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
shieldScale1 = 0.5,
shieldComment1 = _G.SHIELDSLOT,
weapon2HScale1 = 2,
weapon2HComment1 = DISPLAY_NAME.TwoHWeapon,
weapon2HScale2 = 0.3,
weapon2HComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.TwoHWeapon),
weaponMainHScale1 = 1.5,
weaponMainHComment1 = DISPLAY_NAME.MainHWeapon,
weaponMainHScale2 = 0.15,
weaponMainHComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
weaponOffHScale1 = 0.5,
weaponOffHComment1 = DISPLAY_NAME.OffHWeapon,
weaponOffHScale2 = 0.15,
weaponOffHComment2 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, DISPLAY_NAME.OneHWeapon),
holdableScale1 = 0.5,
holdableComment1 = _G.INVTYPE_HOLDABLE,
rangedScale1 = 2,
rangedComment1 = L["%s %s"]:format(_G.LOCALIZED_CLASS_NAMES_MALE.HUNTER, _G.INVTYPE_RANGED),
rangedScale2 = 0.3,
rangedComment2 = L["%s %s"]:format(L["Non-hunter"], _G.INVTYPE_RANGED),
wandScale1 = 0.3,
wandComment1 = LOCAL_NAME.Wand,
thrownScale1 = 0.3,
thrownComment1 = LOCAL_NAME.Thrown,
relicScale1 = 0.3,
relicComment1 = _G.INVTYPE_RELIC,
-- bagScale1 = 0,
-- bagComment1 = _G.INVTYPE_BAG,
}
function mod:CheckGuildConfig(guild, realm)
-- if guild == "Order Of Rhonin" and realm == "艾隆纳亚" then
-- Utils:CopyTable(profileOOR, mod.db.profile)
-- end
end
function mod:OnInitialize()
self.db = EPGP.db:RegisterNamespace("points", mod.dbDefaults)
end
|
local ThrottleLayer = require(script.Parent.ThrottleLayer)
local Error = require(script.Parent.Parent.Error)
local RetryLayer = {}
function RetryLayer._retry(callback, ...)
local attempts = 0
while attempts < 5 do
attempts = attempts + 1
local ok, value = pcall(callback, ...)
if ok then
return value
end
if attempts < 5 then
warn(("[Quicksave] DataStore operation failed. Retrying...\nError:\n%s"):format(
tostring(value)
))
else
error(Error.new({
kind = Error.Kind.DataStoreError,
error = value,
context = "Failed after 5 retries."
}))
end
end
end
function RetryLayer.update(...)
return RetryLayer._retry(function(...)
return ThrottleLayer.update(...)
end, ...)
end
function RetryLayer.read(...)
return RetryLayer._retry(function(...)
return ThrottleLayer.read(...)
end, ...)
end
return RetryLayer |
-- graphics.lua --
-- This file simply loads a few extra bitmaps and creates a new wallset.
gfx.bluehaze = dsb_get_bitmap("ALPHAHAZE")
gfx.redfloor = dsb_get_bitmap("REDFLOOR")
gfx.redroof = dsb_get_bitmap("REDROOF")
wallset.redfloor = dsb_make_wallset_ext(gfx.redfloor, gfx.redroof, gfx.pers0, gfx.pers0alt,
gfx.pers1, gfx.pers1alt, gfx.pers2, gfx.pers2alt, gfx.pers3, gfx.pers3alt,
gfx.farwall3, gfx.farwall3alt, gfx.front1, gfx.front2, gfx.front3,
gfx.left1, gfx.left1alt, gfx.left2, gfx.left2alt, gfx.left3, gfx.left3alt, gfx.wallwindow)
-- Use a player color bitmap
gfx.bright_green = dsb_get_bitmap("BRIGHT_GREEN")
player_colors[1] = gfx.bright_green |
arr = {1, 2}
print (arr[0]) - nil
print (arr[1]) - 0
print (arr[2]) - 1
|
require "class"
local ScriptErrorScreen = require "screens/scripterrorscreen"
require "modutil"
require "prefabs"
MOD_API_VERSION = 6
local function modprint(...)
--print(unpack({...}))
end
local runmodfn = function(fn,mod,modtype)
return (function(...)
if fn then
local status, r = xpcall( function() return fn(unpack(arg)) end, debug.traceback)
if not status then
print("error calling "..modtype.." in mod "..ModInfoname(mod.modname)..": \n"..r)
ModManager:RemoveBadMod(mod.modname,r)
ModManager:DisplayBadMods()
else
return r
end
end
end)
end
ModWrangler = Class(function(self)
self.modnames = {}
self.mods = {}
self.records = {}
self.failedmods = {}
self.enabledmods = {}
self.loadedprefabs = {}
end)
function ModWrangler:GetEnabledModNames()
return self.enabledmods
end
function ModWrangler:GetMod(modname)
for i,mod in ipairs(self.mods) do
if mod.modname == modname then
return mod
end
end
end
function ModWrangler:SetModRecords(records)
self.records = records
for mod,record in pairs(self.records) do
if table.contains(self.enabledmods, mod) then
record.active = true
else
record.active = false
end
end
for i,mod in ipairs(self.enabledmods) do
if not self.records[mod] then
self.records[mod] = {}
self.records[mod].active = true
end
end
end
function ModWrangler:GetModRecords()
return self.records
end
function CreateEnvironment(modname, isworldgen)
local modutil = require("modutil")
require("recipe") -- for Ingredient
local env =
{
TUNING=TUNING,
modname = modname,
pairs = pairs,
ipairs = ipairs,
print = print,
math = math,
table = table,
type = type,
string = string,
tostring = tostring,
Class = Class,
GLOBAL = _G,
MODROOT = "../mods/"..modname.."/",
Prefab = Prefab,
Asset = Asset,
Ingredient = Ingredient,
MODCONFIG = KnownModIndex:GetModConfigurationOptions(modname) or {}, -- Direct access to the mod config table (WARNING: modifying it directly while the game is running could result in weird behavior)
GetModConfigData = GetModConfigDataFn(modname) -- Call is GetModConfigData(optionname) to fetch saved value of the specified option (name must match name field in config options table)
}
if isworldgen == false then
env.CHARACTERLIST = GetActiveCharacterList()
end
env.env = env
--install our crazy loader!
env.modimport = function(modulename)
print("modimport: "..env.MODROOT..modulename)
local result = kleiloadlua(env.MODROOT..modulename)
if result == nil then
error("Error in modimport: "..modulename.." not found!")
elseif type(result) == "string" then
error("Error in modimport: "..ModInfoname(modname).." importing "..modulename.."!\n"..result)
else
setfenv(result, env.env)
result()
end
end
modutil.InsertPostInitFunctions(env)
return env
end
function ModWrangler:LoadMods(worldgen)
if not MODS_ENABLED then
return
end
self.worldgen = worldgen or false
if not worldgen then
KnownModIndex:UpdateModInfo()
end
local moddirs = KnownModIndex:GetModsToLoad(self.worldgen)
for i,modname in ipairs(moddirs) do
if self.worldgen == false or (self.worldgen == true and KnownModIndex:IsModCompatibleWithMode(modname)) then
table.insert(self.modnames, modname)
if self.worldgen == false then
-- Make sure we load the config data before the mod (but not during worldgen)
KnownModIndex:LoadModConfigurationOptions(modname)
end
local initenv = KnownModIndex:GetModInfo(modname)
local env = CreateEnvironment(modname, self.worldgen)
env.modinfo = initenv
table.insert( self.mods, env )
local loadmsg = "Loading mod: "..ModInfoname(modname)
if initenv.modinfo_message and initenv.modinfo_message ~= "" then
loadmsg = loadmsg .. " ("..initenv.modinfo_message..")"
end
print(loadmsg)
end
end
-- Sort the mods by priority, so that "library" mods can load first
local function modPrioritySort(a,b)
local apriority = (a.modinfo and a.modinfo.priority) or 0
local bpriority = (b.modinfo and b.modinfo.priority) or 0
return apriority > bpriority
end
table.sort(self.mods, modPrioritySort)
for i,mod in ipairs(self.mods) do
table.insert(self.enabledmods, mod.modname)
package.path = "..\\mods\\"..mod.modname.."\\scripts\\?.lua;"..package.path
self:InitializeModMain(mod.modname, mod, "modworldgenmain.lua")
if not self.worldgen then
-- worldgen has to always run (for customization screen) but modmain can be
-- skipped for worldgen. This reduces a lot of issues with missing globals.
self:InitializeModMain(mod.modname, mod, "modmain.lua")
end
end
end
function ModWrangler:InitializeModMain(modname, env, mainfile)
if not KnownModIndex:IsModCompatibleWithMode(modname) then return end
print("Mod: "..ModInfoname(modname), "Loading "..mainfile)
local fn = kleiloadlua("../mods/"..modname.."/"..mainfile)
if type(fn) == "string" then
print("Mod: "..ModInfoname(modname), " Error loading mod!\n"..fn.."\n")
table.insert( self.failedmods, {name=modname,error=fn} )
return false
elseif not fn then
print("Mod: "..ModInfoname(modname), " Mod had no "..mainfile..". Skipping.")
return true
else
local status, r = RunInEnvironment(fn,env)
if status == false then
print("Mod: "..ModInfoname(modname), " Error loading mod!\n"..r.."\n")
table.insert( self.failedmods, {name=modname,error=r} )
return false
else
-- the env is an "out reference" so we're done here.
return true
end
end
end
function ModWrangler:RemoveBadMod(badmodname,error)
KnownModIndex:DisableBecauseBad(badmodname)
table.insert( self.failedmods, {name=badmodname,error=error} )
end
function ModWrangler:DisplayBadMods()
if self.worldgen then
-- we can't save or show errors from worldgen! Up to the main game to display the error.
for k,badmod in ipairs(self.failedmods) do
local errormsg = badmod.error
error(errormsg)
end
return
end
-- If the frontend isn't ready yet, just hold onto this until we can display it.
if #self.failedmods > 0 then
for i,failedmod in ipairs(self.failedmods) do
KnownModIndex:DisableBecauseBad(failedmod.name)
self:GetMod(failedmod.name).modinfo.failed = true
print("Disabling "..ModInfoname(failedmod.name).." because it had an error.")
end
end
-- There are several flows which may have disabled mods; now is a safe place to save those changes.
KnownModIndex:Save()
if TheFrontEnd then
for k,badmod in ipairs(self.failedmods) do
TheFrontEnd:DisplayError(
ScriptErrorScreen(
STRINGS.UI.MAINSCREEN.MODFAILTITLE,
STRINGS.UI.MAINSCREEN.MODFAILDETAIL.." "..KnownModIndex:GetModFancyName(badmod.name).."\n"..badmod.error.."\n",
{
{text=STRINGS.UI.MAINSCREEN.SCRIPTERRORQUIT, cb = function() TheSim:ForceAbort() end},
{text=STRINGS.UI.MAINSCREEN.MODQUIT, cb = function()
KnownModIndex:DisableAllMods()
KnownModIndex:Save(function()
SimReset()
end)
end},
{text=STRINGS.UI.MAINSCREEN.MODFORUMS, nopop=true, cb = function() VisitURL("http://forums.kleientertainment.com/index.php?/forum/26-dont-starve-mods-and-tools/") end }
},
ANCHOR_LEFT,
STRINGS.UI.MAINSCREEN.MODFAILDETAIL2,
20
))
end
self.failedmods = {}
end
end
function ModWrangler:RegisterPrefabs()
if not MODS_ENABLED then
return
end
for i,modname in ipairs(self.enabledmods) do
local mod = self:GetMod(modname)
mod.LoadPrefabFile = LoadPrefabFile
mod.RegisterPrefabs = RegisterPrefabs
mod.Prefabs = {}
print("Mod: "..ModInfoname(mod.modname), "Registering prefabs")
-- We initialize the prefabs in the sandbox and collect all the created prefabs back
-- into the main world.
if mod.PrefabFiles then
for i,prefab_path in ipairs(mod.PrefabFiles) do
print("Mod: "..ModInfoname(mod.modname), " Registering prefab file: prefabs/"..prefab_path)
local ret = runmodfn( mod.LoadPrefabFile, mod, "LoadPrefabFile" )("prefabs/"..prefab_path)
if ret then
for i,prefab in ipairs(ret) do
print("Mod: "..ModInfoname(mod.modname), " "..prefab.name)
mod.Prefabs[prefab.name] = prefab
end
end
end
end
local prefabnames = {}
for name, prefab in pairs(mod.Prefabs) do
table.insert(prefabnames, name)
Prefabs[name] = prefab -- copy the prefabs back into the main environment
end
print("Mod: "..ModInfoname(mod.modname), " Registering default mod prefab")
RegisterPrefabs( Prefab("modbaseprefabs/MOD_"..mod.modname, nil, mod.Assets, prefabnames) )
local modname = "MOD_"..mod.modname
TheSim:LoadPrefabs({modname})
table.insert(self.loadedprefabs, modname)
end
end
function ModWrangler:UnloadPrefabs()
for i, modname in ipairs( self.loadedprefabs ) do
print("unloading prefabs for mod "..ModInfoname(modname))
TheSim:UnloadPrefabs({modname})
end
end
function ModWrangler:SetPostEnv()
local moddetail = ""
--print("\n\n---MOD INFO SCREEN---\n\n")
local modnames = ""
local newmodnames = ""
local oldmodnames = ""
local failedmodnames = ""
local forcemodnames = ""
if #self.mods > 0 then
for i,mod in ipairs(self.mods) do
modprint("###"..mod.modname)
--dumptable(mod.modinfo)
if KnownModIndex:IsModNewlyBad(mod.modname) then
modprint("@NEWLYBAD")
failedmodnames = failedmodnames.."\""..KnownModIndex:GetModFancyName(mod.modname).."\" "
elseif KnownModIndex:IsModNewlyOld(mod.modname) and KnownModIndex:WasModEnabled(mod.modname) then
modprint("@NEWLYOLD")
oldmodnames = oldmodnames.."\""..KnownModIndex:GetModFancyName(mod.modname).."\" "
--elseif KnownModIndex:IsModNew(mod.modname) then
--print("@NEW")
--newmodnames = newmodnames.."\""..KnownModIndex:GetModFancyName(mod.modname).."\" "
--end
elseif KnownModIndex:IsModForceEnabled(mod.modname) then
modprint("@FORCEENABLED")
mod.TheFrontEnd = TheFrontEnd
mod.TheSim = TheSim
mod.Point = Point
mod.TheGlobalInstance = TheGlobalInstance
for i,modfn in ipairs(mod.postinitfns.GamePostInit) do
runmodfn( modfn, mod, "gamepostinit" )()
end
forcemodnames = forcemodnames.."\""..KnownModIndex:GetModFancyName(mod.modname).."\" "
elseif KnownModIndex:IsModEnabled(mod.modname) then
modprint("@ENABLED")
mod.TheFrontEnd = TheFrontEnd
mod.TheSim = TheSim
mod.Point = Point
mod.TheGlobalInstance = TheGlobalInstance
for i,modfn in ipairs(mod.postinitfns.GamePostInit) do
runmodfn( modfn, mod, "gamepostinit" )()
end
modnames = modnames.."\""..KnownModIndex:GetModFancyName(mod.modname).."\" "
else
modprint("@DISABLED")
end
end
end
--print("\n\n---END MOD INFO SCREEN---\n\n")
if oldmodnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.OLDMODS.." "..oldmodnames.."\n"
end
if failedmodnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.FAILEDMODS.." "..failedmodnames.."\n"
end
if oldmodnames ~= "" or failedmodnames ~= "" then
moddetail = moddetail..STRINGS.UI.MAINSCREEN.OLDORFAILEDMODS.."\n\n"
end
if newmodnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.NEWMODDETAIL.." "..newmodnames.."\n"..STRINGS.UI.MAINSCREEN.NEWMODDETAIL2.."\n\n"
end
if modnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.MODDETAIL.." "..modnames.."\n\n"
end
if newmodnames ~= "" or modnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.MODDETAIL2.."\n\n"
end
if forcemodnames ~= "" then
moddetail = moddetail.. STRINGS.UI.MAINSCREEN.FORCEMODDETAIL.." "..forcemodnames.."\n\n"
end
if (modnames ~= "" or newmodnames ~= "" or oldmodnames ~= "" or failedmodnames ~= "" or forcemodnames ~= "") and TheSim:ShouldWarnModsLoaded() then
--if (#self.enabledmods > 0) and TheSim:ShouldWarnModsLoaded() then
TheFrontEnd:PushScreen(
ScriptErrorScreen(
STRINGS.UI.MAINSCREEN.MODTITLE,
moddetail,
{
{text=STRINGS.UI.MAINSCREEN.TESTINGYES, cb = function() TheFrontEnd:PopScreen() end},
{text=STRINGS.UI.MAINSCREEN.MODQUIT, cb = function()
KnownModIndex:DisableAllMods()
KnownModIndex:Save(function()
SimReset()
end)
end},
{text=STRINGS.UI.MAINSCREEN.MODFORUMS, nopop=true, cb = function() VisitURL("http://forums.kleientertainment.com/index.php?/forum/26-dont-starve-mods-and-tools/") end }
}))
elseif KnownModIndex:WasLoadBad() then
TheFrontEnd:PushScreen(
ScriptErrorScreen(
STRINGS.UI.MAINSCREEN.MODSBADTITLE,
STRINGS.UI.MAINSCREEN.MODSBADLOAD,
{
{text=STRINGS.UI.MAINSCREEN.TESTINGYES, cb = function() TheFrontEnd:PopScreen() end},
{text=STRINGS.UI.MAINSCREEN.MODFORUMS, nopop=true, cb = function() VisitURL("http://forums.kleientertainment.com/index.php?/forum/26-dont-starve-mods-and-tools/") end }
}))
end
self:DisplayBadMods()
end
function ModWrangler:SimPostInit(wilson)
for i,modname in ipairs(self.enabledmods) do
local mod = self:GetMod(modname)
for i,modfn in ipairs(mod.postinitfns.SimPostInit) do
runmodfn( modfn, mod, "simpostinit" )(wilson)
end
end
self:DisplayBadMods()
end
function ModWrangler:GetPostInitFns(type, id)
local retfns = {}
for i,modname in ipairs(self.enabledmods) do
local mod = self:GetMod(modname)
if mod.postinitfns[type] then
local modfns = nil
if id then
modfns = mod.postinitfns[type][id]
else
modfns = mod.postinitfns[type]
end
if modfns ~= nil then
for i,modfn in ipairs(modfns) do
--print(modname, "added modfn "..type.." for "..tostring(id))
table.insert(retfns, runmodfn(modfn, mod, id and type..": "..id or type))
end
end
end
end
return retfns
end
function ModWrangler:GetPostInitData(type, id)
local moddata = {}
for i,modname in ipairs(self.enabledmods) do
local mod = self:GetMod(modname)
if mod.postinitdata[type] then
local data = nil
if id then
data = mod.postinitdata[type][id]
else
data = mod.postinitdata[type]
end
if data ~= nil then
--print(modname, "added moddata "..type.." for "..tostring(id))
table.insert(moddata, data)
end
end
end
return moddata
end
ModManager = ModWrangler()
---------------------------------------------
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local EzSpec = require(ReplicatedStorage.EzSpec)
EzSpec.runTests({
directories = {
script.Parent.Specs;
};
-- ignoreNames = {
-- "ThisWillFailToRequire";
-- "DeclareExamples";
-- };
includeDescendants = true;
-- verboseLogging = true;
-- showOnlyFailures = true;
-- showExecutionTime = true;
-- useEmojis = false;
})
|
ITEM.name = "Заряд РС-15"
ITEM.desc = "Самодельное взрывное устройство, полученное из различных химических веществ, забитых в контейнер с металлическими шариками и со сломанным электрическим воспламенителем. Активируется автоматически. \n\nХАРАКТЕРИСТИКИ: \n-взрывоопасно \n-военное изделие \n\nДля активации необходимо выложить"
ITEM.category = "Комфорт"
ITEM.price = 6940
ITEM.exRender = false
ITEM.weight = 1.25
ITEM.model = "models/kek1ch/bomb_c4.mdl"
ITEM.width = 2
ITEM.height = 2
ITEM.iconCam = {
pos = Vector(0, 0, 200),
ang = Angle(90, 0, 0),
fov = 4.7
}
ITEM.functions.Use = {
name = "установить",
icon = "icon16/cup.png",
onRun = function(item)
local client = item.player
local mine = ents.Create("mine")
local data = {
start = client:GetShootPos(),
endpos = client:GetShootPos() + client:GetAimVector() * 95,
filter = client
}
local trace = util.TraceLine(data)
if (!trace.Hit or trace.HitSky) then return false end
mine:SetPos(trace.HitPos)
mine:Spawn()
mine:Activate()
mine:EmitSound("physics/flesh/flesh_impact_hard6.wav")
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
} |
--[[lit-meta
name = 'voronianski/match-path'
description = 'Express.js style path matching for Luvit.io servers'
version = '1.0.0'
homepage = 'https://github.com/luvitrocks/http-utils'
repository = {
url = 'http://github.com/luvitrocks/http-utils.git'
}
tags = {'http', 'path', 'route', 'router', 'path-to-regexp', 'server', 'utopia', 'utopia-route'}
author = {
name = 'Dmitri Voronianski',
email = 'dmitri.voronianski@gmail.com'
}
license = 'MIT'
]]
local quotepattern = '([' .. ('%^$().[]*+-?'):gsub('(.)', '%%%1') .. '])'
function escape(str)
return str:gsub(quotepattern, '%%%1')
end
function compilePath (path)
local parts = {'^'}
local names = {}
for a, b, c, d in path:gmatch('([^:]*):([_%a][_%w]*)(:?)([^:]*)') do
if #a > 0 then
parts[#parts + 1] = escape(a)
end
if #c > 0 then
parts[#parts + 1] = '(.*)'
else
parts[#parts + 1] = '([^/]*)'
end
names[#names + 1] = b
if #d > 0 then
parts[#parts + 1] = escape(d)
end
end
if #parts == 1 then
return function (str)
if str == path then
return {}
end
end
end
parts[#parts + 1] = '$'
local pattern = table.concat(parts)
function getParams (str)
local matches = { str:match(pattern) }
if #matches > 0 then
local results = {}
for i = 1, #matches do
results[names[i]] = matches[i]
end
return results
end
end
return getParams
end
exports.compile = compilePath
|
local M = {}
local tree = {
disable_netrw = true,
hijack_netrw = true,
open_on_setup = false,
ignore_ft_on_setup = {},
auto_close = false,
open_on_tab = false,
hijack_cursor = false,
update_cwd = false,
update_to_buf_dir = {
enable = true,
auto_open = true,
},
diagnostics = {
enable = false,
icons = {
hint = "",
info = "",
warning = "",
error = "",
}
},
update_focused_file = {
enable = false,
update_cwd = false,
ignore_list = {}
},
system_open = {
cmd = nil,
args = {}
},
filters = {
dotfiles = false,
custom = {}
},
git = {
enable = true,
ignore = true,
timeout = 500,
},
view = {
width = 30,
height = 30,
hide_root_folder = false,
side = 'left',
auto_resize = false,
mappings = {
custom_only = false,
list = {}
},
number = false,
relativenumber = false,
signcolumn = "yes"
},
trash = {
cmd = "trash",
require_confirm = true
}
}
M.setup = function()
nvim-tree = require 'nvim-tree'
nvim-tree.setup(tree)
end
return M
|
-- List of all groups
groups = {
"general",
"globals",
"default"
}
for k,v in ipairs(groups) do
CreateGroup(v)
end
|
util.AddNetworkString("nutTransferItem")
local TRANSFER = "transfer"
function PLUGIN:HandleItemTransferRequest(client, itemID, x, y, invID)
-- Get the item that should be moved, its inventory, and the destination.
local inventory = nut.inventory.instances[invID]
local item = nut.item.instances[itemID]
if (not item) then return end
local oldInventory = nut.inventory.instances[item.invID]
if (not oldInventory or not oldInventory.items[itemID]) then
return
end
-- Make sure the item is permitted to move between the two inventories.
local status,reason = hook.Run("CanItemBeTransfered", item, oldInventory, inventory, client)
if (status == false) then client:notify(reason or "You can't do that right now.") return end
local context = {
client = client,
item = item,
from = oldInventory,
to = inventory
}
local canTransfer, reason = oldInventory:canAccess(TRANSFER, context)
if (not canTransfer) then
return
end
if (not inventory) then
return hook.Run("ItemDraggedOutOfInventory", client, item)
end
canTransfer, reason = inventory:canAccess(TRANSFER, context)
if (not canTransfer) then
if (isstring(reason)) then
client:notifyLocalized(reason)
end
return
end
-- If valid, remove the item from its current inventory and put it in
-- the other inventory. If something fails, just drop the item in the world.
local oldX, oldY = item:getData("x"), item:getData("y")
local failItemDropPos = client:getItemDropPos()
if (client.invTransferTransaction and client.invTransferTransactionTimeout > RealTime()) then
return
end
client.invTransferTransaction = true
client.invTransferTransactionTimeout = RealTime()
local function fail(err)
client.invTransferTransaction = nil
if (err) then
print(err)
debug.Trace()
end
if (IsValid(client)) then
client:notifyLocalized("itemOnGround")
end
item:spawn(failItemDropPos)
end
local tryCombineWith
local originalAddRes
return oldInventory:removeItem(itemID, true)
:next(function()
return inventory:add(item, x, y)
end)
:next(function(res)
if (not res or not res.error) then return end
-- If the item was dropped on another item, then "combine" them.
-- This is subject to how the target item defines "combine".
local conflictingItem = istable(res.error) and res.error.item
if (conflictingItem) then
tryCombineWith = conflictingItem
end
originalAddRes = res
return oldInventory:add(item, oldX, oldY)
end)
:next(function(res)
if (res and res.error) then return res end
if (tryCombineWith and IsValid(client)) then
if (hook.Run("ItemCombine", client, item, tryCombineWith)) then
return
end
end
end)
:next(function(res)
client.invTransferTransaction = nil
if (res and res.error) then
fail()
else
hook.Run("ItemTransfered", context)
end
return originalAddRes
end)
:catch(fail)
end
net.Receive("nutTransferItem", function(_, client)
local itemID = net.ReadUInt(32)
local x = net.ReadUInt(32)
local y = net.ReadUInt(32)
local invID = net.ReadType()
hook.Run("HandleItemTransferRequest", client, itemID, x, y, invID)
end)
|
-- Pause when Minimize
-- This script pauses playback when minimizing the window, and resumes playback
-- if it's brought back again. If the player was already paused when minimizing,
-- then try not to mess with the pause state.
local did_minimize = false
mp.observe_property("window-minimized", "bool", function(name, value)
local pause = mp.get_property_native("pause")
if value then
if not pause then
mp.set_property_native("pause", true)
did_minimize = true
end
elseif not value then
if did_minimize and pause then
mp.set_property_native("pause", false)
end
did_minimize = false
end
end)
|
GM.Name = "Prop Hunt"
GM.Author = "MrGrim48"
GM.Email = "N/A"
GM.Website = "N/A"
include( "module_loader.lua" )
-- Load Modules
Loader.Load( "playerclass" )
Loader.Load( "core" )
Loader.Load( "modules" ) |
--[[
Calls the given function if it actually exists.
Useful in Roact components where a callback passed as a prop is optional, so
you don't always know if you want to run it.
Usage:
maybeCall(nil) -- does nothing
maybeCall(function()
print("Hello!") -- prints hello
end)
]]
local t = require(script.Parent.Parent.lib.t)
local maybeCallCheck = t.union(t.callback, t.none)
local function maybeCall(callback, ...)
assert(maybeCallCheck(callback))
if type(callback) == "function" then
return callback(...)
end
end
return maybeCall
|
local MSG = "[ ] FAILED proxy tests"
local a = newproxy(false)
assert(getmetatable(a) == nil, MSG)
local b = newproxy(true)
local mt = getmetatable(b)
assert(mt ~= nil, MSG)
assert(not pcall(setmetatable, b, {}), MSG)
mt.__metatable = "The metatable is locked"
assert(getmetatable(b) ~= mt, MSG)
assert(not pcall(function()
return b + b
end), MSG)
mt.__add = function(x, y)
assert(x == y, MSG)
return "asd"
end
assert(b + b == "asd", MSG)
local c = newproxy(b)
assert(not pcall(function() return b + c end), MSG)
assert(c + c == "asd", MSG)
assert(getmetatable(c) == getmetatable(b), MSG)
assert(not pcall(newproxy, 1), MSG)
assert(not pcall(newproxy, a), MSG)
assert(pcall(newproxy, nil), MSG)
assert(pcall(newproxy), MSG)
assert(pcall(newproxy, true), MSG)
assert(pcall(newproxy, false), MSG)
assert(pcall(newproxy, b), MSG)
assert(pcall(newproxy, c), MSG)
print("[X] passed proxy tests") |
-- Copyright (c) Jérémie N'gadi
--
-- All rights reserved.
--
-- Even if 'All rights reserved' is very clear :
--
-- You shall not use any piece of this software in a commercial product / service
-- You shall not resell this software
-- You shall not provide any facility to install this particular software in a commercial product / service
-- If you redistribute this software, you must link to ORIGINAL repository at https://github.com/ESX-Org/es_extended
-- This copyright should appear in every part of the project code
Translations = {
['skin_menu'] = 'ulkonäkö',
['use_rotate_view'] = 'paina ~INPUT_VEH_FLY_ROLL_LEFT_ONLY~ tai ~INPUT_VEH_FLY_ROLL_RIGHT_ONLY~ liikutaaksesi kameraa.',
['skin'] = 'vaihda ulkonäköä',
['saveskin'] = 'talleta ulkonäkö tiedostoon',
['skin_saved'] = 'Skin saved successfully',
}
|
package.path = package.path..";src/?.lua"
local mgl = require("MGL")
mgl.gen_mat(2); mgl.gen_vec(2)
mgl.gen_mat(3); mgl.gen_vec(3)
mgl.gen_mat(4); mgl.gen_vec(4)
-- build model matrix
local m = mgl.translate(mgl.vec3(0,0,10)) --
* mgl.rotate(mgl.vec3(1,0,0), -math.pi/2) --
* mgl.scale(mgl.vec3(2))
local invm = mgl.inverse(m)
local p = mgl.vec3(0,0,1)
local pp = m*mgl.vec4(p,1)
assert(mgl.vec3(pp) == mgl.vec3(0,2,10))
local ppi = invm*pp
assert(mgl.length(mgl.vec3(ppi)-p) < 1e-6)
local ortho = mgl.orthographic(0,10,0,10,0,10)
assert(ortho*mgl.vec4(5,5,-5,1) == mgl.vec4(0,0,0,1))
local persp = mgl.perspective(math.rad(90), 16/9, 1, 10)
local proj = persp*mgl.vec4(0,0,-5,1)
proj = proj/proj.w
assert(mgl.length(proj-mgl.vec4(0,0,0.5,1)) < 0.3)
local proji = mgl.inverse(persp)*proj
proji = proji/proji.w
assert(mgl.length(proji-mgl.vec4(0,0,0.5,1)) < 1e6)
print("m")
print(m)
print("invm")
print(invm)
print("p", p)
print("pp", pp)
print("ppi", ppi)
print("ortho")
print(ortho)
print("persp")
print(persp)
|
local PAC = PersonalAssistant.Constants
local PAStrings = {
-- =================================================================================================================
-- Language specific texts that need to be translated --
-- Welcome Messages --
SI_PA_WELCOME_NO_SUPPORT = "à votre service ! - La traduction pour le language [%s] n'est pas (encore) disponible",
SI_PA_WELCOME_SUPPORT = "à votre service !",
SI_PA_WELCOME_PLEASE_SELECT_PROFILE = table.concat({"vous souhaite la bienvenue ! Pour commencer, veuillez aller dans les réglages d'extensions afin de sélectionner un profil. Merci :-)"}),
-- =================================================================================================================
-- == MENU/PANEL TEXTS == --
-- -----------------------------------------------------------------------------------------------------------------
SI_PA_MENU_GENERAL_DESCRIPTION = "PersonalAssistant est un ensemble de fonctionnalités diverses qui ont pour but de vous rendre le jeu ESO plus agréable",
-- -----------------------------------------------------------------------------------------------------------------
-- General Settings --
SI_PA_MENU_GENERAL_HEADER = "Paramètres généraux",
SI_PA_MENU_GENERAL_SHOW_WELCOME = "Afficher le message d'accueil",
SI_PA_MENU_GENERAL_TELEPORT_HEADER = "Habitations",
SI_PA_MENU_GENERAL_TELEPORT_PRIMARY_HOUSE = table.concat({PAC.ICONS.OTHERS.HOME.NORMAL, " Aller à la maison"}),
SI_PA_MENU_GENERAL_TELEPORT_PRIMARY_HOUSE_W = "Si la position actuelle permet un voyage rapide, cela lancera la téléportation vers votre maison primaire !",
--SI_PA_MENU_GENERAL_TELEPORT_OUTSIDE = "",
--SI_PA_MENU_GENERAL_TELEPORT_OUTSIDE_T = "",
-- -----------------------------------------------------------------------------------------------------------------
-- Admin Settings --
SI_PA_MENU_ADMIN_HEADER = "Paramètres administrateur",
}
for key, value in pairs(PAStrings) do
SafeAddString(_G[key], value, 1)
end
|
local Pnml = require "petrinet.pnml"
local Yaml = require "yaml"
local function show (pn)
local result = pn.analysis ()
local ps = {}
local ts = {}
for _, place in ipairs (pn.places) do
ps [place.name] = {
initial = place.initial,
bound = place.bound,
}
end
for _, transition in ipairs (pn.transitions) do
ts [transition.name] = transition.liveness
end
print (Yaml.dump {
durations = {
reachability = result.reachability.duration,
bound = result.bound.duration,
liveness = result.liveness.duration,
},
markings = {
size = result.reachability.size,
},
bound = ps,
liveness = ts,
})
end
for _, what in ipairs { "petrinet" --[[, "petrinet.struct"]] } do
local Petrinet = require (what)
describe ("#" .. what, function ()
it ("works", function ()
local pn = Petrinet {
p1 = {
type = "place",
initial = 1,
},
p2 = {
type = "place",
initial = 0,
},
t = {
type = "transition",
pre = {
p1 = 1,
},
post = {
p2 = 1,
},
},
}
assert (pn.initial + pn.empty == pn.initial)
assert (pn.initial - pn.empty == pn.initial)
assert (pn.initial + pn.initial == pn.marking { p1 = 2 })
assert (pn.initial:t () == pn.marking { p2 = 1 })
local result = pn.analysis ()
assert (result.reachability.size == 2, result.reachability.size)
end)
it ("loads models", function ()
local model = Pnml "models/dekker-10.pnml"
local pn = Petrinet (model)
local result = pn.analysis ()
assert (result.reachability.size == 6144, result.reachability.size)
end)
it ("loads models", function ()
local model = Pnml "models/G-PPP-1-1.pnml"
local pn = Petrinet (model)
local result = pn.analysis ()
assert (result.reachability.size == 10380, result.reachability.size)
end)
it ("works also with #Philosophers", function ()
local n = 10
local data = {}
for i = 1, n do
local id = tostring (i)
data ["fork-" .. id] = {
type = "place",
initial = 1,
}
data ["thinking-" .. id] = {
type = "place",
initial = 1,
}
data ["waiting-" .. id] = {
type = "place",
initial = 0,
}
data ["eating-" .. id] = {
type = "place",
initial = 0,
}
end
for i = 1, n do
local id = tostring (i)
local next = tostring (i < n and i + 1 or 1)
data ["t1-" .. id] = {
type = "transition",
pre = {
["fork-" .. id] = 1,
["thinking-" .. id] = 1,
},
post = {
["waiting-" .. id] = 1,
},
}
data ["t2-" .. id] = {
type = "transition",
pre = {
["waiting-" .. id ] = 1,
["fork-" .. next] = 1,
},
post = {
["eating-" .. id ] = 1,
},
}
data ["t3-" .. id] = {
type = "transition",
pre = {
["eating-" .. id ] = 1,
},
post = {
["fork-" .. id ] = 1,
["fork-" .. next] = 1,
["thinking-" .. id ] = 1,
},
}
end
-- local profi = require 'profi'
-- profi:start()
local pn = Petrinet (data)
local result = pn.analysis ()
-- profi:stop()
-- profi:writeReport ("report.txt")
assert (result.reachability.size == 6726, result.reachability.size)
end)
it ("can analyze liveness", function ()
local pn = Petrinet {
p1 = {
type = "place",
initial = 1,
},
p2 = {
type = "place",
initial = 0,
},
t1 = {
type = "transition",
pre = {
p1 = 1,
},
post = {
p2 = 1,
},
},
t2 = {
type = "transition",
pre = {
p2 = 1,
},
post = {
p1 = 1,
},
},
}
local result = pn.analysis ()
assert (result.reachability.size == 2, result.reachability.size)
end)
end)
end
|
—- enable semantic highlighting
_SEMANATIC = true
-- semantic highlighting. NEED base16 themes to work!
events.connect(events.LEXER_LOADED, function (lang)
if _SEMANATIC == false then return end
buffer.edge_colour = buffer.property_int[“color.base0A”]
buffer.property[‘style.operator’] = ‘fore:%(color.base0F)’
buffer.property[‘style.function’] = ‘fore:%(color.base08)’
buffer.property[‘style.library’] = ‘fore:%(color.base09)’
buffer.property[‘style.identifier’] = ‘fore:%(color.base0D)’
buffer.property[‘style.number’] = ‘fore:%(color.base0E)’
buffer.property[‘style.constant’] = ‘fore:%(color.base0A)’
buffer.property[‘style.keyword’] = ‘fore:%(color.base05)’
end)
|
workspace "LiquidEngine"
basedir "../workspace/"
language "C++"
cppdialect "C++17"
architecture "x86_64"
-- Set editor as starting project
startproject "Liquidator"
setupLibraryDirectories{}
setupPlatformDefines{}
linkPlatformLibraries{}
setupToolsetOptions{}
includedirs {
"../engine/src",
"../engine/rhi/core/include",
"../engine/rhi/vulkan/include",
"../engine/platform-tools/include"
}
configurations { "Debug", "Release", "Profile-Debug", "Profile-Release" }
filter { "toolset:msc-*" }
flags { "FatalCompileWarnings" }
filter {"configurations:Debug or configurations:Profile-Debug"}
defines { "LIQUID_DEBUG" }
symbols "On"
filter {"configurations:Release or configurations:Profile-Release"}
defines { "LIQUID_RELEASE" }
optimize "On"
filter {"configurations:Profile-Debug or configurations:Profile-Release"}
defines { "LIQUID_PROFILER" }
|
local ffi = require("ffi")
local ffi_load = ffi.load
local ffi_cdef = ffi.cdef
local _setmetatable = setmetatable
ffi_cdef([[
/* ============================== Data Types ============================== */
/* Easing Types */
typedef enum ice_ease_type {
ICE_EASE_TYPE_PROGRESS = 1,
ICE_EASE_TYPE_PENNER = 4
} ice_ease_type;
/* ============================== Functions ============================== */
/* Functions for Linear Easing */
double ice_ease_linear(ice_ease_type ease_type, ...);
/* Functions for Quadratic Easing */
double ice_ease_quad_in(ice_ease_type ease_type, ...);
double ice_ease_quad_out(ice_ease_type ease_type, ...);
double ice_ease_quad_in_out(ice_ease_type ease_type, ...);
/* Functions for Cubic Easing */
double ice_ease_cubic_in(ice_ease_type ease_type, ...);
double ice_ease_cubic_out(ice_ease_type ease_type, ...);
double ice_ease_cubic_in_out(ice_ease_type ease_type, ...);
/* Functions for Quartic Easing */
double ice_ease_quart_in(ice_ease_type ease_type, ...);
double ice_ease_quart_out(ice_ease_type ease_type, ...);
double ice_ease_quart_in_out(ice_ease_type ease_type, ...);
/* Functions for Quintic Easing */
double ice_ease_quint_in(ice_ease_type ease_type, ...);
double ice_ease_quint_out(ice_ease_type ease_type, ...);
double ice_ease_quint_in_out(ice_ease_type ease_type, ...);
/* Functions for Sinusoidal Easing */
double ice_ease_sine_in(ice_ease_type ease_type, ...);
double ice_ease_sine_out(ice_ease_type ease_type, ...);
double ice_ease_sine_in_out(ice_ease_type ease_type, ...);
/* Functions for Exponential Easing */
double ice_ease_expo_in(ice_ease_type ease_type, ...);
double ice_ease_expo_out(ice_ease_type ease_type, ...);
double ice_ease_expo_in_out(ice_ease_type ease_type, ...);
/* Functions for Circular Easing */
double ice_ease_circ_in(ice_ease_type ease_type, ...);
double ice_ease_circ_out(ice_ease_type ease_type, ...);
double ice_ease_circ_in_out(ice_ease_type ease_type, ...);
/* Functions for Elastic Easing */
double ice_ease_elastic_in(ice_ease_type ease_type, ...);
double ice_ease_elastic_out(ice_ease_type ease_type, ...);
double ice_ease_elastic_in_out(ice_ease_type ease_type, ...);
/* Functions for Back Easing */
double ice_ease_back_in(ice_ease_type ease_type, ...);
double ice_ease_back_out(ice_ease_type ease_type, ...);
double ice_ease_back_in_out(ice_ease_type ease_type, ...);
/* Functions for Bounce Easing */
double ice_ease_bounce_in(ice_ease_type ease_type, ...);
double ice_ease_bounce_out(ice_ease_type ease_type, ...);
double ice_ease_bounce_in_out(ice_ease_type ease_type, ...);
]])
local l = ffi_load("ice_ease")
local mt = { __index = l }
local lib = _setmetatable({}, mt)
lib.ICE_EASE_PI = 3.14159265358979323846
return lib
|
local gears = require("gears")
-- local lain = require("lain")
local awful = require("awful")
local wibox = require("wibox")
local dpi = require("beautiful.xresources").apply_dpi
local os = os
local my_table = awful.util.table or gears.table -- 4.{0,1} compatibility
local theme = {}
theme.dir = os.getenv("HOME") .. "/.config/awesome/themes/steamburn"
theme.wallpaper = theme.dir .. "/wall.png"
theme.font = "Iosevka SS07"
theme.fg_normal = "#e2ccb0"
theme.fg_focus = "#d88166"
theme.fg_urgent = "#CC9393"
theme.bg_normal = "#140c0b"
theme.bg_focus = "#140c0b"
theme.bg_urgent = "#2a1f1e"
theme.border_width = dpi(1)
theme.border_normal = "#302627"
theme.border_focus = "#c2745b"
theme.border_marked = "#CC9393"
theme.taglist_fg_focus = "#d88166"
theme.tasklist_bg_focus = "#140c0b"
theme.tasklist_fg_focus = "#d88166"
theme.taglist_squares_sel = theme.dir .. "/icons/square_sel.png"
theme.taglist_squares_unsel = theme.dir .. "/icons/square_unsel.png"
theme.menu_height = dpi(16)
theme.menu_width = dpi(140)
theme.awesome_icon = theme.dir .. "/icons/awesome.png"
theme.menu_submenu_icon = theme.dir .. "/icons/submenu.png"
theme.layout_txt_tile = "[t]"
theme.layout_txt_tileleft = "[l]"
theme.layout_txt_tilebottom = "[b]"
theme.layout_txt_tiletop = "[tt]"
theme.layout_txt_fairv = "[fv]"
theme.layout_txt_fairh = "[fh]"
theme.layout_txt_spiral = "[s]"
theme.layout_txt_dwindle = "[d]"
theme.layout_txt_max = "[m]"
theme.layout_txt_fullscreen = "[F]"
theme.layout_txt_magnifier = "[M]"
theme.layout_txt_floating = "[|]"
theme.tasklist_plain_task_name = true
theme.tasklist_disable_icon = true
theme.useless_gap = dpi(2)
theme.layout_txt_termfair = "[termfair]"
theme.layout_txt_centerfair = "[centerfair]"
theme.gap_single_client = false
-- Textclock
local mytextclock = wibox.widget.textclock(" %H:%M ")
mytextclock.font = theme.font
local spr = wibox.widget.textbox(" ")
local function update_txt_layoutbox(s)
-- Writes a string representation of the current layout in a textbox widget
local txt_l = theme["layout_txt_" .. awful.layout.getname(awful.layout.get(s))] or ""
s.mytxtlayoutbox:set_text(txt_l)
end
function theme.at_screen_connect(s)
-- Quake application
-- s.quake = lain.util.quake({ app = awful.util.terminal })
-- If wallpaper is a function, call it with the screen
local wallpaper = theme.wallpaper
if type(wallpaper) == "function" then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
-- Tags
awful.tag(awful.util.tagnames, s, awful.layout.layouts)
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Textual layoutbox
s.mytxtlayoutbox = wibox.widget.textbox(theme["layout_txt_" .. awful.layout.getname(awful.layout.get(s))])
awful.tag.attached_connect_signal(s, "property::selected", function()
update_txt_layoutbox(s)
end)
awful.tag.attached_connect_signal(s, "property::layout", function()
update_txt_layoutbox(s)
end)
s.mytxtlayoutbox:buttons(my_table.join(
awful.button({}, 1, function()
awful.layout.inc(1)
end),
awful.button({}, 2, function()
awful.layout.set(awful.layout.layouts[1])
end),
awful.button({}, 3, function()
awful.layout.inc(-1)
end),
awful.button({}, 4, function()
awful.layout.inc(1)
end),
awful.button({}, 5, function()
awful.layout.inc(-1)
end)
))
-- Create a taglist widgets
--
local function tags_filter(t)
return t.selected or #t:clients() > 0
end
s.mytaglist = awful.widget.taglist(s, tags_filter, awful.util.taglist_buttons)
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, awful.util.tasklist_buttons)
-- Create the wibox
s.mywibox = awful.wibar({ position = "top", screen = s, height = dpi(18) })
-- Add widgets to the wibox
s.mywibox:setup({
layout = wibox.layout.align.horizontal,
{ -- Left widgets
layout = wibox.layout.fixed.horizontal,
spr,
s.mytaglist,
spr,
s.mytxtlayoutbox,
--spr,
s.mypromptbox,
spr,
},
s.mytasklist, -- Middle widget
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
mytextclock,
wibox.widget.systray(),
},
})
end
return theme
|
--[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
OpenAPI spec version: 1.0.1
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
--[[
Unit tests for openapi-client.model.github_repositories
Automatically generated by openapi-generator (https://openapi-generator.tech)
Please update as you see appropriate
]]
describe("github_repositories", function()
local openapi-client_github_repositories = require "openapi-client.model.github_repositories"
-- unit tests for the property '_class'
describe("property _class test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property '_links'
describe("property _links test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'items'
describe("property items test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'last_page'
describe("property last_page test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'next_page'
describe("property next_page test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'page_size'
describe("property page_size test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
end)
|
--!The Make-like Build Utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2017, TBOOX Open Source Group.
--
-- @author ruki
-- @file static.lua
--
-- imports
import("core.base.option")
import("core.tool.linker")
import("core.tool.compiler")
import("object")
-- build target from objects
function _build_from_objects(target, buildinfo)
-- build objects
object.build(target, buildinfo)
-- make headers
local srcheaders, dstheaders = target:headerfiles()
if srcheaders and dstheaders then
local i = 1
for _, srcheader in ipairs(srcheaders) do
local dstheader = dstheaders[i]
if dstheader then
os.cp(srcheader, dstheader)
end
i = i + 1
end
end
-- expand object files with *.o/obj
local objectfiles = {}
for _, objectfile in ipairs(target:objectfiles()) do
if objectfile:find("%*") then
local matchfiles = os.match(objectfile)
if matchfiles then
table.join2(objectfiles, matchfiles)
end
else
table.insert(objectfiles, objectfile)
end
end
-- the target file
local targetfile = target:targetfile()
-- is verbose?
local verbose = option.get("verbose")
-- trace percent info
cprintf("${green}[%02d%%]:${clear} ", (buildinfo.targetindex + 1) * 100 / buildinfo.targetcount)
if verbose then
cprint("${dim magenta}archiving.$(mode) %s", path.filename(targetfile))
else
cprint("${magenta}archiving.$(mode) %s", path.filename(targetfile))
end
-- trace verbose info
if verbose then
print(target:linkcmd(objectfiles))
end
-- link it
linker.link(objectfiles, targetfile, target)
end
-- build target from sources
function _build_from_sources(target, buildinfo, sourcebatch, sourcekind)
-- the target file
local targetfile = target:targetfile()
-- is verbose?
local verbose = option.get("verbose")
-- trace percent into
cprintf("${green}[%02d%%]:${clear} ", (buildinfo.targetindex + 1) * 100 / buildinfo.targetcount)
if verbose then
cprint("${dim magenta}archiving.$(mode) %s", path.filename(targetfile))
else
cprint("${magenta}archiving.$(mode) %s", path.filename(targetfile))
end
-- trace verbose info
if verbose then
print(compiler.buildcmd(sourcebatch.sourcefiles, targetfile, target, sourcekind))
end
-- build it
compiler.build(sourcebatch.sourcefiles, targetfile, target, sourcekind)
end
-- build static target
function build(target, buildinfo)
-- only one source kind?
local kindcount = 0
local sourcekind = nil
local sourcebatch = nil
for kind, batch in pairs(target:sourcebatches()) do
sourcekind = kind
sourcebatch = batch
kindcount = kindcount + 1
if kindcount > 1 then
break
end
end
-- build target
if kindcount == 1 and sourcekind and compiler.feature(sourcekind, "static:sources") then
_build_from_sources(target, buildinfo, sourcebatch, sourcekind)
else
_build_from_objects(target, buildinfo)
end
end
|
object_tangible_furniture_all_frn_all_couch_love_seat_s1 = object_tangible_furniture_all_shared_frn_all_couch_love_seat_s1:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_couch_love_seat_s1, "object/tangible/furniture/all/frn_all_couch_love_seat_s1.iff")
|
player = Game.Players.yfc
char = player.Character
char.Torso.Transparency = 1
char.Head.Transparency = 1
char["Right Arm"].Transparency = 1
char["Right Leg"].Transparency = 1
char["Left Arm"].Transparency = 1
char["Left Leg"].Transparency = 1
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(3, 2, 3)
part:BreakJoints()
part.BrickColor = BrickColor.new("Bright red")
mesh = Instance.new("SpecialMesh")
mesh.Parent = part
mesh.MeshType = "Sphere"
mesh.Scale = Vector3.new(1.01,1.01,1.01)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(0, 0, 0)
weld.C1 = CFrame.new()
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(3, 1, 3)
part:BreakJoints()
part.BrickColor = BrickColor.new("Bright red")
mesh = Instance.new("BlockMesh")
mesh.Parent = part
mesh.Scale = Vector3.new(1.01,0.65,1.01)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(0, 0.75, 0)
weld.C1 = CFrame.new()
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(1, 2, 1)
part:BreakJoints()
part.BrickColor = BrickColor.new("Really black")
mesh = Instance.new("CylinderMesh")
mesh.Parent = part
mesh.Scale = Vector3.new(0.6,1.01,0.6)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(0.5, 1.75, 1.15)
weld.C1 = CFrame.new()
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(1, 2, 1)
part:BreakJoints()
part.BrickColor = BrickColor.new("Really black")
mesh = Instance.new("CylinderMesh")
mesh.Parent = part
mesh.Scale = Vector3.new(0.6,1.01,0.6)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(-0.5, 1.75, 1.15)
weld.C1 = CFrame.new()
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(1, 2, 1)
part:BreakJoints()
part.BrickColor = BrickColor.new("Really black")
mesh = Instance.new("CylinderMesh")
mesh.Parent = part
mesh.Scale = Vector3.new(0.6,1.01,0.6)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(0.5, 1.75, -1.15)
weld.C1 = CFrame.new()
part = Instance.new("Part")
part.Parent = player.Character
part.Size = Vector3.new(1, 2, 1)
part:BreakJoints()
part.BrickColor = BrickColor.new("Really black")
mesh = Instance.new("CylinderMesh")
mesh.Parent = part
mesh.Scale = Vector3.new(0.6,1.01,0.6)
weld = Instance.new("Weld")
weld.Parent = part
weld.Part0 = part
weld.Part1 = player.Character.Torso
weld.C0 = CFrame.new(-0.5, 1.75, -1.15)
weld.C1 = CFrame.new() |
local tremove = table.remove
function ezlib.item.get.list(value)
if type(value) == "table" then
if value.not_items then
not_items = ezlib.item.not_item
value.not_items = nil
else
not_items = "item"
end
else
not_items = "item"
end
local freturn = 0
local item = {}
local list = {}
local del_list = {}
if type(not_items) == "table" then
for _, ing in pairs(not_items) do
local entities = data.raw[ing]
if entities then
for b in pairs(entities) do
local entity = entities[b]
if entity then
list[#list+1] = {entity.name, entity.type}
end
end
end
end
if value ~= nil and type(value) == "table" then
for _, ing in pairs(list) do
local entity = data.raw[ing[2]][ing[1]]
for a in pairs(value) do
local t = value[a] -- ?
if value[a] ~= nil then
if type(t) == "string" or type(t) == "number" then
if entity[a] ~= t or entity[a] == nil then
del_list[#del_list+1] = ing
end
elseif type(t) == "table" then
for b, v in pairs(t) do
if type(v) == "string" or type(v) == "number" then
local r = entity[a][b] -- ?
if r ~= t[b] or r == nil then
del_list[#del_list+1] = ing
end
elseif type(v) == "table" then
log("You can't mine so deap")
else
break
end
end
else
break
end
end
end
end
end
else
item = data.raw.item -- TODO: refactor
if item ~= nil then
for k in pairs(item) do
list[#list+1] = item[k].name
end
end
if value ~= nil and type(value) == "table" then
for a in pairs(value) do
if value[a] ~= nil then
if type(value[a]) == "string" or type(value[a]) == "number" then
for x, ing2 in pairs(list) do
local v = item[list[x]][a]
if v ~= value[a] or v == nil then
del_list[#del_list+1] = ing2
end
end
elseif type(value[a]) == "table" then
for b in pairs(value[a]) do
if type(value[a][b]) == "string" or type(value[a][b]) == "number" then
for x, ing2 in pairs(list) do
-- Does this work?
local v = item[list[x]][a]
if v ~= value[a][b] or v == nil then
del_list[#del_list+1] = ing2
end
end
elseif type(value[a][b]) == "table" then
log("You can't mine so deap")
else
break
end
end
else
break
end
end
end
end
end
list = ezlib.tbl.remove(list, del_list)
if list then
if #list == 1 then
list = list[1]
freturn = 1
elseif #list == 0 then
list = nil
else
freturn = 1
end
end
if ezlib.debug_self then
local print = ""
print = print .. "ezlib.item.get.list\n---------------------------------------------------------------------------------------------\n"
if type(list) == "table" then
print = print .. " Found " .. #list .. " items."
elseif type(list) == "string" then
print = print .. " Found item " .. list .. "."
else
print = print .. " [Warning] Found 0 items in type."
end
if type(value) == "table" then
print = print .. "\n List of filters:"
print = print .. ezlib.log.print(value, 0)
end
log(print .. "\n---------------------------------------------------------------------------------------------")
end
if freturn == 0 then
return nil
else
return list
end
end
function ezlib.item.add.flag(value, flag)
local print = "ezlib.item.add.flag\n---------------------------------------------------------------------------------------------\n"
local entity = data.raw.item[value]
if entity then
local flags = entity.flags
if flags then
flags[#flags+1] = flag
else
entity.flags = flag
end
if ezlib.debug_self then
log(print .. " Flag " .. flag .. " added to " .. value .. ".\n---------------------------------------------------------------------------------------------")
end
else
if ezlib.debug_self then
log(print .. " [Warning] Item with name " .. value .. " not found.\n---------------------------------------------------------------------------------------------")
else
log(" [Warning] Item with name " .. value .. " not found.")
end
end
end
function ezlib.item.remove.flag(value, flag)
local print = "ezlib.item.remove.flag\n---------------------------------------------------------------------------------------------\n"
local entity = data.raw[type][value]
if entity then
local flags = entity.flags
if flags then
for i=#flags, 1, -1 do
-- TODO: check
if flags[i] == flag then
tremove(flags, i)
end
end
end
if ezlib.debug_self then
log(print .. " Flag " .. flag .. " removed from " .. value .. ".\n---------------------------------------------------------------------------------------------")
end
else
if ezlib.debug_self then
log(print .. " [Warning] Item with name " .. value .. " not found.\n---------------------------------------------------------------------------------------------")
else
log(" [Warning] Item with name " .. value .. " not found.")
end
end
end
|
----------------------------------------------------------------------------------------------------
-- Client Lua Script for RaidCore Addon on WildStar Game.
--
-- Copyright (C) 2015 RaidCore
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- Description:
-- TODO
----------------------------------------------------------------------------------------------------
local Apollo = require "Apollo"
local GameLib = require "GameLib"
local core = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("RaidCore")
local mod = core:NewEncounter("Gloomclaw", 52, 98, 115)
if not mod then return end
----------------------------------------------------------------------------------------------------
-- Registering combat.
----------------------------------------------------------------------------------------------------
mod:RegisterTrigMob(core.E.TRIGGER_ANY, { "unit.gloomclaw" })
mod:RegisterEnglishLocale({
-- Unit names.
["unit.gloomclaw"] = "Gloomclaw",
["Corrupted Ravager"] = "Corrupted Ravager",
["Empowered Ravager"] = "Empowered Ravager",
["Strain Parasite"] = "Strain Parasite",
["Gloomclaw Skurge"] = "Gloomclaw Skurge",
["Corrupted Fraz"] = "Corrupted Fraz",
["Essence of Logic"] = "Essence of Logic",
-- Datachron messages.
["Gloomclaw is reduced to a weakened state"] = "Gloomclaw is reduced to a weakened state!",
["Gloomclaw is vulnerable"] = "Gloomclaw is vulnerable!",
["Gloomclaw is pushed back"] = "Gloomclaw is pushed back by the purification of the essences!",
["Gloomclaw is moving forward"] = "Gloomclaw is moving forward to corrupt more essences!",
-- Cast.
["Rupture"] = "Rupture",
["Corrupting Rays"] = "Corrupting Rays",
-- Timer bars.
["Next wave #%u"] = "Next wave #%u",
["Next rupture"] = "Next rupture",
["Full corruption"] = "Full corruption",
-- Message bars.
["WAVE"] = "WAVE",
["INTERRUPT %s"] = "INTERRUPT %s",
["SECTION %u"] = "SECTION %u",
["FROG %u"] = "FROG %u",
["LEFT"] = "LEFT",
["RIGHT"] = "RIGHT",
["TRANSITION"] = "TRANSITION",
["MOO PHASE"] = "MOO PHASE",
["BURN HIM HARD"] = "BURN HIM HARD",
})
mod:RegisterFrenchLocale({
-- Unit names.
["unit.gloomclaw"] = "Serrenox",
["Corrupted Ravager"] = "Ravageur corrompu",
["Empowered Ravager"] = "Ravageur renforcé",
["Strain Parasite"] = "Parasite de la Souillure",
["Gloomclaw Skurge"] = "Skurge serrenox",
["Corrupted Fraz"] = "Friz corrompu",
["Essence of Logic"] = "Essence de logique",
-- Datachron messages.
["Gloomclaw is reduced to a weakened state"] = "Serrenox a été affaibli !",
["Gloomclaw is vulnerable"] = "Serrenox est vulnérable !",
["Gloomclaw is pushed back"] = "Serrenox est repoussé par la purification des essences !",
["Gloomclaw is moving forward"] = "Serrenox s'approche pour corrompre davantage d'essences !",
-- Cast.
["Rupture"] = "Rupture",
["Corrupting Rays"] = "Rayons de corruption",
-- Timer bars.
["Next wave #%u"] = "Next wave n°%u",
["Next rupture"] = "Prochaine rupture",
["Full corruption"] = "Totalement corrompu",
-- Message bars.
["WAVE"] = "WAVE",
["INTERRUPT %s"] = "INTERROMPRE %s",
["SECTION %u"] = "SECTION %u",
["FROG %u"] = "ADD %u",
["LEFT"] = "GAUCHE",
["RIGHT"] = "DROITE",
["TRANSITION"] = "TRANSITION",
["MOO PHASE"] = "MOO PHASE",
["BURN HIM HARD"] = "Burst DPS",
})
mod:RegisterGermanLocale({
-- Unit names.
["unit.gloomclaw"] = "Düsterklaue",
["Corrupted Ravager"] = "Korrumpierter Verwüster",
["Strain Parasite"] = "Transmutierten-Parasit",
["Gloomclaw Skurge"] = "Düsterklauen-Geißel",
["Corrupted Fraz"] = "Korrumpierter Fraz",
["Essence of Logic"] = "Logikessenz",
-- Datachron messages.
-- Cast.
["Rupture"] = "Aufreißen",
["Corrupting Rays"] = "Korrumpierende Strahlen",
-- Timer bars.
-- Message bars.
})
-- Default settings.
mod:RegisterDefaultSetting("SoundRuptureInterrupt")
mod:RegisterDefaultSetting("SoundCorruptingRays")
mod:RegisterDefaultSetting("SoundSectionSwitch")
mod:RegisterDefaultSetting("SoundMoOWarning")
mod:RegisterDefaultSetting("SoundWaveWarning")
mod:RegisterDefaultSetting("SoundRuptureCountDown")
mod:RegisterDefaultSetting("SoundCorruptionCountDown")
mod:RegisterDefaultSetting("OtherMaulerMarkers")
mod:RegisterDefaultSetting("OtherLeftRightMarkers")
-- Timers default configs.
mod:RegisterDefaultTimerBarConfigs({
["RUPTURE"] = { sColor = "xkcdBrightRed" },
["WAVE"] = { sColor = "xkcdBrightOrange" },
["CORRUPTION"] = { sColor = "xkcdBrown" },
["MOO"] = { sColor = "xkcdBurntYellow" },
}
)
mod:RegisterUnitBarConfig("unit.gloomclaw", {
nPriority = 0,
tMidphases = {
{percent = 85},
{percent = 65},
{percent = 45},
{percent = 25},
{percent = 16},
}
}
)
----------------------------------------------------------------------------------------------------
-- Constants.
----------------------------------------------------------------------------------------------------
local leftSpawn = {
{x = 4288.5, y = -568.48095703125, z = -16765.66796875 },
{x = 4288.5, y = -568.30078125, z = -16858.9765625 },
{x = 4288.5, y = -568.95300292969, z = -16949.40234375 },
{x = 4288.5, y = -568.95300292969, z = -17040.22265625 },
{x = 4288.5, y = -568.95300292969, z = -17040.099609375 }
}
local rightSpawn = {
{x = 4332.5, y = -568.4833984375, z = -16765.66796875 },
{x = 4332.5, y = -568.45147705078, z = -16858.9765625 },
{x = 4332.5, y = -568.95300292969, z = -16949.40234375 },
{x = 4332.5, y = -568.95300292969, z = -17040.22265625 },
{x = 4332.5, y = -568.95300292969, z = -17040.099609375 }
}
local spawnTimer = { 26, 33, 25, 14, 20.5 }
local spawnCount = { 4, 3, 4, 5, 5 }
local maulerSpawn = {
["northwest"] = { x = 4288, y = -568, z = -17040 },
["northeast"] = { x = 4332, y = -568, z = -17040 },
["southwest"] = { x = 4288, y = -568, z = -16949 }, --todo check if these 2 are sw/se or other way around
["southeast"] = { x = 4332, y = -568, z = -16949 },
}
----------------------------------------------------------------------------------------------------
-- Locals.
----------------------------------------------------------------------------------------------------
local GetUnitById = GameLib.GetUnitById
local prev
local waveCount, ruptCount, essenceUp
local first
local section
local function RemoveEssenceTracking()
for nId, _ in next, essenceUp do
core:RemoveUnit(nId)
core:DropMark(nId)
essenceUp[nId] = nil
end
end
----------------------------------------------------------------------------------------------------
-- Encounter description.
----------------------------------------------------------------------------------------------------
function mod:OnBossEnable()
waveCount, ruptCount, prev = 0, 0, 0
section = 1
first = true
essenceUp = {}
mod:AddTimerBar("RUPTURE", "next rupture", 35, mod:GetSetting("SoundRuptureCountDown"))
mod:AddTimerBar("CORRUPTION", "Full corruption", 106, mod:GetSetting("SoundCorruptionCountDown"))
end
function mod:OnWipe()
Apollo.RemoveEventHandler(core.E.EVENT_COMBAT_LOG_HEAL, self)
core:ResetWorldMarkers()
end
function mod:OnUnitCreated(nId, tUnit, sName)
if sName == self.L["Corrupted Ravager"] or sName == self.L["Empowered Ravager"] then
core:WatchUnit(tUnit, core.E.TRACK_CASTS)
elseif sName == self.L["unit.gloomclaw"] then
mod:AddUnit(tUnit)
core:WatchUnit(tUnit, core.E.TRACK_CASTS)
end
end
function mod:OnCastStart(nId, sCastName, nCastEndTime, sName)
if sName == self.L["unit.gloomclaw"] and sCastName == self.L["Rupture"] then
ruptCount = ruptCount + 1
mod:AddMsg("RUPTURE", self.L["INTERRUPT %s"]:format(sName:upper()), 5, mod:GetSetting("SoundRuptureInterrupt") and "Destruction")
if ruptCount == 1 then
mod:AddTimerBar("RUPTURE", "Next rupture", 43, mod:GetSetting("SoundRuptureCountDown"))
end
elseif (sName == self.L["Corrupted Ravager"] or sName == self.L["Empowered Ravager"])
and sCastName == self.L["Corrupting Rays"] then
local playerUnit = GameLib.GetPlayerUnit()
local tUnit = GetUnitById(nId)
local distance_to_unit = self:GetDistanceBetweenUnits(playerUnit, tUnit)
if distance_to_unit < 35 then
mod:AddMsg("RAYS", self.L["INTERRUPT %s"]:format(sName:upper()), 5, mod:GetSetting("SoundCorruptingRays") and "Inferno")
end
end
end
function mod:OnDatachron(sMessage)
local isPushBack = sMessage == self.L["Gloomclaw is pushed back"]
local isMoveForward = sMessage == self.L["Gloomclaw is moving forward"]
if isPushBack or isMoveForward then
if not first then
waveCount, ruptCount, prev = 0, 0, 0
mod:RemoveTimerBar("RUPTURE")
mod:RemoveTimerBar("CORRUPTION")
mod:RemoveTimerBar("WAVE")
if isPushBack then
section = section + 1
else
section = section - 1
end
mod:AddMsg("PHASE", self.L["SECTION %u"]:format(section), 5, mod:GetSetting("SoundSectionSwitch") and "Info", "Blue")
if section ~= 4 then
mod:AddTimerBar("WAVE", self.L["Next wave #%u"]:format(waveCount + 1), 11)
mod:AddTimerBar("RUPTURE", "Next rupture", 39, mod:GetSetting("SoundRuptureCountDown"))
end
mod:AddTimerBar("CORRUPTION", "Full corruption", 111, mod:GetSetting("SoundCorruptionCountDown"))
else
first = false
end
core:ResetWorldMarkers()
if mod:GetSetting("OtherMaulerMarkers") then
core:SetWorldMarker("FROG1", self.L["FROG %u"]:format(1), maulerSpawn["northwest"])
core:SetWorldMarker("FROG2", self.L["FROG %u"]:format(2), maulerSpawn["northeast"])
core:SetWorldMarker("FROG3", self.L["FROG %u"]:format(3), maulerSpawn["southeast"])
core:SetWorldMarker("FROG4", self.L["FROG %u"]:format(4), maulerSpawn["southwest"])
end
if mod:GetSetting("OtherLeftRightMarkers") then
if leftSpawn[section] then
core:SetWorldMarker("SECLEFT", self.L["LEFT"], leftSpawn[section])
end
if rightSpawn[section] then
core:SetWorldMarker("SECRIGHT", self.L["RIGHT"], rightSpawn[section])
end
end
Apollo.RegisterEventHandler(core.E.EVENT_COMBAT_LOG_HEAL, "OnCombatLogHeal", self)
elseif sMessage:find(self.L["Gloomclaw is reduced to a weakened state"]) then
mod:RemoveTimerBar("RUPTURE")
mod:RemoveTimerBar("CORRUPTION")
mod:RemoveTimerBar("WAVE")
mod:AddMsg("TRANSITION", "TRANSITION", 5, mod:GetSetting("SoundMoOWarning") and "Alert")
RemoveEssenceTracking()
elseif sMessage:find(self.L["Gloomclaw is vulnerable"]) then
mod:RemoveTimerBar("RUPTURE")
mod:RemoveTimerBar("CORRUPTION")
mod:RemoveTimerBar("WAVE")
mod:AddMsg("TRANSITION", "BURN HIM HARD", 5, mod:GetSetting("SoundMoOWarning") and "Alert")
mod:AddTimerBar("MOO", "MOO PHASE", 20, mod:GetSetting("SoundMoOWarning"))
RemoveEssenceTracking()
end
end
function mod:OnCombatLogHeal(tArgs)
if tArgs.unitTarget then
local targetName = core:ReplaceNoBreakSpace(tArgs.unitTarget:GetName())
local targetId = tArgs.unitTarget:GetId()
if targetName == self.L["Essence of Logic"] then
if not essenceUp[targetId] then
essenceUp[targetId] = true
local essPos = tArgs.unitTarget:GetPosition()
core:MarkUnit(tArgs.unitTarget, 0, (essPos.x < 4310) and "L" or "R")
mod:AddUnit(tArgs.unitTarget)
if #essenceUp == 2 then
Apollo.RemoveEventHandler(core.E.EVENT_COMBAT_LOG_HEAL, self)
end
end
end
end
end
function mod:OnEnteredCombat(nId, tUnit, sName, bInCombat)
if bInCombat then
if sName == self.L["Strain Parasite"]
or sName == self.L["Gloomclaw Skurge"]
or sName == self.L["Corrupted Fraz"] then
local timeOfEvent = GameLib.GetGameTime()
if timeOfEvent - prev > 10 then
prev = timeOfEvent
waveCount = waveCount + 1
mod:AddMsg("WAVE", "WAVE", 5, mod:GetSetting("SoundWaveWarning") and "Info", "Blue")
if section < 5 then
if waveCount < spawnCount[section] then
mod:AddTimerBar("WAVE", self.L["Next wave #%u"]:format(waveCount + 1), spawnTimer[section])
end
else
local sTimerText = self.L["Next wave #%u"]:format(waveCount + 1)
if waveCount == 1 then
mod:AddTimerBar("WAVE", sTimerText, 20.5)
elseif waveCount == 2 then
mod:AddTimerBar("WAVE", sTimerText, 30)
elseif waveCount == 3 then
mod:AddTimerBar("WAVE", sTimerText, 15)
end
end
end
end
end
end
|
vim.cmd('colorscheme nord')
vim.cmd('set guifont=Fira\\ Code')
vim.cmd('syntax on')
vim.wo.rnu = true
vim.wo.nu = true
vim.wo.cursorline = true
vim.wo.numberwidth = 4
require('lualine').setup{
options = {
theme = 'nord',
section_separators = {'', ''},
component_separators = {'', ''},
disabled_filetypes = {},
icons_enabled = true,
},
sections = {
lualine_a = { {'mode', upper = true} },
lualine_b = { {'branch', icon = ''} },
lualine_c = { {'filename', file_status = true} },
lualine_x = { '' },
lualine_y = { '' },
lualine_z = { 'location' },
},
inactive_sections = {
lualine_a = { },
lualine_b = { },
lualine_c = { 'filename' },
lualine_x = { 'location' },
lualine_y = { },
lualine_z = { }
}
}
vim.g.nord_color = {
"#2E3440", --0
"#3B4252", --1
"#434C5E", --2
"#4C566A", --3
"#616E88", --4
"#D8DEE9", --5
"#E5E9F0", --6
"#ECEFF4", --7
"#8FBCBB", --8
"#88C0D0", --9
"#81A1C1", --10
"#5E81AC", --11
"#BF616A", --12
"#D08770", --13
"#EBCB8B", --14
"#A3BE8C", --15
"#B48EAD" --16
}
require("lsp-colors").setup({
Error = vim.g.nord_color[12],
Warning = vim.g.nord_color[14],
Information = vim.g.nord_color[9],
Hint = vim.g.nord_color[15]
})
|
--[[ Created by Grid2 original authors, modified by Michael ]]--
local Grid2 = Grid2
local GetTime = GetTime
local string_cut = Grid2.strcututf8
local min = math.min
local next = next
local justifyH = { CENTER = "CENTER", TOP = "CENTER", BOTTOM = "CENTER", LEFT = "LEFT", RIGHT = "RIGHT", TOPLEFT = "LEFT", TOPRIGHT = "RIGHT", BOTTOMLEFT = "LEFT", BOTTOMRIGHT = "RIGHT" }
local justifyV = { CENTER = "CENTER", TOP = "TOP", BOTTOM = "BOTTOM", LEFT = "CENTER", RIGHT = "CENTER", TOPLEFT = "TOP", TOPRIGHT = "TOP", BOTTOMLEFT = "BOTTOM", BOTTOMRIGHT = "BOTTOM" }
Grid2.defaults.profile.formatting = {
longDecimalFormat = "%.1f",
shortDecimalFormat = "%.0f",
longDurationStackFormat = "%.1f:%d",
shortDurationStackFormat = "%.0f:%d",
invertDurationStack = false,
}
local timers = {}
local stacks = {}
local expirations = {}
local curTime -- Here goes current time to minimize GetTime() calls
-- {{ Timer management
local TimerStart, TimerStop
do
local timer
function TimerStart(text, func)
timer = Grid2:CreateTimer( function()
curTime = GetTime()
for text, func in next, timers do
func(text)
end
end, 0.1 )
timers[text] = func
TimerStart = function(text, func)
if not next(timers) then timer:Play() end
timers[text] = func
end
end
function TimerStop(text)
timers[text], expirations[text], stacks[text] = nil, nil, nil
if not next(timers) then timer:Stop() end
end
end
--}}
-- {{ Update functions
local FmtDE = {} -- masks for duration|elapsed
local FmtDES = {} -- masks for duration|elapsed & stacks
-- elapsed + stacks
local function _UpdateES(text)
text:SetFormattedText( FmtDES[false], curTime - expirations[text] , stacks[text] or 1 )
end
-- stacks + elapsed
local function _UpdateSE(text)
text:SetFormattedText( FmtDES[false], stacks[text] or 1, curTime - expirations[text] )
end
-- duration + stacks
local function _UpdateDS(text)
local timeLeft = expirations[text] - curTime
if timeLeft>0 then
text:SetFormattedText( FmtDES[timeLeft<1], timeLeft, stacks[text] or 1 )
else
text:SetText("")
end
end
-- stacks + duration
local function _UpdateSD(text)
local timeLeft = expirations[text] - curTime
if timeLeft>0 then
text:SetFormattedText( FmtDES[timeLeft<1], stacks[text] or 1, timeLeft )
else
text:SetText("")
end
end
-- elapsed
local function UpdateE(text)
text:SetFormattedText( "%.0f", curTime - expirations[text] )
end
-- duration
local function UpdateD(text)
local timeLeft = expirations[text] - curTime
if timeLeft>0 then
text:SetFormattedText( FmtDE[timeLeft<1], timeLeft )
else
text:SetText("")
end
end
-- elapsed+stacks | stacks+elapsed
local UpdateES = _UpdateES
-- duration+stacks | stacks+duration
local UpdateDS = _UpdateDS
-- }}
--{{ Indicator methods
local function Text_Create(self, parent)
local f = self:CreateFrame("Frame", parent)
f:SetAllPoints()
f:SetBackdrop(nil)
local Text = f.Text or f:CreateFontString(nil, "OVERLAY")
Text:SetFontObject(GameFontHighlightSmall)
f.Text = Text
Text:Show()
end
local function Text_Layout(self, parent)
local Frame = parent[self.name]
local Text = Frame.Text
Frame:SetParent(parent)
Frame:ClearAllPoints()
Frame:SetAllPoints()
Frame:SetFrameLevel(parent:GetFrameLevel() + self.frameLevel)
Text:SetFont(self.textfont, self.textsize, self.fontFlags)
Text:ClearAllPoints()
Text:SetPoint(self.anchor, parent.container, self.anchorRel, self.offsetx, self.offsety)
Text:SetJustifyH(justifyH[self.anchorRel])
Text:SetJustifyV(justifyV[self.anchorRel])
Text:SetWidth(parent:GetWidth())
Text:SetShadowOffset(1,-1)
Text:SetShadowColor(0,0,0, self.shadowAlpha)
Frame:Show()
end
local function Text_GetBlinkFrame(self, parent)
return parent[self.name]
end
local function Text_OnUpdateDE(self, parent, unit, status)
local Text = parent[self.name].Text
if status then
Text:Show()
local expiration = status:GetExpirationTime(unit)
if expiration then
curTime = GetTime() -- not local because is used later by self.updateFunc
if expiration > curTime then
if self.stack then
stacks[Text] = status:GetCount(unit)
end
if self.elapsed then
expirations[Text] = min( expiration - (status:GetDuration(unit) or 0), curTime )
else
expirations[Text] = expiration
end
if not timers[Text] then
TimerStart(Text, self.updateFunc)
end
self.updateFunc(Text)
return
end
else
Text:SetText( string_cut(status:GetText(unit) or "", self.textlength) )
if timers[Text] then TimerStop(Text) end
return
end
end
Text:Hide()
if timers[Text] then TimerStop(Text) end
end
local function Text_OnUpdateS(self, parent, unit, status)
local Text = parent[self.name].Text
if status then
local count = status:GetCount(unit)
if count then
Text:SetFormattedText( "%d", count )
else
Text:SetText( string_cut(status:GetText(unit) or "", self.textlength) )
end
Text:Show()
else
Text:Hide()
end
end
local function Text_OnUpdateP(self, parent, unit, status)
local Text = parent[self.name].Text
if status then
local percent, text
if status.GetPercentText then
text = status:GetPercentText(unit)
else
percent, text = status:GetPercent(unit)
end
if text then
Text:SetText( text )
elseif percent then
Text:SetFormattedText( "%.0f%%", percent*100 )
else
Text:SetText( string_cut(status:GetText(unit) or "", self.textlength) )
end
Text:Show()
else
Text:Hide()
end
end
local function Text_OnUpdate(self, parent, unit, status)
local Text = parent[self.name].Text
if status then
Text:SetText( string_cut(status:GetText(unit) or "", self.textlength) )
Text:Show()
else
Text:Hide()
end
end
local function Text_Disable(self, parent)
local f = parent[self.name]
f:Hide()
f:SetParent(nil)
f:ClearAllPoints()
end
local function Text_UpdateDB(self)
-- text fmt
local fmt = Grid2.db.profile.formatting
FmtDE[true] = fmt.longDecimalFormat
FmtDE[false] = fmt.shortDecimalFormat
FmtDES[true] = fmt.longDurationStackFormat
FmtDES[false] = fmt.shortDurationStackFormat
UpdateES = fmt.invertDurationStack and _UpdateSE or _UpdateES
UpdateDS = fmt.invertDurationStack and _UpdateSD or _UpdateDS
-- indicator dbx
local dbx = self.dbx
local theme = Grid2Frame.db.profile
local l = dbx.location
self.anchor = l.point
self.anchorRel = l.relPoint
self.offsetx = l.x
self.offsety = l.y
self.frameLevel = dbx.level
self.textlength = dbx.textlength or 16
self.textfont = Grid2:MediaFetch("font", dbx.font or theme.font) or STANDARD_TEXT_FONT
self.textsize = dbx.fontSize or theme.fontSize or 11
if dbx.fontFlags then
self.shadowAlpha = dbx.shadowDisabled and 0 or 1
self.fontFlags = dbx.fontFlags
else
self.shadowAlpha = theme.shadowDisabled and 0 or 1
self.fontFlags = theme.fontFlags
end
if dbx.duration or dbx.elapsed then
self.stack = dbx.stack
self.elapsed = dbx.elapsed
if dbx.stack then
self.updateFunc = dbx.elapsed and UpdateES or UpdateDS
else
self.updateFunc = dbx.elapsed and UpdateE or UpdateD
end
self.OnUpdate = Text_OnUpdateDE
elseif dbx.stack then
self.OnUpdate = Text_OnUpdateS
elseif dbx.percent then
self.OnUpdate = Text_OnUpdateP
else
self.OnUpdate = Text_OnUpdate
end
end
local function TextColor_OnUpdate(self, parent, unit, status)
local Text = parent[self.parentName].Text
if status then
Text:SetTextColor(status:GetColor(unit))
else
Text:SetTextColor(1, 1, 1, 1)
end
end
local function Create(indicatorKey, dbx)
local indicator = Grid2.indicators[indicatorKey] or Grid2.indicatorPrototype:new(indicatorKey)
indicator.dbx = dbx
indicator.Create = Text_Create
indicator.GetBlinkFrame = Text_GetBlinkFrame
indicator.Layout = Text_Layout
indicator.Disable = Text_Disable
indicator.UpdateDB = Text_UpdateDB
Text_UpdateDB(indicator, dbx)
Grid2:RegisterIndicator(indicator, { "text" })
local colorKey = indicatorKey .. "-color"
local TextColor = Grid2.indicators[colorKey] or Grid2.indicatorPrototype:new(colorKey)
TextColor.dbx = dbx
TextColor.parentName = indicatorKey
TextColor.Create = Grid2.Dummy
TextColor.Layout = Grid2.Dummy
TextColor.UpdateDB = Grid2.Dummy
TextColor.OnUpdate = TextColor_OnUpdate
Grid2:RegisterIndicator(TextColor, { "color" })
indicator.sideKick = TextColor
return indicator, TextColor
end
Grid2.setupFunc["text"] = Create
Grid2.setupFunc["text-color"] = Grid2.Dummy
-- }}
|
--[[
TheNexusAvenger
Class representing a view for pulling from remote repositories.
--]]
local NexusGit = require(script.Parent.Parent.Parent.Parent):GetContext(script)
local RemotePullRequest = NexusGit:GetResource("NexusGitRequest.GetRequest.RemotePullRequest")
local Directory = NexusGit:GetResource("NexusGitRequest.File.Directory")
local File = NexusGit:GetResource("NexusGitRequest.File.File")
local FileSelectionFrame = NexusGit:GetResource("UI.Frame.FileSelection.FileSelectionFrame")
local NexusWrappedInstance = NexusGit:GetResource("NexusPluginFramework.Base.NexusWrappedInstance")
local NexusScrollingFrame = NexusGit:GetResource("NexusPluginFramework.UI.Scroll.NexusScrollingFrame")
local NexusCollapsableListFrame = NexusGit:GetResource("NexusPluginFramework.UI.CollapsableList.NexusCollapsableListFrame")
local NexusEnums = NexusGit:GetResource("NexusPluginFramework.Data.Enum.NexusEnumCollection").GetBuiltInEnums()
local GitPullView = NexusWrappedInstance:Extend()
GitPullView:SetClassName("GitPullView")
GitPullView:Implements(NexusGit:GetResource("UI.View.Frame.IViewFrame"))
--[[
Creates an git pull view object.
--]]
function GitPullView:__new(Host,RemotesToBranches,DefaultRemote,DefaultBranch)
self:InitializeSuper("Frame")
--Store the host.
self:__SetChangedOverride("Host",function() end)
self.Host = Host
--Convert the remotes and branches to files.
local BranchesFiles = {}
for Remote,Branches in pairs(RemotesToBranches) do
local RemoteDirectory = Directory.new(Remote)
table.insert(BranchesFiles,RemoteDirectory)
--Add the branches.
for _,Branch in pairs(Branches) do
local BranchFile = File.new(Branch)
BranchFile:SetStatus(NexusEnums.FileStatus.Unmodified)
RemoteDirectory:AddFile(BranchFile)
end
end
--Create the list.
local RemotesListFrame = FileSelectionFrame.new(BranchesFiles)
RemotesListFrame.BorderSizePixel = 1
RemotesListFrame.Size = UDim2.new(1,0,1,-30)
RemotesListFrame.Parent = self
--Check the default branch.
local DefaultRemoteListElement = RemotesListFrame:FindFirstChild(DefaultRemote)
if DefaultRemoteListElement then
local DefaultBranchListElement = DefaultRemoteListElement:GetCollapsableContainer():FindFirstChild(DefaultBranch)
if DefaultBranchListElement then
DefaultBranchListElement.CheckedState = NexusEnums.CheckBoxState.Checked
end
end
--Create the buttons.
local CancelButton = NexusWrappedInstance.GetInstance("TextButton")
CancelButton.Size = UDim2.new(0,84,0,22)
CancelButton.Position = UDim2.new(1,-88,1,-26)
CancelButton.BackgroundColor3 = "DialogButton"
CancelButton.TextColor3 = "DialogButtonText"
CancelButton.Text = "Cancel"
CancelButton.Parent = self
self:__SetChangedOverride("CancelButton",function() end)
self.CancelButton = CancelButton
local PullButton = NexusWrappedInstance.GetInstance("TextButton")
PullButton.Size = UDim2.new(0,84,0,22)
PullButton.Position = UDim2.new(1,-176,1,-26)
PullButton.BackgroundColor3 = "DialogMainButton"
PullButton.TextColor3 = "DialogMainButtonText"
PullButton.Text = "Pull"
PullButton.Parent = self
self:__SetChangedOverride("PullButton",function() end)
self.PullButton = PullButton
--Set up the clicked events.
local DB = true
PullButton.MouseButton1Down:Connect(function()
if DB then
DB = false
--Get the selected branches.
local BranchesToPull = {}
for _,RemoteDirectory in pairs(RemotesListFrame:GetSelectedFiles()) do
for _,BranchFile in pairs(RemoteDirectory:GetFiles()) do
table.insert(BranchesToPull,{RemoteDirectory:GetFileName(),BranchFile:GetFileName()})
end
end
--Pull the selected branches.
self.object:PullCommits(BranchesToPull)
end
end)
CancelButton.MouseButton1Down:Connect(function()
if DB then
DB = false
self.object:Close()
end
end)
end
--[[
Sends a git request to pull.
--]]
function GitPullView:SendPullRequest(RemoteRepo,RemoteBranch)
RemotePullRequest.new(self.Host,RemoteRepo,RemoteBranch):SendRequest()
end
--[[
Sends the pull request to the server.
--]]
function GitPullView:PullCommits(RemoteBranches)
--Pull the branches.
for i,RemoteBranch in pairs(RemoteBranches) do
local RemoteName,BranchName = RemoteBranch[1],RemoteBranch[2]
self:UpdatePullStatus((i - 1)/#RemoteBranches,"Pulling from "..RemoteName.."/"..BranchName..".")
local Worked,Return = pcall(function()
self:SendPullRequest(RemoteName,BranchName)
end)
--Show an error if one happened.
if not Worked then
self:UpdatePullStatus(false,"Pull failed.")
warn("Pull request failed because "..tostring(Return))
return
end
end
--Show a success message.
self:UpdatePullStatus(true,"Pull successful.")
end
--[[
Updates the status of the push.
--]]
function GitPullView:UpdatePullStatus(Percent,StatusText)
if self ~= self.object then
self.object:UpdatePullStatus(Percent,StatusText)
end
end
--[[
Closes the view.
--]]
function GitPullView:Close()
self:Destroy()
end
return GitPullView |
local Pad = Entity:new()
function Pad:new(x, y, debugColor)
x = x or (Constants.SCREEN_WIDTH - (Constants.PAD_WIDTH * Constants.PAD_LENGTH)) / 2
y = y or Constants.SCREEN_HEIGHT - Constants.PAD_HEIGHT - Constants.PAD_MARGIN
local o = Entity:new(x, y, Constants.PAD_WIDTH * Constants.PAD_LENGTH, Constants.PAD_HEIGHT, nil, debugColor)
setmetatable(o, self)
self.__index = self
o.sleft = Sprites["pad_left"]
o.smid = Sprites["pad_mid"]
o.sright = Sprites["pad_right"]
o.len = Constants.PAD_LENGTH
o.velocity = Constants.PAD_VELOCITY
o.transparent = false
return o
end
function Pad:getWidth()
return self.width
end
function Pad:setLength(length)
self.width = Constants.PAD_WIDTH * length
self.len = length
end
function Pad:draw()
if self.transparent then
return
end
-- Error
if self.len < 2 then
return
end
-- Draw
Renderer.drawSprite(self.sleft, self.debugColor, self.x, self.y, Constants.PAD_WIDTH, self.height)
local pos = self.x + Constants.PAD_WIDTH
for i = 2, self.len - 1, 1 do
Renderer.drawSprite(self.smid, self.debugColor, pos, self.y, Constants.PAD_WIDTH, self.height)
pos = pos + Constants.PAD_WIDTH
end
Renderer.drawSprite(self.sright, self.debugColor, pos, self.y, Constants.PAD_WIDTH, self.height)
end
return Pad
|
function createTrunkMarker(veh)
if source ~= localPlayer then return end
local occ = getElementData(veh, "vehicleOccupation")
if occ == "National Task Force" or occ == "FBI Agent" or occ == "NSA Agent" or occ == "Police Detective" or occ == "Police Officer" or occ == "SWAT Officer" or occ == "Military Forces" or occ == "Air Force" then
if getElementData(veh,"VI:inventory") ~= false then return end
triggerServerEvent("VI:createTrunk", veh)
setElementData(source, "VI:hasObj", false)
setElementData(source, "VI:effects", false)
end
end
--addCommandHandler("trunk", createTrunkMarker)
addEvent("onClientPlayerVehicleEnter", true)
addEventHandler("onClientPlayerVehicleEnter", root, createTrunkMarker)
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
function isLaw(p)
local n =getTeamName(getPlayerTeam(p))
if n == "SWAT Team" or n == "Military Forces" or n == "Government" then
return true
else
return false
end
end
function onPlayerMarkerHit (marker)
local vehicle = getElementAttachedTo(marker)
if source == localPlayer and not getPedOccupiedVehicle(localPlayer) then
if isLaw(source) == true then
bindKey("x", "down", openInv, marker, source, vehicle)
if not openLabel then
openLabel = guiCreateLabel(0, 0.85, 1, 0.1, "Press x to open the vehicle's trunk.", true)
guiLabelSetHorizontalAlign(openLabel, "center", false)
end
end
end
end
addEvent("VI:openTrunk", true)
addEventHandler("VI:openTrunk", root, onPlayerMarkerHit)
function onPlayerMarkerLeave (marker)
if source == localPlayer and not getPedOccupiedVehicle(localPlayer) then
unbindKey("x")
if invWindow then
hideGUI (marker)
end
if openLabel and isElement(openLabel) then
destroyElement(openLabel)
openLabel = nil
end
end
end
addEvent("VI:closeTrunk", true)
addEventHandler("VI:closeTrunk", root, onPlayerMarkerLeave)
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
function openInv(keyPressed,state, marker, player, veh)
local vehicle = getElementAttachedTo(marker)
if player == localPlayer and vehicle == veh and getElementData(veh, "VI:opened") == false and not getPedOccupiedVehicle(player) then
local inv = getElementData(veh, "VI:inventory")
setElementData(veh, "VI:opened", true)
if invWindow then
guiGridListClear(itemList)
showCursor(true)
guiSetVisible(invWindow, true)
setElementData(btnTake,"VI:vehicle", veh)
for i=1, #inv do
local row = guiGridListAddRow(itemList)
guiGridListSetItemText(itemList, row, itemId, inv[i][1], false, true)
guiGridListSetItemText(itemList, row, itemName, inv[i][2], false, false)
guiGridListSetItemText(itemList, row, itemQuantity, inv[i][3], false, true)
end
if getElementData(player, "VI:hasObj") == true then
guiSetText(btnTake, "Store object")
else guiSetText(btnTake, "Take")
end
local inv = nil
else
local Width, Height = 300, 350
local screenWidth, screenHeight = guiGetScreenSize()
local X = ( screenWidth/2 ) - ( Width/2 )
local Y = ( screenHeight/2 ) - ( Height/2 )
showCursor(true)
invWindow = guiCreateWindow(X, Y, Width, Height, "AUR ~ Barriers Inventory", false)
guiWindowSetSizable(invWindow, false)
btnClose = guiCreateButton(160, 300, 120, 30, "Close", false, invWindow)
addEventHandler("onClientGUIClick", btnClose, closeGUI)
btnTake = guiCreateButton(20, 300, 120, 30, "Take", false, invWindow)
addEventHandler("onClientGUIClick", btnTake, takeObj)
setElementData(btnTake,"VI:vehicle", veh)
itemList = guiCreateGridList(10, 25, 280, 250, false, invWindow)
itemId = guiGridListAddColumn(itemList, "Id:", 0.25)
itemName = guiGridListAddColumn(itemList, "Object:", 0.40)
itemQuantity = guiGridListAddColumn(itemList, "Quantity:", 0.25)
for i=1, #inv do
local row = guiGridListAddRow(itemList)
guiGridListSetItemText(itemList, row, itemId, inv[i][1], false, true)
guiGridListSetItemText(itemList, row, itemName, inv[i][2], false, false)
guiGridListSetItemText(itemList, row, itemQuantity, inv[i][3], false, true)
end
if getElementData(player, "VI:hasObj") == true then
guiSetText(btnTake, "Store object")
end
local inv = nil
end
elseif player == localPlayer and vehicle == veh and getElementData(veh, "VI:opened") == true then exports.NGCdxmsg:createNewDxMessage( "This vehicle's trunk is currently being used by a player, please wait!", 255, 0, 0 )
end
end
function closeGUI ()
if source ~= btnClose then return end
guiSetVisible(invWindow, false)
showCursor(false)
guiGridListClear(itemList)
local veh = getElementData(btnTake,"VI:vehicle")
setElementData(veh, "VI:opened", false)
end
function hideGUI (btnORmarker)
if invWindow then
guiSetVisible(invWindow, false)
showCursor(false)
local veh = getElementData(btnORmarker,"VI:vehicle")
setElementData(veh, "VI:opened", false)
end
end
function takeObj()
if source ~= btnTake then return end
local veh = getElementData(btnTake,"VI:vehicle")
local player = localPlayer
if guiGetText(btnTake) == "Take" then
local index = guiGridListGetSelectedItem(itemList)
if index < 0 then return end
local objId = tonumber(guiGridListGetItemText(itemList, index, itemId))
local objQty = tonumber(guiGridListGetItemText(itemList, index, itemQuantity))
if objQty <= 0 then return end
updateVehInv(objId, veh, player, "-")
spawnObject(player, objId )
hideGUI (btnTake)
setElementData(veh, "VI:opened", false)
local index = nil
local objId = nil
local veh = nil
elseif guiGetText(btnTake) == "Store object" then
local objs = getAttachedElements(localPlayer)
local inv = getElementData(veh, "VI:inventory")
for i,v in ipairs (objs) do
if getElementType(v) == "object" then
for i=1, #inv do
if inv[i][1] == tostring(getElementModel(v)) then
objId = getElementModel(v)
obj = v
updateVehInv(objId, veh, player, "+")
setElementData(veh, "VI:opened", false)
hideGUI (btnTake)
unbindKey("mouse2")
triggerServerEvent("destroyObj", obj )
setElementData(player, "VI:hasObj", false)
toggleEffects(localPlayer)
if placeLabel and isElement(placeLabel) then
destroyElement(placeLabel)
placeLabel = nil
end
end
end
end
end
if not objId then exports.NGCdxmsg:createNewDxMessage( "You can't store that object in this vehicle!", 255, 0, 0 ) setControlState("walk", true) end
objId = nil
veh = nil
obj = nil
end
end
function updateVehInv (objID, veh, player, action)
if localPlayer == player then
local inv = getElementData(veh, "VI:inventory")
for i=1,#inv do
if tonumber(inv[i][1]) == objID then
local id = inv[i][1]
local name = inv[i][2]
if action == "-" then
qty = tonumber(inv[i][3]) - 1
elseif action == "+" then
qty = tonumber(inv[i][3]) + 1
end
inv[i]= {id, name, qty}
setElementData(veh, "VI:inventory", inv)
qty = nil
end
end
updateGUI(veh, localPlayer)
local inv = nil
end
end
function updateGUI (veh, player)
if localPlayer == player then
if invWindow then
guiGridListClear(itemList)
local inv = getElementData(veh, "VI:inventory")
showCursor(true)
guiSetVisible(invWindow, true)
for i=1, #inv do
local row = guiGridListAddRow(itemList)
guiGridListSetItemText(itemList, row, itemId, inv[i][1], false, true)
guiGridListSetItemText(itemList, row, itemName, inv[i][2], false, false)
guiGridListSetItemText(itemList, row, itemQuantity, inv[i][3], false, true)
end
local inv = nil
end
end
end
---------------------------------------------------------------------------------------------------
-------------------------------Obj functions (pick/drop/spawn/despawn)-----------------
function spawnObject (thePlayer, objID)
if thePlayer == localPlayer and objID and getElementData(thePlayer, "VI:hasObj") ~= true and isLaw(thePlayer)==true then
unbindKey("x")
triggerServerEvent("spawnObj", thePlayer, objID)
if openLabel and isElement(openLabel) then
destroyElement(openLabel)
openLabel = nil
end
if not placeLabel then
placeLabel = guiCreateLabel(0, 0.8, 1, 0.1, "Press RMB to place the object.", true)
guiLabelSetHorizontalAlign(placeLabel, "center", false)
end
end
end
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
local handlersAdded = {}
function addColHandlers ()
if not handlersAdded[source] then
addEventHandler("onClientColShapeHit", source, destroyPickObj)
addEventHandler("onClientColShapeLeave", source, onColLeave)
handlersAdded[source] = true
end
end
addEvent("addColHandlers", true)
addEventHandler("addColHandlers", root, addColHandlers)
-------------------------
function destroyPickObj (hitElement)
local e = getElementAttachedTo(source)
if isElement(e) == true then else return end
local objID = getElementModel (e)
if hitElement == localPlayer and not getPedOccupiedVehicle(localPlayer) and getElementData(localPlayer, "VI:hasObj") ~= true and isLaw(localPlayer)==true then
if not pickLabel then
pickLabel = guiCreateLabel(0, 0.8, 1, 0.1, "Press x to pick the object.", true)
guiLabelSetHorizontalAlign(pickLabel, "center", false)
end
bindKey("x", "down", deleteObj, hitElement, objID, source)
end
end
function deleteObj (key, keyState, thePlayer , objID, col)
if isElementWithinColShape(thePlayer, col) then
triggerServerEvent("onBarrierGetDestroyed", col)
spawnObject(thePlayer, objID)
end
unbindKey("x")
if pickLabel and isElement(pickLabel) then
destroyElement(pickLabel)
pickLabel = nil
end
end
---------------------
function onColLeave (hitElement)
if hitElement == localPlayer and not getPedOccupiedVehicle(localPlayer) and isLaw(hitElement) == true then
unbindKey("x")
if pickLabel and isElement(pickLabel) then
destroyElement(pickLabel)
pickLabel = nil
end
end
end
-----------------------------------------------------------------------------
---------------Effects while carrying object---------------------------
addEvent("toggleEffects", true)
function toggleEffects(player)
if source == localPlayer or player == localPlayer then
local state = getElementData(localPlayer, "VI:effects")
if state ~= true then
setPedWeaponSlot(localPlayer, 0)
addEventHandler("onClientPlayerWeaponSwitch", localPlayer, onWeaponSwitch)
setControlState("walk", true)
toggleControl("jump", false)
toggleControl("sprint", false)
toggleControl("enter_exit", false)
setElementData(localPlayer, "VI:effects", true)
elseif state == true then
removeEventHandler("onClientPlayerWeaponSwitch", localPlayer, onWeaponSwitch)
setControlState("walk", false)
toggleControl("jump", true)
toggleControl("sprint", true)
toggleControl("enter_exit", true)
setElementData(localPlayer, "VI:effects", false)
if placeLabel and isElement(placeLabel) then
destroyElement(placeLabel)
placeLabel = nil
end
end
end
end
addEventHandler("toggleEffects", root, toggleEffects)
function onWeaponSwitch ()
setPedWeaponSlot(source, 0)
end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
function onBarrierHitByExplosion( x, y, z, theType )
for index, barrier in ipairs(getElementsByType("object")) do
if (getElementModel ( barrier ) == 1228) or (getElementModel ( barrier ) == 1238) or (getElementModel ( barrier ) == 1459) or (getElementModel ( barrier ) == 2060) then
local barrierx, barriery, barrierz = getElementPosition(barrier)
local distance = getDistanceBetweenPoints2D(barrierx, barriery, x, y)
if (distance <= 8) then
local attached = getAttachedElements(barrier)
for i,v in ipairs (attached) do
if getElementType(v) == "colshape" then
triggerServerEvent("onBarrierGetDestroyed", v )
end
end
end
end
end
end
addEventHandler("onClientExplosion", root, onBarrierHitByExplosion)
function onBarrierHitByVehicle ( hitElement, force )
if hitElement and getElementType(hitElement) == "object" then
if (getElementModel ( hitElement ) == 1228 or getElementModel ( hitElement ) == 1459 and force >30) or (getElementModel ( hitElement ) == 1238 or getElementModel ( hitElement ) == 2060) then
local attached = getAttachedElements(hitElement)
for i,v in ipairs (attached) do
if getElementType(v) == "colshape" then
triggerServerEvent("onBarrierGetDestroyed", v )
end
end
end
end
end
addEventHandler("onClientVehicleCollision", root, onBarrierHitByVehicle)
function barriersUnBreakable (object, thePlayer)
local objectid = getElementModel(object)
if objectid ~= 1238 then
setObjectBreakable(object,false)
end
end
addEvent("setBarriersUnBreakable", true)
addEventHandler("setBarriersUnBreakable", root, barriersUnBreakable)
addEvent("clearLabels", true)
function onVehicleEnterDeleteLabels()
if source == localPlayer then
unbindKey("x")
unbindKey("mouse2")
if pickLabel and isElement(pickLabel) then
destroyElement(pickLabel)
pickLabel = nil
end
if openLabel and isElement(openLabel) then
destroyElement(openLabel)
openLabel = nil
end
if placeLabel and isElement(placeLabel) then
destroyElement(placeLabel)
placeLabel = nil
end
end
end
addEventHandler("clearLabels", root, onVehicleEnterDeleteLabels)
addEventHandler("onClientPlayerVehicleEnter", root, onVehicleEnterDeleteLabels)
function getPositionFromElementAtOffset( element, x, y, z )
if not x or not y or not z then
return x, y, z
end
local matrix = getElementMatrix ( element )
local offX = x * matrix[1][1] + y * matrix[2][1] + z * matrix[3][1] + matrix[4][1]
local offY = x * matrix[1][2] + y * matrix[2][2] + z * matrix[3][2] + matrix[4][2]
local offZ = x * matrix[1][3] + y * matrix[2][3] + z * matrix[3][3] + matrix[4][3]
return offX, offY, offZ
end
function getVehicleWheelPosition( vehicle, wheel)
local x, y, z = 0, 0, 0
local minX, minY, minZ, maxX, maxY, maxZ = getElementBoundingBox(vehicle)
if wheel == 1 then
x, y, z = getPositionFromElementAtOffset(vehicle, minX, maxY, minZ)
elseif wheel == 2 then
x, y, z = getPositionFromElementAtOffset(vehicle, minX, -maxY, minZ)
elseif wheel == 3 then
x, y, z = getPositionFromElementAtOffset(vehicle, maxX, maxY, minZ)
elseif wheel == 4 then
x, y, z = getPositionFromElementAtOffset(vehicle, maxX, -maxY, minZ)
end
return x, y, z
end
stingers = {}
addEvent("CSGrecStinger",true)
addEventHandler("CSGrecStinger",localPlayer,function(v) table.insert(stingers,v) end)
addEventHandler("onClientRender", root,
function ()
if ( isPedInVehicle( localPlayer ) ) and ( getPlayerWantedLevel() >= 1 ) then
local theVehicle = getPedOccupiedVehicle( localPlayer )
if ( theVehicle ) then
local wx1, wy1, wz1 = getVehicleWheelPosition( theVehicle, 1 )
local wx2, wy2, wz2 = getVehicleWheelPosition( theVehicle, 2 )
local wx3, wy3, wz3 = getVehicleWheelPosition( theVehicle, 3 )
local wx4, wy4, wz4 = getVehicleWheelPosition( theVehicle, 4 )
for k, v in ipairs(stingers) do
if isElement(v) then
if getElementData( v, "isStinger2" ) == true then
local x,y,z = getElementPosition(localPlayer)
local vx, vy, vz = getElementPosition( v )
if getDistanceBetweenPoints2D(x,y,vx,vy) > 10 then return end
if getDistanceBetweenPoints2D( wx1, wy1, vx, vy ) <= 2.33 then
setVehicleWheelStates( theVehicle, 1, -1, -1, -1 )
end
if getDistanceBetweenPoints2D( wx2, wy2, vx, vy ) <= 2.33 then
setVehicleWheelStates( theVehicle, -1, 1, -1, -1 )
end
if getDistanceBetweenPoints2D( wx3, wy3, vx, vy ) <= 2.33 then
setVehicleWheelStates( theVehicle, -1, -1, 1, -1 )
end
if getDistanceBetweenPoints2D( wx4, wy4, vx, vy ) <= 2.33 then
setVehicleWheelStates( theVehicle, -1, -1, -1, 1 )
end
end
end
end
end
end
end
)
|
-- Generated by CSharp.lua Compiler
local System = System
local SlipeMtaDefinitions
local SlipeSharedRadar
local SlipeSharedUtilities
System.import(function (out)
SlipeMtaDefinitions = Slipe.MtaDefinitions
SlipeSharedRadar = Slipe.Shared.Radar
SlipeSharedUtilities = Slipe.Shared.Utilities
end)
System.namespace("Slipe.Client.Radar", function (namespace)
-- <summary>
-- Class representing a minimap blip
-- </summary>
namespace.class("Blip", function (namespace)
local __ctor1__, __ctor2__, __ctor3__, __ctor4__, __ctor5__
__ctor1__ = function (this, element)
SlipeSharedRadar.SharedBlip.__ctor__(this, element)
end
-- <summary>
-- Creates a blip from all the createBlip parameters
-- </summary>
__ctor2__ = function (this, vector, icon, color, size, ordering, visibleDistance)
__ctor1__(this, SlipeMtaDefinitions.MtaClient.CreateBlip(vector.X, vector.Y, vector.Z, icon, size, color:getR(), color:getG(), color:getB(), color:getA(), ordering, visibleDistance))
end
-- <summary>
-- Creates a standard red blip
-- </summary>
__ctor3__ = function (this, vector)
__ctor2__(this, vector:__clone__(), 0, SlipeSharedUtilities.Color.getRed(), 2, 0, 16383)
end
-- <summary>
-- Creates a blip attached to an MTA element
-- </summary>
__ctor4__ = function (this, physicalElement, icon, color, size, ordering, visibleDistance)
__ctor1__(this, SlipeMtaDefinitions.MtaClient.CreateBlipAttachedTo(physicalElement:getMTAElement(), icon, size, color:getR(), color:getG(), color:getB(), color:getA(), ordering, visibleDistance))
end
-- <summary>
-- Creates a standard red blip attached to an MTA element
-- </summary>
__ctor5__ = function (this, physicalElement)
__ctor4__(this, physicalElement, 0, SlipeSharedUtilities.Color.getRed(), 2, 0, 16383)
end
return {
__inherits__ = function (out)
return {
out.Slipe.Shared.Radar.SharedBlip
}
end,
__ctor__ = {
__ctor1__,
__ctor2__,
__ctor3__,
__ctor4__,
__ctor5__
},
__metadata__ = function (out)
return {
methods = {
{ ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement },
{ ".ctor", 0x606, __ctor2__, System.Numerics.Vector3, System.Int32, out.Slipe.Shared.Utilities.Color, System.Int32, System.Int32, System.Single },
{ ".ctor", 0x106, __ctor3__, System.Numerics.Vector3 },
{ ".ctor", 0x606, __ctor4__, out.Slipe.Shared.Elements.PhysicalElement, System.Int32, out.Slipe.Shared.Utilities.Color, System.Int32, System.Int32, System.Single },
{ ".ctor", 0x106, __ctor5__, out.Slipe.Shared.Elements.PhysicalElement }
},
class = { 0x6, System.new(out.Slipe.Shared.Elements.DefaultElementClassAttribute, 2, 8 --[[ElementType.Blip]]) }
}
end
}
end)
end)
|
local utils = require("utils")
local drawing = {}
function drawing.drawSprite(spriteMeta, x, y, r, sx, sy, ox, oy)
love.graphics.draw(spriteMeta.image, spriteMeta.quad, x, y, r, sx, sy, ox, oy)
end
function drawing.getCurvePoint(start, stop, control, percent)
local startMul = (1 - percent)^2
local controlMul = 2 * (1 - percent) * percent
local stopMul = percent^2
local x = start[1] * startMul + control[1] * controlMul + stop[1] * stopMul
local y = start[2] * startMul + control[2] * controlMul + stop[2] * stopMul
return x, y
end
function drawing.getSimpleCurve(start, stop, control, resolution)
control = control or {(start[1] + stop[1]) / 2, (start[2] + stop[2]) / 2}
resolution = resolution or 16
local res = {}
for i = 0, resolution do
local x, y = drawing.getCurvePoint(start, stop, control, i / resolution)
table.insert(res, x)
table.insert(res, y)
end
return res
end
function drawing.getRelativeQuad(spriteMeta, x, y, width, height, hideOverflow, realSize)
local image = spriteMeta.image
local imageWidth, imageHeight = image:getDimensions()
local quadX, quadY, quadWidth, quadHeight = spriteMeta.quad:getViewport()
local offsetX, offsetY = 0, 0
if realSize then
offsetX = spriteMeta.offsetX
offsetY = spriteMeta.offsetY
x += offsetX
y += offsetY
if x > 0 then
offsetX = 0
end
if y > 0 then
offsetY = 0
end
end
-- Make sure the width/height doesn't go outside the original quad
if hideOverflow ~= false then
width = math.min(width, quadWidth - x)
height = math.min(height, quadHeight - y)
if x < 0 then
width += x
x = 0
end
if y < 0 then
height += y
y = 0
end
end
return love.graphics.newQuad(quadX + x, quadY + y, width, height, imageWidth, imageHeight), offsetX, offsetY
end
-- TODO - Vertical offset is wrong based on scale?
function drawing.printCenteredText(text, x, y, width, height, font, fontSize, trim)
font = font or love.graphics.getFont()
fontSize = fontSize or 1
if trim ~= false then
text = utils.trim(text)
end
local fontHeight = font:getHeight()
local fontLineHeight = font:getLineHeight()
local longest, lines = font:getWrap(text, width / fontSize)
local textHeight = (#lines - 1) * (fontHeight * fontLineHeight) + fontHeight
local offsetX = 1
local offsetY = math.floor((height - textHeight) / 2) + 1
love.graphics.push()
love.graphics.translate(x + offsetX, y + offsetY)
love.graphics.scale(fontSize, fontSize)
love.graphics.printf(text, 0, 0, width / fontSize, "center")
love.graphics.pop()
end
function drawing.addCenteredText(batch, text, x, y, width, height, font, fontSize, trim)
font = font or love.graphics.getFont()
fontSize = fontSize or 1
if trim ~= false then
text = utils.trim(text)
end
local fontHeight = font:getHeight()
local fontLineHeight = font:getLineHeight()
local longest, lines = font:getWrap(text, width / fontSize)
local textHeight = (#lines - 1) * (fontHeight * fontLineHeight) + fontHeight
local offsetX = 1
local offsetY = math.floor((height - textHeight) / 2) + 1
local wrapLimit = math.floor(width / fontSize)
batch:addf(text, wrapLimit, "center", x + offsetX, y + offsetY, 0, fontSize, fontSize)
end
function drawing.getTrianglePoints(x, y, theta, height)
theta = theta - math.pi / 2
local px1 = x + height * math.cos(theta + math.pi / 4)
local py1 = y + height * math.sin(theta + math.pi / 4)
local px2 = x + height * math.cos(theta - math.pi / 4)
local py2 = y + height * math.sin(theta - math.pi / 4)
return x, y, px1, py1, px2, py2
end
function drawing.triangle(mode, x, y, theta, height)
love.graphics.polygon(mode, drawing.getTrianglePoints(x, y, theta, height))
end
function drawing.callKeepOriginalColor(func)
local pr, pg, pb, pa = love.graphics.getColor()
func()
love.graphics.setColor(pr, pg, pb, pa)
end
function drawing.getDashedLineSegments(x1, y1, x2, y2, dash, space)
dash = dash or 6
space = space or 4
local length = math.sqrt((x1 - x2)^2 + (y1 - y2)^2)
local progress = 0
local segments = {}
while progress < length do
local startPercent = progress / length
local stopPercent = math.min(length, progress + dash) / length
local startX = x1 + (x2 - x1) * startPercent
local startY = y1 + (y2 - y1) * startPercent
local stopX = x1 + (x2 - x1) * stopPercent
local stopY = y1 + (y2 - y1) * stopPercent
table.insert(segments, {startX, startY, stopX, stopY})
progress += dash + space
end
return segments
end
function drawing.drawDashedLine(x1, y1, x2, y2, dash, space)
local segments = drawing.getDashedLineSegments(x1, y1, x2, y2, dash, space)
for _, segment in ipairs(segments) do
love.graphics.line(segment)
end
end
return drawing |
require 'BatchBRNN'
------------------------------------------------------------------------
--[[ BatchBRNNReLU ]] --
-- Based On BatchBRNN. Adds ClippedReLU non-linearity to Vanilla BRNN.
------------------------------------------------------------------------
local BatchBRNNReLU, parent = torch.class('cudnn.BatchBRNNReLU', 'cudnn.BatchBRNN')
function BatchBRNNReLU:__init(inputDim, outputDim)
parent.__init(self, inputDim, outputDim)
local rnn = self.rnn
rnn.mode = 'CUDNN_RNN_RELU'
rnn:reset()
self:insert(cudnn.ClippedReLU(20, true), 6)
end |
-----------------------------------------
-- ID: 4656
-- Scroll of Shell
-- Teaches the white magic Shell
-----------------------------------------
function onItemCheck(target)
return target:canLearnSpell(48)
end
function onItemUse(target)
target:addSpell(48)
end |
local function contains(tab, val)
for index, value in ipairs (tab) do
if value == val then
return true
end
end
return false
end
return contains; |
--- Table of enabled/disabled abilities.
-- @module invokation.const.ability_list
local M = {
item_tome_of_knowledge = false,
item_courier = false,
item_branches = false,
item_quelling_blade = false,
item_tpscroll = false,
item_travel_boots = false,
item_travel_boots_2 = false,
item_phase_boots = false,
item_power_treads = false,
item_moon_shard = false,
}
return M
|
-- Some parts copy pasted from _fallback.
local player= Var "Player"
local el_pos= cons_players[player].gameplay_element_positions
local Judgment
local tani= setmetatable({upper= true}, text_and_number_interface_mt)
local tani_params= {
sx= el_pos.combo_xoffset or 0, sy= el_pos.combo_yoffset or 30,
tx= 8, nx= -8, ta= left, na= right, text_section= "Combo"
}
local ShowComboAt = THEME:GetMetric("Combo", "ShowComboAt");
local Pulse = THEME:GetMetric("Combo", "PulseCommand");
local PulseLabel = THEME:GetMetric("Combo", "PulseLabelCommand");
local JudgeCmds = {}
local function set_judge_commands()
if cons_players[player].flags.gameplay.still_judge then
local function judge_general_effect(self)
self:diffusealpha(1):sleep(.8):april_linear(.1):diffusealpha(0)
end
for i, w in ipairs{"W2", "W3", "W4", "W5", "Miss"} do
JudgeCmds["TapNoteScore_"..w]= judge_general_effect
end
JudgeCmds.TapNoteScore_W1= function(self)
self:glowblink():effectperiod(.05):effectcolor1(color("1,1,1,0"))
:effectcolor2(color("1,1,1,0.25"))
judge_general_effect(self)
end
Pulse= noop_nil
PulseLabel= noop_nil
else
local function judge_general_effect(self, i)
local jscale= el_pos.judgment_scale
self:diffusealpha(1):zoom((1 + (.1 * (6 - i))) * jscale)
:april_linear(.05):zoom(jscale):sleep(.8)
:april_linear(.1):zoomy(.5 * jscale):zoomx(2 * jscale):diffusealpha(0)
end
for i, w in ipairs{"W2", "W3", "W4"} do
JudgeCmds["TapNoteScore_"..w]= function(self)
judge_general_effect(self, i + 1)
end
end
JudgeCmds.TapNoteScore_W1= function(self)
self:glowblink():effectperiod(.05):effectcolor1(color("1,1,1,0"))
:effectcolor2(color("1,1,1,0.25"))
judge_general_effect(self, 1)
end
JudgeCmds.TapNoteScore_W5= function(self)
self:vibrate():effectmagnitude(4, 8, 8)
judge_general_effect(self, 5)
end
JudgeCmds.TapNoteScore_Miss= function(self)
local jscale= el_pos.judgment_scale
self:diffusealpha(1):zoom(jscale):y(-20 * jscale)
:april_linear(.8):y(20 * jscale):sleep(.8)
:april_linear(.1):zoomy(.5 * jscale):zoomx(2 * jscale):diffusealpha(0)
end
end
end
set_judge_commands()
local NumberMinZoom = THEME:GetMetric("Combo", "NumberMinZoom");
local NumberMaxZoom = THEME:GetMetric("Combo", "NumberMaxZoom");
local NumberMaxZoomAt = THEME:GetMetric("Combo", "NumberMaxZoomAt");
local LabelMinZoom = THEME:GetMetric("Combo", "LabelMinZoom");
local LabelMaxZoom = THEME:GetMetric("Combo", "LabelMaxZoom");
local tns_reverse= TapNoteScore:Reverse()
local tns_opposition= {
[tns_reverse["TapNoteScore_W1"]]= "TapNoteScore_Miss",
[tns_reverse["TapNoteScore_W2"]]= "TapNoteScore_W5",
[tns_reverse["TapNoteScore_W3"]]= "TapNoteScore_W4",
[tns_reverse["TapNoteScore_W4"]]= "TapNoteScore_W3",
[tns_reverse["TapNoteScore_W5"]]= "TapNoteScore_W2",
[tns_reverse["TapNoteScore_Miss"]]= "TapNoteScore_W1",
TapNoteScore_W1= "TapNoteScore_Miss",
TapNoteScore_W2= "TapNoteScore_W5",
TapNoteScore_W3= "TapNoteScore_W4",
TapNoteScore_W4= "TapNoteScore_W3",
TapNoteScore_W5= "TapNoteScore_W2",
TapNoteScore_Miss= "TapNoteScore_W1"
}
local tns_texts= {
TapNoteScore_W1= "Ridiculous",
TapNoteScore_W2= "Fantastic",
TapNoteScore_W3= "Excellent",
TapNoteScore_W4= "Great",
TapNoteScore_W5= "Decent",
TapNoteScore_Miss= "Miss"
}
local tns_windows= {}
local err_tex_width= 512
local err_tex_height= 16
local herr_tex_width= err_tex_width * .5
local herr_tex_height= err_tex_height * .5
local error_width= _screen.w * .4
local herror_width= error_width * .5
local min_offset= 0
local max_offset= 0
do
local window_scale= PREFSMAN:GetPreference("TimingWindowScale")
local windows= {
PREFSMAN:GetPreference("TimingWindowSecondsW1") * window_scale,
PREFSMAN:GetPreference("TimingWindowSecondsW2") * window_scale,
PREFSMAN:GetPreference("TimingWindowSecondsW3") * window_scale,
PREFSMAN:GetPreference("TimingWindowSecondsW4") * window_scale,
PREFSMAN:GetPreference("TimingWindowSecondsW5") * window_scale,
PREFSMAN:GetPreference("TimingWindowSecondsW5") * window_scale*1.25,
}
local tns_to_window= {}
for i= 1, 5 do
local tns_name= "TapNoteScore_W"..i
tns_to_window[tns_name]= windows[i]
tns_windows[i]= {windows[i], tns_name}
end
local error_window_name= cons_players[player].error_history_threshold
local error_window= windows[6]
if tns_to_window[error_window_name] then
error_window= tns_to_window[error_window_name]
end
min_offset= -error_window
max_offset= error_window
tns_windows.TapNoteScore_W1= {0, windows[1]}
tns_windows.TapNoteScore_W2= {windows[1], windows[2]}
tns_windows.TapNoteScore_W3= {windows[2], windows[3]}
tns_windows.TapNoteScore_W4= {windows[3], windows[4]}
tns_windows.TapNoteScore_W5= {windows[4], windows[5]}
tns_windows.TapNoteScore_Miss= {windows[5], windows[6]}
end
local function offset_to_judge(offset)
local aboff= math.abs(offset)
for i= 1, #tns_windows do
if aboff <= tns_windows[i][1] then return tns_windows[i][2] end
end
return "TapNoteScore_Miss"
end
local judge_colors= fetch_color("judgment")
local dark_judge_colors= {}
local bright_judge_colors= {}
for name, c in pairs(judge_colors) do
dark_judge_colors[name]= adjust_luma(c, .5)
bright_judge_colors[name]= adjust_luma(c, 2)
end
local def_col= fetch_color("text")
local function fjtc(j)
return judge_colors[j] or def_col
end
local function offset_to_color(offset)
return bright_judge_colors[offset_to_judge(offset)] or def_col
end
local function offset_to_dark_color(offset)
return dark_judge_colors[offset_to_judge(offset)] or def_col
end
local function scale_off(offset, min, max)
return scale(clamp(offset, min_offset, max_offset), min_offset, max_offset,
min, max)
end
local function offset_to_x(offset)
return scale_off(offset, 0, err_tex_width)
end
local function offset_to_w(offset)
return scale_off(offset, -herror_width, herror_width)
end
local error_history_size= cons_players[player].error_history_size
local history_alpha= 0
if error_history_size > 0 then
history_alpha= .25^(1 / error_history_size)
end
local error_bar_mt= {
__index= {
create_actors= function(self)
return Def.ActorFrame{
InitCommand= function(subself)
self.container= subself
end,
player_flags_changedMessageCommand= function(subself, param)
if param.pn ~= player then return end
if param.name ~= "error_bar" then return end
if cons_players[player].flags.gameplay.error_bar then
self.hidden= false
self.container:hibernate(0)
else
self.hidden= true
self.container:hibernate(math.huge)
end
end,
Def.ActorFrame{
InitCommand= function(subself)
subself:hibernate(math.huge)
end,
Def.ActorFrameTexture{
InitCommand= function(subself)
self.prev_frame_aft= subself
subself:setsize(err_tex_width, err_tex_height)
:EnableAlphaBuffer(true):Create()
:EnablePreserveTexture(false)
:Draw()
self.prev_frame_tex= subself:GetTexture()
self.prev_frame_sprite:visible(true)
end,
Def.Sprite{
InitCommand= function(subself)
self.prev_frame_sprite= subself
subself:xy(herr_tex_width, herr_tex_height):visible(false)
:setsize(err_tex_width, err_tex_height)
end
}
},
Def.ActorFrameTexture{
InitCommand= function(subself)
self.aft= subself
subself:setsize(err_tex_width, 16)
:EnableAlphaBuffer(true):Create()
:EnablePreserveTexture(false)
:Draw()
self.texture= subself:GetTexture()
self.prev_frame_sprite:SetTexture(self.texture)
self.past_error:visible(true)
self.curr_error:visible(true)
end,
Def.Sprite{
InitCommand= function(subself)
self.past_error= subself
subself:xy(herr_tex_width, herr_tex_height):visible(false)
:setsize(err_tex_width, err_tex_height)
:diffusealpha(history_alpha)
:SetTexture(self.prev_frame_tex)
end
},
Def.Quad{
InitCommand= function(subself)
self.curr_error= subself
subself:xy(herr_tex_width, 8):setsize(1, 16):visible(false)
end
}
},
},
Def.Sprite{
InitCommand= function(subself)
self.cum_error= subself
subself:SetTexture(self.texture)
end
},
Def.Quad{
InitCommand= function(subself)
self.recent_error= subself:horizalign(left)
end
},
}
end,
add_error= function(self, offset)
self.recent_error:SetWidth(offset_to_w(offset))
:diffuse(offset_to_color(offset))
self.curr_error:x(offset_to_x(offset))
:diffuse(offset_to_dark_color(offset))
self.prev_frame_aft:Draw()
self.aft:Draw()
end,
set_pos_scale= function(self, x, y, s)
self.container:xy(x, y)
self.cum_error:xy(0, 8 * s):setsize(error_width, 16 * s)
self.recent_error:xy(0, 8 * s):setsize(0, 8 * s)
end,
}}
local errbar= setmetatable({}, error_bar_mt)
local non_mine_tnses= {
TapNoteScore_W1= true,
TapNoteScore_W2= true,
TapNoteScore_W3= true,
TapNoteScore_W4= true,
TapNoteScore_W5= true,
TapNoteScore_Miss= true,
TapNoteScore_CheckpointHit= true,
TapNoteScore_CheckpointMiss= true,
}
local tns_values= {}
local function add_value_set(enum_table)
for i, tns in ipairs(enum_table) do
local metric_name= "PercentScoreWeight" .. ToEnumShortString(tns)
if metric_name ~= "PercentScoreWeightNone" then
local value= THEME:GetMetric("ScoreKeeperNormal", metric_name)
tns_values[tns]= value
end
end
end
add_value_set(TapNoteScore)
add_value_set(HoldNoteScore)
local tns_reverse= TapNoteScore:Reverse()
local tns_cont_combo= tns_cont_combo()
local tns_maint_combo= tns_maint_combo()
local tns_inc_miss_combo= tns_reverse[THEME:GetMetric("Gameplay", "MaxScoreToIncrementMissCombo")]
local prev_combo= -1
local function get_seconds()
return STATSMAN:GetCurStageStats():GetStepsSeconds()
end
local function add_to_col(col_score, judge, max_value, offset)
local step_value= tns_values[judge]
if not step_value then return end
col_score.dp= col_score.dp + step_value
col_score.mdp= col_score.mdp + max_value
col_score.judge_counts[judge]= col_score.judge_counts[judge] + 1
col_score.step_timings[#col_score.step_timings+1]= {
time= get_seconds(), judge= judge, offset= offset}
end
local function add_tn_to_col(col_score, tapnote, max_value)
add_to_col(col_score, tapnote:GetTapNoteResult():GetTapNoteScore(),
max_value, tapnote:GetTapNoteResult():GetTapNoteOffset())
end
local function set_combo_stuff(param)
local toast= cons_players[player].toasty
if toast then
toast.remaining= toast.remaining - 1
toast.progress= toast.progress + 1
if toast.remaining <= 0 then
cons_players[player].toasty= nil
end
end
local combo= param.Misses or param.Combo
if not combo or combo < ShowComboAt then
tani:hide()
return
end
tani:unhide()
local label_text= ""
if param.Combo then
label_text= "Combo"
else
label_text= "Misses"
end
local wombo= combo
local combo_qual= cons_players[player].combo_quality
if toast and toast.remaining > 0 then
wombo= toast.progress
label_text= "Misses"
end
tani:set_text(label_text)
--tani:set_number(wordify_number(wombo))
tani:set_number(("%i"):format(wombo))
if combo_qual then
if combo_qual.worst_tns then
local color= fjtc(combo_qual.worst_tns)
if toast and toast.remaining > 0 then
color= fjtc(toast.judge)
end
if color then
tani.text:diffuse(color)
tani.number:diffuse(color)
end
end
end
param.Zoom= scale(combo, 0, NumberMaxZoomAt, NumberMinZoom, NumberMinZoom)
param.Zoom= clamp(param.Zoom, NumberMinZoom, NumberMaxZoom)
param.LabelZoom= scale(combo, 0, NumberMaxZoomAt, LabelMinZoom, LabelMaxZoom)
Pulse(tani.number, param)
PulseLabel(tani.text, param)
end
local function disp_offset_from_judge(judge)
local width= tns_windows[judge][2] - tns_windows[judge][1]
local offset= tns_windows[judge][1] + (width * MersenneTwister.Random())
if MersenneTwister.Random() > .5 then
offset= offset * -1
end
return offset
end
local judgment_conf_names= {
judgment= true, combo= true, error_bar= true,
}
local function set_display_judgment(disp_judge, disp_offset)
local text= tns_texts[disp_judge]
if text then
if cons_players[player].flags.gameplay.error_bar then
errbar:add_error(disp_offset)
end
Judgment:playcommand("Reset")
:settext(get_string_wrapper("JudgementNames", text):upper())
:diffuse(fjtc(disp_judge))
:visible(true)
JudgeCmds[disp_judge](Judgment)
end
end
local args= {
Name= "Judgement",
InitCommand= function(self)
if newskin_available() then
self:draworder(newfield_draw_order.under_field)
end
end,
Def.ActorFrame{
normal_text(
"Judgment", "", nil, fetch_color("gameplay.text_stroke"), 0, 0, 1,
center, {
ResetCommand= cmd(xy,0,0;finishtweening;stopeffect;visible,false)}),
tani:create_actors("tani", tani_params),
errbar:create_actors(),
InitCommand= function(self)
Judgment= self:GetChild("Judgment")
Judgment:visible(false):zoom(el_pos.judgment_scale)
tani:hide()
tani.container:zoom(el_pos.combo_scale)
tani.text:strokecolor(fetch_color("gameplay.text_stroke"))
tani.number:strokecolor(fetch_color("gameplay.text_stroke"))
tani.number:wrapwidthpixels((_screen.cx / el_pos.combo_scale) - 16)
self:playcommand("gameplay_conf_changed", {pn= player, thing= next(judgment_conf_names)})
end,
ToastyAchievedMessageCommand= function(self,params)
if params.PlayerNumber == player then
--Trace("ToastyAchievedMessageCommand params:")
--rec_print_table(params)
if cons_players[player].flags.gameplay.allow_toasty then
cons_players[player].toasty= {
judge= "TapNoteScore_Miss", remaining= 5, progress= 0 }
end
end
end,
player_flags_changedMessageCommand= function(self, param)
if param.pn ~= player then return end
if param.name ~= "still_judge" then return end
set_judge_commands()
Judgment:zoom(el_pos.judgment_scale)
set_display_judgment("TapNoteScore_W1", .0215)
end,
gameplay_conf_changedMessageCommand= function(self, param)
if param.pn ~= player then return end
if not judgment_conf_names[param.thing] then return end
self:xy(el_pos.judgment_xoffset, el_pos.judgment_yoffset)
tani:move_to(el_pos.combo_xoffset, el_pos.combo_yoffset)
tani.container:zoom(el_pos.combo_scale)
Judgment:zoom(el_pos.judgment_scale)
set_display_judgment("TapNoteScore_W1", .0215)
errbar:set_pos_scale(el_pos.error_bar_xoffset, el_pos.error_bar_yoffset, el_pos.error_bar_scale)
end,
JudgmentMessageCommand=
function(self, param)
if param.Player ~= player then return end
local fake_judge= cons_players[player].fake_judge
local fake_score= cons_players[player].fake_score
local stage_stats= cons_players[player].stage_stats
if true_gameplay then
local max_step_value= 0
if param.HoldNoteScore then
max_step_value= tns_values.HoldNoteScore_Held
elseif param.TapNoteScore then
if non_mine_tnses[param.TapNoteScore] then
max_step_value= tns_values.TapNoteScore_W1
end
end
local taps= param.Notes
local holds= param.Holds
local col_scores= cons_players[player].column_scores
if taps and col_scores then
add_to_col(col_scores[0], param.TapNoteScore, max_step_value, param.TapNoteOffset)
local function add_set(set)
for track, tapnote in pairs(set) do
add_tn_to_col(col_scores[track], tapnote, max_step_value)
end
end
if taps then add_set(taps) end
end
if param.HoldNoteScore and col_scores then
add_to_col(col_scores[0], param.HoldNoteScore, max_step_value)
add_to_col(col_scores[param.FirstTrack+1], param.HoldNoteScore, max_step_value)
end
end
if param.HoldNoteScore then
if not tns_values[param.HoldNoteScore] then
Trace("tns_values for " .. param.HoldNoteScore .. " is nil.")
end
if fake_judge then
if fake_judge() ~= "TapNoteScore_Miss" then
fake_score.dp= fake_score.dp + tns_values.HoldNoteScore_Held
fake_score.HoldNoteScore_Held=
(fake_score.HoldNoteScore_Held or 0) + 1
else
fake_score.dp= fake_score.dp + tns_values.HoldNoteScore_LetGo
fake_score.HoldNoteScore_LetGo=
(fake_score.HoldNoteScore_LetGo or 0) + 1
end
else
fake_score[param.HoldNoteScore]=
(fake_score[param.HoldNoteScore] or 0) + 1
fake_score.dp= fake_score.dp + tns_values[param.HoldNoteScore]
end
return
end
local this_tns= param.TapNoteScore
if this_tns == "TapNoteScore_CheckpointHit"
or this_tns == "TapNoteScore_CheckpointMiss" then
if fake_judge and fake_judge() ~= "TapNoteScore_Miss" then
fake_score.dp= fake_score.dp + tns_values.TapNoteScore_CheckpointHit
else
fake_score.dp= fake_score.dp + tns_values.TapNoteScore_CheckpointMiss
end
return
end
if this_tns == "TapNoteScore_HitMine"
or this_tns == "TapNoteScore_AvoidMine"
or this_tns == "TapNoteScore_None" then return end
local firsts= stage_stats.firsts
if firsts then
if not firsts[this_tns] then
firsts[this_tns]= get_seconds()
end
end
local disp_judge= this_tns
local disp_offset= param.TapNoteOffset
if fake_judge then
disp_judge= fake_judge()
disp_offset= disp_offset_from_judge(disp_judge)
fake_score.judge_counts[disp_judge]=
fake_score.judge_counts[disp_judge] + 1
fake_score.dp= fake_score.dp + tns_values[disp_judge]
fake_score.step_timings[#fake_score.step_timings+1]= {
time= get_seconds(), judge= disp_judge, offset= disp_offset}
end
local rev_disp= tns_reverse[disp_judge]
if fake_score.combo_is_misses then
if rev_disp <= tns_inc_miss_combo then
fake_score.combo= (fake_score.combo or 0) + 1
elseif rev_disp >= tns_cont_combo then
fake_score.combo= 1
fake_score.combo_is_misses= false
end
else
if rev_disp < tns_maint_combo then
fake_score.combo= 0
if rev_disp <= tns_inc_miss_combo then
fake_score.combo= 1
fake_score.combo_is_misses= true
end
elseif rev_disp >= tns_cont_combo then
fake_score.combo= (fake_score.combo or 0) + 1
end
end
if cons_players[player].toasty then
disp_judge= cons_players[player].toasty.judge
disp_offset= disp_offset_from_judge(disp_judge)
end
local combo_qual= cons_players[player].combo_quality
if combo_qual then
local prev_worst= combo_qual.worst_tns
if prev_worst then
combo_qual.worst_tns= math.min(rev_disp, prev_worst)
else
combo_qual.worst_tns= rev_disp
end
if not prev_worst or rev_disp < prev_worst or
-- starting a new combo.
(prev_worst < tns_maint_combo and rev_disp >= tns_cont_combo)
then
combo_qual.worst_tns= rev_disp
end
end
set_display_judgment(disp_judge, disp_offset)
if fake_judge then
if fake_score.combo_is_misses then
set_combo_stuff({Misses= fake_score.combo})
else
set_combo_stuff({Combo= fake_score.combo})
end
end
end,
ComboCommand= function(self, param)
if prev_combo == -1 then
prev_combo= math.floor((param.Combo or 0) / 1000) * 1000
end
if param.Combo then
if param.Combo >= prev_combo + 1000 then
prev_combo= math.floor(param.Combo / 1000) * 1000
if cons_players[player].flags.gameplay.combo_confetti then
activate_confetti("combo", true, player)
end
end
else
prev_combo= 0
end
if not cons_players[player].fake_judge then
set_combo_stuff(param)
end
end,
},
}
args[1].OnCommand= THEME:GetMetric("Judgment", "JudgmentOnCommand")
return Def.ActorFrame(args)
|
local sql = require("sqlite3")
local conn = sql.open("yot.db")
local options = require("options")
print("Creating database...")
conn:exec([[
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT PRIMARY KEY,
persistent_roles TEXT DEFAULT "{}",
disabled_commands TEXT DEFAULT "{}",
disabled_modules TEXT DEFAULT "{}",
command_permissions TEXT DEFAULT "{}",
prefix TEXT DEFAULT "]]..options.defaultPrefix..[[",
warning_length REAL DEFAULT ]]..options.warningLength..[[,
default_mute_length REAL DEFAULT ]]..options.muteLength..[[,
warning_kick_level REAL DEFAULT ]]..options.warningKickLevel..[[,
warning_ban_level REAL DEFAULT ]]..options.warningBanLevel..[[,
delete_command_messages BOOLEAN DEFAULT 0 NOT NULL CHECK (delete_command_messages IN (0,1)),
public_log_channel TEXT,
staff_log_channel TEXT,
suggestions_channel TEXT,
welcome_channel TEXT,
muted_role TEXT,
advertising_allowed_role TEXT
);
CREATE TABLE IF NOT EXISTS warnings (
guild_id TEXT,
user_id TEXT,
level REAL,
end_timestamp REAL,
is_active BOOLEAN DEFAULT 1 NOT NULL CHECK (is_active IN (0,1)),
PRIMARY KEY (guild_id, user_id),
FOREIGN KEY (guild_id) REFERENCES guild_settings(guild_id)
);
CREATE TABLE IF NOT EXISTS mutes (
guild_id TEXT,
user_id TEXT,
length REAL,
end_timestamp REAL,
is_active BOOLEAN DEFAULT 1 NOT NULL CHECK (is_active IN (0,1)),
PRIMARY KEY (guild_id, user_id),
FOREIGN KEY (guild_id) REFERENCES guild_settings(guild_id)
);
CREATE TABLE IF NOT EXISTS persistent_roles (
guild_id TEXT,
user_id TEXT,
roles TEXT,
PRIMARY KEY (guild_id, user_id),
FOREIGN KEY (guild_id) REFERENCES guild_settings(guild_id)
);
CREATE TABLE IF NOT EXISTS webhooks (
channel_id TEXT PRIMARY KEY,
webhook_id TEXT
);
]])
print("Done.") |
local Drawable = Class()
function Drawable:init(pos, image)
self.pos = pos
self.image = love.graphics.newImage(image)
end
function Drawable:draw()
love.graphics.draw(self.image, self.pos.x, self.pos.y)
end
return Drawable
|
local key = @key
local capacity = tonumber(@capacity)
local timestamp = tonumber(@timestamp)
local requestId = @requestId
local count = redis.call("zcard", key)
local allowed = count < capacity
if allowed then
redis.call("zadd", key, timestamp, requestId)
end
return { allowed, count } |
local e=_ENV
function debughook(event, line)
local now = os.time()
if now - when > 3 then
coroutine.yield()
end
end
function catch(err)
return "Script timed out"
end
sandbox_env = {
ipairs = ipairs,
next = next,
pairs = pairs,
pcall = pcall,
tonumber = tonumber,
tostring = tostring,
type = type,
unpack = unpack,
coroutine = { create = coroutine.create, resume = coroutine.resume,
running = coroutine.running, status = coroutine.status,
wrap = coroutine.wrap },
string = { byte = string.byte, char = string.char, find = string.find,
format = string.format, gmatch = string.gmatch, gsub = string.gsub,
len = string.len, lower = string.lower, match = string.match,
rep = string.rep, reverse = string.reverse, sub = string.sub,
upper = string.upper },
table = { insert = table.insert, maxn = table.maxn, remove = table.remove,
sort = table.sort },
math = { abs = math.abs, acos = math.acos, asin = math.asin,
atan = math.atan, atan2 = math.atan2, ceil = math.ceil, cos = math.cos,
cosh = math.cosh, deg = math.deg, exp = math.exp, floor = math.floor,
fmod = math.fmod, frexp = math.frexp, huge = math.huge,
ldexp = math.ldexp, log = math.log, log10 = math.log10, max = math.max,
min = math.min, modf = math.modf, pi = math.pi, pow = math.pow,
rad = math.rad, random = math.random, sin = math.sin, sinh = math.sinh,
sqrt = math.sqrt, tan = math.tan, tanh = math.tanh },
os = { date = os.date, clock = os.clock, difftime = os.difftime, time = os.time },
d = function() debug.sethook(debughook, 'l') end
}
when = os.time()
function eval(sender, channel, params)
local sb_orig_env=_G
local ls = loadstring
if not params then return nil end
when = os.time()
setfenv(0, sandbox_env)
local func, err = ls([[d() return ]] .. params )
if err then
sb_orig_env.setfenv(0, sb_orig_env)
debug.sethook()
say(channel or sender, "<b>Error in eval:</b> " .. err)
return
end
local okay, rv = xpcall(coroutine.wrap(func), catch)
sb_orig_env.setfenv(0, sb_orig_env)
debug.sethook()
if not okay then
say(channel or sender, "<b>Error in eval:</b> " .. rv)
else
rv = tostring(rv)
for line in rv:gmatch("([^\r\n]+)") do
say(channel or sender, sender .. ": " .. line)
end
end
end
registerHelperFunction("eval", eval, "Evaluates lua code and returns the output", 8) |
GM.PickupHistory = {}
GM.PickupHistoryLast = 0
GM.PickupHistoryTop = ScrH() / 2
GM.PickupHistoryWide = 300
GM.PickupHistoryCorner = surface.GetTextureID( "gui/corner8" )
--[[---------------------------------------------------------
Name: gamemode:HUDWeaponPickedUp( wep )
Desc: The game wants you to draw on the HUD that a weapon has been picked up
-----------------------------------------------------------]]
function GM:HUDWeaponPickedUp( wep )
if ( !IsValid( LocalPlayer() ) || !LocalPlayer():Alive() ) then return end
if ( !IsValid( wep ) ) then return end
if ( !isfunction( wep.GetPrintName ) ) then return end
local pickup = {}
pickup.time = CurTime()
pickup.name = wep:GetPrintName()
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 255, 200, 50, 255 )
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
if ( self.PickupHistoryLast >= pickup.time ) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
--[[---------------------------------------------------------
Name: gamemode:HUDItemPickedUp( itemname )
Desc: An item has been picked up..
-----------------------------------------------------------]]
function GM:HUDItemPickedUp( itemname )
if ( !IsValid( LocalPlayer() ) || !LocalPlayer():Alive() ) then return end
local pickup = {}
pickup.time = CurTime()
pickup.name = "#"..itemname
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 180, 255, 180, 255 )
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
if ( self.PickupHistoryLast >= pickup.time ) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
--[[---------------------------------------------------------
Name: gamemode:HUDAmmoPickedUp( itemname, amount )
Desc: Ammo has been picked up..
-----------------------------------------------------------]]
function GM:HUDAmmoPickedUp( itemname, amount )
if ( !IsValid( LocalPlayer() ) || !LocalPlayer():Alive() ) then return end
-- Try to tack it onto an exisiting ammo pickup
if ( self.PickupHistory ) then
for k, v in pairs( self.PickupHistory ) do
if ( v.name == "#" .. itemname .. "_ammo" ) then
v.amount = tostring( tonumber( v.amount ) + amount )
v.time = CurTime() - v.fadein
return
end
end
end
local pickup = {}
pickup.time = CurTime()
pickup.name = "#" .. itemname .. "_ammo"
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 180, 200, 255, 255 )
pickup.amount = tostring( amount )
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
local w, h = surface.GetTextSize( pickup.amount )
pickup.xwidth = w
pickup.width = pickup.width + w + 16
if ( self.PickupHistoryLast >= pickup.time ) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
function GM:HUDDrawPickupHistory()
if ( self.PickupHistory == nil ) then return end
local x, y = ScrW() - self.PickupHistoryWide - 20, self.PickupHistoryTop
local tall = 0
local wide = 0
for k, v in pairs( self.PickupHistory ) do
if ( !istable( v ) ) then
Msg( tostring( v ) .."\n" )
PrintTable( self.PickupHistory )
self.PickupHistory[ k ] = nil
return
end
if ( v.time < CurTime() ) then
if ( v.y == nil ) then v.y = y end
v.y = ( v.y * 5 + y ) / 6
local delta = ( v.time + v.holdtime ) - CurTime()
delta = delta / v.holdtime
local alpha = 255
local colordelta = math.Clamp( delta, 0.6, 0.7 )
-- Fade in/out
if ( delta > 1 - v.fadein ) then
alpha = math.Clamp( ( 1.0 - delta ) * ( 255 / v.fadein ), 0, 255 )
elseif ( delta < v.fadeout ) then
alpha = math.Clamp( delta * ( 255 / v.fadeout ), 0, 255 )
end
v.x = x + self.PickupHistoryWide - (self.PickupHistoryWide * ( alpha / 255 ) )
local rx, ry, rw, rh = math.Round( v.x - 4 ), math.Round( v.y - ( v.height / 2 ) - 4 ), math.Round( self.PickupHistoryWide + 9 ), math.Round( v.height + 8 )
local bordersize = 8
surface.SetTexture( self.PickupHistoryCorner )
surface.SetDrawColor( v.color.r, v.color.g, v.color.b, alpha )
surface.DrawTexturedRectRotated( rx + bordersize/2, ry + bordersize / 2, bordersize, bordersize, 0 )
surface.DrawTexturedRectRotated( rx + bordersize/2, ry + rh -bordersize / 2, bordersize, bordersize, 90 )
surface.DrawRect( rx, ry + bordersize, bordersize, rh-bordersize * 2 )
surface.DrawRect( rx + bordersize, ry, v.height - 4, rh )
surface.SetDrawColor( 230 * colordelta, 230 * colordelta, 230 * colordelta, alpha )
surface.DrawRect( rx + bordersize + v.height - 4, ry, rw - ( v.height - 4 ) - bordersize * 2, rh )
surface.DrawTexturedRectRotated( rx + rw - bordersize / 2 , ry + rh - bordersize / 2, bordersize, bordersize, 180 )
surface.DrawTexturedRectRotated( rx + rw - bordersize / 2 , ry + bordersize / 2, bordersize, bordersize, 270 )
surface.DrawRect( rx + rw-bordersize, ry + bordersize, bordersize, rh-bordersize * 2 )
draw.SimpleText( v.name, v.font, v.x + v.height + 9, v.y - ( v.height / 2 ) + 1, Color( 0, 0, 0, alpha * 0.5 ) )
draw.SimpleText( v.name, v.font, v.x + v.height + 8, v.y - ( v.height / 2 ), Color( 255, 255, 255, alpha ) )
if ( v.amount ) then
draw.SimpleText( v.amount, v.font, v.x + self.PickupHistoryWide + 1, v.y - ( v.height / 2 ) + 1, Color( 0, 0, 0, alpha * 0.5 ), TEXT_ALIGN_RIGHT )
draw.SimpleText( v.amount, v.font, v.x + self.PickupHistoryWide, v.y - ( v.height / 2 ), Color( 255, 255, 255, alpha ), TEXT_ALIGN_RIGHT )
end
y = y + ( v.height + 16 )
tall = tall + v.height + 18
wide = math.Max( wide, v.width + v.height + 24 )
if ( alpha == 0 ) then self.PickupHistory[ k ] = nil end
end
end
self.PickupHistoryTop = ( self.PickupHistoryTop * 5 + ( ScrH() * 0.75 - tall ) / 2 ) / 6
self.PickupHistoryWide = ( self.PickupHistoryWide * 5 + wide ) / 6
end
|
local sm = require("slot_machine")
local image = require("image")
local buffer = require("doubleBuffering")
local shell = require("shell")
local casino = require("casino")
local event = require("event")
local machine = sm.Machine:new()
local bet = 1
local consoleLines = {}
for i = 1, 11 do
consoleLines[i] = ""
end
local function drawRightMenu()
buffer.drawRectangle(63, 2, 21, 12, 0, 0, " ")
buffer.drawText(63, 2, 0xAAAAAA, "Вывод:")
for i = 1, #consoleLines do
buffer.drawText(63, 2 + i, (15 - #consoleLines + i) * 0x111111, consoleLines[i])
end
buffer.drawRectangle(63, 16, 21, 6, 0xFFFFFF, 0, " ")
for i = 1, 6 do
if bet == 7 - i then
buffer.drawRectangle(63, 15 + i, 21, 1, 0xFF8A00, 0, " ")
end
buffer.drawText(73, 15 + i, 0, tostring(7 - i))
end
buffer.drawChanges()
end
local function message(msg)
table.remove(consoleLines, 1)
table.insert(consoleLines, tostring(msg))
drawRightMenu()
end
local function initStaticData()
local pre_symbols = {
{ "fish", 5, "Фугу" },
{ "cookie", 5, "Печенье" },
{ "quartz", 5, "Кристалл истинного кварца" },
{ "emerald", 10, "Изумруд" },
{ "crystal", 10, "Лазутроновый кристалл" },
{ "golden_apple", 20, "Золотое яблоко" },
{ "diamond", 50, "Алмаз" },
{ "uu_matter", 100, "Материя" },
{ "creeper", 200, "Голова крипера" }
}
local imagesFolder = "/home/images/one_armed_creeper/"
shell.execute("md " .. imagesFolder)
machine.symbols = {}
for i = 1, #pre_symbols do
local symbol = sm.Symbol:new()
local imgPath = imagesFolder .. pre_symbols[i][1] .. ".pic"
local downloadUrl = REPOSITORY .. "/resources/images/one_armed_creeper/" .. pre_symbols[i][1] .. ".pic"
casino.downloadFile(downloadUrl, imgPath)
symbol.image = image.load(imgPath)
symbol.name = pre_symbols[i][3]
symbol.ratio = pre_symbols[i][2]
machine.symbols[i] = symbol
end
end
local function calculateRewardRatio(symbols)
local a, b, c = symbols[1], symbols[2], symbols[3]
if a == b and b == c then
return a.ratio
end
if a == b or b == c then
return 1
end
if a == c then
return 2
end
return 0
end
local function roll()
local result = {}
local columns = {}
local columnSize = #machine.symbols
for i = 1, 3 do
columns[i] = machine.rollColumn()
result[i] = columns[i][columnSize]
end
for i = 1, columnSize do
for j = 1, 3 do
buffer.drawImage(-10 + j * 17, 4, columns[j][i].image)
end
buffer.drawChanges()
os.sleep(0.2)
end
return result
end
local function drawRewards()
buffer.drawText(6, 17, 0, "Пара смежных символов: " .. bet * 1 .. " ")
buffer.drawText(6, 18, 0, "Пара символов по краям: " .. bet * 2 .. " ")
local symbols = machine.symbols
for i = 1, #symbols do
buffer.drawText(7, 19 + i, 0, symbols[i].name .. ": " .. symbols[i].ratio * bet .. " ")
end
buffer.drawChanges()
end
local function drawStatic()
buffer.setResolution(85, 30)
buffer.clear(0xBFBFBF)
buffer.drawRectangle(3, 2, 81, 28, 0xFFFFFF, 0, " ")
buffer.drawRectangle(61, 1, 2, 32, 0xBFBFBF, 0, " ")
buffer.drawRectangle(1, 14, 60, 1, 0xBFBFBF, 0, " ")
buffer.drawRectangle(63, 14, 21, 1, 0xBFBFBF, 0, " ")
buffer.drawRectangle(63, 22, 21, 1, 0xBFBFBF, 0, " ")
buffer.drawRectangle(63, 26, 21, 1, 0xBFBFBF, 0, " ")
buffer.drawRectangle(63, 23, 21, 3, 0xc7ffc6, 0, " ")
buffer.drawRectangle(63, 27, 21, 3, 0xffc6c6, 0, " ")
buffer.drawText(5, 16, 0, "Награды:")
buffer.drawText(6, 19, 0, "Три символа в ряд:")
buffer.drawText(70, 15, 0, 'Ставка')
buffer.drawText(70, 24, 0, 'Играть')
buffer.drawText(70, 28, 0, 'Выход')
buffer.drawChanges()
end
initStaticData()
drawStatic()
drawRightMenu()
drawRewards()
for j = 1, 3 do
buffer.drawImage(-10 + j * 17, 4, machine.symbols[#machine.symbols].image)
end
buffer.drawChanges()
while true do
local _, _, x, y = event.pull("touch")
-- Right menu buttons
if x >= 63 and x <= 84 then
-- Bet buttons
if y >= 16 and y <= 21 then
local new_bet = 22 - y
if new_bet ~= bet then
bet = new_bet
drawRightMenu()
drawRewards()
end
end
-- Play button
if y >= 23 and y <= 25 then
local payed, reason = casino.takeMoney(bet)
if payed then
message("Вы поставили " .. bet)
local ratio = calculateRewardRatio(roll())
if ratio > 0 then
message("Вы выиграли " .. bet * ratio)
casino.reward(bet * ratio)
else
message("Вы проиграли")
end
casino.gameIsOver()
else
message(reason)
end
end
-- Exit button
if y >= 27 and y <= 29 then
error("Exit by request")
end
end
end
|
function onCreate()
makeLuaSprite('theSky','chaos',-900,-300)
addLuaSprite('theSky',false)
makeAnimatedLuaSprite('Pork','Porker Lewis',1400,-500)
addAnimationByPrefix('Pork','Porker Lewis','Porker FG',24,true)
addLuaSprite('Pork',true)
end
function onBeatHit()-- for every beat
objectPlayAnimation('Pork','Porker FG',true)
end |
UIElements = {}
-- Adapted from Simply-Love-SM5/Scripts/SL-Helpers.lua
function UIElements.Border(width, height, bw)
return Def.ActorFrame {
Def.Quad {
Name = "MaskSource",
InitCommand = function(self)
self:zoomto(width, height):MaskSource(true)
end
},
Def.Quad {
Name = "MaskDest",
InitCommand = function(self)
self:zoomto(width+2*bw,height+2*bw):MaskDest()
end
},
Def.Quad {
Name = "ClearBuffer",
InitCommand = function(self)
self:diffusealpha(0):clearzbuffer(true)
end
},
}
end
-- Basic clickable button implementation with quads
function UIElements.QuadButton(z, depth)
local t = Def.Quad{
InitCommand = function(self)
self:z(z)
end,
OnCommand = function(self)
local screen = SCREENMAN:GetTopScreen()
if screen ~= nil then
BUTTON:AddButton(self, screen:GetName(), depth)
end
end,
MouseOverCommand = function(self) end,
MouseOutCommand = function(self) end,
MouseUpCommand = function(self, params) end,
MouseDownCommand = function(self, params) end,
MouseClickCommand = function(self, params) end,
MouseReleaseCommand = function(self, params) end,
MouseDragCommand = function(self, params) end,
MouseHoldCommand = function(self, params) end,
}
return t
end
-- Basic clickable button implementation with quads
function ButtonDemo(z)
local t = Def.ActorFrame{
RolloverUpdateCommand = function(self, params)
self:PlayCommandsOnChildren("RolloverUpdate", params)
end,
ClickCommand = function(self, params)
self:PlayCommandsOnChildren("Click", params)
end,
DragUpdateCommand = function(self, params)
self:xy(params.MouseX, params.MouseY)
end,
}
t[#t+1] = UIElements.Border(150, 50, 5)..{
InitCommand = function(self)
self:visible(false):diffuse(color("#000000"))
end,
RolloverUpdateCommand = function(self, params)
if params.update == "over" then
self:visible(true)
TOOLTIP:Show()
TOOLTIP:SetText(string.format("X:%0.2f Y:%0.2f", self:GetTrueX(), self:GetTrueY()))
end
if params.update == "out" then
self:visible(false)
TOOLTIP:Hide()
end
end
}
t[#t+1] = UIElements.QuadButton(z, 1)..{
InitCommand= function(self)
self:z(z):zoomto(150,50):diffuse(color("#000000")):diffusealpha(0.5)
end,
MouseOverCommand = function(self) self:GetParent():playcommand("RolloverUpdate",{update = "over"}) end,
MouseOutCommand = function(self) self:GetParent():playcommand("RolloverUpdate",{update = "out"}) end,
MouseUpCommand = function(self,params) self:diffuse(color("#FF0000")):diffusealpha(0.5) self:GetParent():playcommand("Click",{update = "OnMouseUp", event = params.event}) end,
MouseDownCommand = function(self,params) self:diffuse(color("#00FF00")):diffusealpha(0.5) self:GetParent():playcommand("Click",{update = "OnMouseDown", event = params.event}) end,
MouseClickCommand = function(self,params) self:diffuse(color("#0000FF")):diffusealpha(0.5) self:GetParent():playcommand("Click",{update = "OnMouseClicked", event = params.event}) end,
MouseReleaseCommand = function(self,params) self:diffuse(color("#FF00FF")):diffusealpha(0.5) self:GetParent():playcommand("Click",{update = "OnMouseReleased", event = params.event}) end,
MouseDragCommand = function(self, params) self:GetParent():playcommand("DragUpdate", params) end,
}
t[#t+1] = LoadFont("Common Normal") .. {
InitCommand= function(self)
self:y(0):zoom(0.6):settext("init")
end,
ClickCommand = function(self, params)
self:settextf("X:%.0f Y:%.0f \nAngle:%.0f \n%s",self:GetTrueX(), self:GetTrueY(), self:GetTrueRotationZ()%360, params.event)
end,
}
return t
end
-- Checkboxes
function UIElements.CheckBox(z, checked)
local zoom = 0.15
local checked = checked
local t = Def.ActorFrame{
OnCommand = function(self)
self:playcommand("Toggle")
end,
ChildMouseClickCommand = function(self)
if checked then
checked = false
self:playcommand("Uncheck")
self:RunCommandsOnChildren(function(self) self:playcommand("Uncheck") end)
else
checked = true
self:playcommand("Check")
self:RunCommandsOnChildren(function(self) self:playcommand("Check") end)
end
end,
CheckCommand = function(self)
end,
UncheckCommand = function(self)
end
}
t[#t+1] = UIElements.QuadButton(z, 1) .. {
InitCommand = function(self)
self:zoomto(zoom*100,zoom*100)
self:diffuse(COLOR.TextMain)
end,
MouseDownCommand = function(self)
self:diffuse(COLOR.TextSub2)
end,
MouseUpCommand = function(self)
self:diffuse(COLOR.TextMain)
end,
MouseReleaseCommand = function(self)
self:diffuse(COLOR.TextMain)
end
}
t[#t+1] = LoadActor(THEME:GetPathG("", "_x"))..{
InitCommand = function(self)
self:zoom(zoom)
end,
CheckCommand = function(self)
self:finishtweening()
self:smooth(0.1)
self:zoom(zoom)
self:diffusealpha(1)
end,
UncheckCommand = function(self)
self:finishtweening()
self:smooth(0.1)
self:zoom(0)
self:diffusealpha(0)
end
}
return t
end
function UIElements.Slider(z, width)
local zoom = 0.15
local t = Def.ActorFrame{
SliderMovedCommand = function(self, params)
self:GetChild("ValueText"):settext(params.Value)
end,
}
t[#t+1] = UIElements.QuadButton(z+1, 0) .. {
Name = "SliderBar",
InitCommand = function(self)
self:zoomto(width, zoom*100/2)
self:halign(0)
end,
MouseOverCommand = function(self) end,
MouseOutCommand = function(self) end,
MouseUpCommand = function(self, params) end,
MouseDownCommand = function(self, params)
local mouseX = clamp(params.MouseX,0,width)
self:GetParent():GetChild("SliderHandle"):x(mouseX)
self:GetParent():playcommand("SliderMoved", {Value = mouseX/width})
end,
MouseClickCommand = function(self, params) end,
MouseReleaseCommand = function(self, params) end,
MouseDragCommand = function(self, params)
local mouseX = clamp(params.MouseX,0,width)
self:GetParent():GetChild("SliderHandle"):x(mouseX)
self:GetParent():playcommand("SliderMoved", {Value = mouseX/width})
end,
}
t[#t+1] = UIElements.QuadButton(z, 0) .. {
Name = "SliderHandle",
InitCommand = function(self)
self:zoomto(zoom*100,zoom*100)
self:diffuse(COLOR.TextMain)
self:x(0)
end,
MouseOverCommand = function(self) end,
MouseOutCommand = function(self) end,
MouseUpCommand = function(self, params) end,
MouseDownCommand = function(self, params) end,
MouseClickCommand = function(self, params) end,
MouseReleaseCommand = function(self, params) end,
MouseDragCommand = function(self, params)
local mouseX = clamp(params.MouseX,0,width)
self:x(mouseX)
self:GetParent():playcommand("SliderMoved", {Value = mouseX/width})
end,
}
t[#t+1] = LoadFont("Common Normal") .. {
Name = "ValueText",
InitCommand = function(self)
self:x(width + 10):zoom(0.6):halign(0):diffuse(color("#000000"))
end;
}
return t
end
function UIElements.DoubleSlider()
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "Default",
id = "MarsRenameControl",
PlaceObj('XTemplateWindow', {
'__class', "XDialog",
'Padding', box(0, 200, 0, 0),
'HAlign', "center",
'VAlign', "center",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XImage",
'Dock', "box",
'HAlign', "center",
'VAlign', "top",
'Image', "UI/Common/paradox_account.tga",
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idRenameTitle",
'Dock', "top",
'HAlign', "center",
'TextFont', "ParadoxAccountItemTitle",
'TextColor', RGBA(129, 202, 233, 255),
'RolloverTextColor', RGBA(129, 202, 233, 255),
'Translate', true,
}),
PlaceObj('XTemplateTemplate', {
'__template', "MarsEdit",
'Margins', box(0, 15, 0, 0),
'MinWidth', 428,
'MaxWidth', 428,
}),
PlaceObj('XTemplateWindow', {
'__class', "XToolBar",
'Id', "idToolbar",
'IdNode', false,
'Margins', box(0, 20, 0, 0),
'Dock', "top",
'HAlign', "center",
'LayoutHSpacing', 120,
'Background', RGBA(0, 0, 0, 0),
'Toolbar', "RenameActionBar",
'Show', "text",
'ButtonTemplate', "MenuEntry",
}),
PlaceObj('XTemplateAction', {
'ActionId', "ok",
'ActionName', T{6895, --[[XTemplate MarsRenameControl ActionName]] "OK"},
'ActionToolbar', "RenameActionBar",
'ActionShortcut', "Enter",
'ActionGamepad', "ButtonA",
'OnActionEffect', "close",
}),
PlaceObj('XTemplateAction', {
'ActionId', "rename",
'ActionName', T{817350877792, --[[XTemplate MarsRenameControl ActionName]] "RENAME"},
'ActionToolbar', "RenameActionBar",
'ActionGamepad', "ButtonY",
'__condition', function (parent, context) return Platform.console and context and context.console_show end,
}),
PlaceObj('XTemplateAction', {
'ActionId', "cancel",
'ActionName', T{5450, --[[XTemplate MarsRenameControl ActionName]] "CANCEL"},
'ActionToolbar', "RenameActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "close",
}),
}),
})
|
-- Use the current selection to create a Larger than Life rule
-- with a Custom neighborhood
--
-- Instructions:
-- 1. Draw the neigborhood as cells
-- 2. Make a square selection containing the cells
-- 3. Run this script and a rule is created with the correct
-- range and custom neighborhood definition
--
-- Selection must be square and have a side length which is an
-- odd number from 3 to 81 (which equates to ranges 1 to 40)
--
-- Author: Chris Rowett (crowett@gmail.com), Sep 2020
local g = golly()
local minlen = 3
local maxlen = 81
-- check for selection
local selrect = g.getselrect()
if #selrect == 0 then
g.warn("Please make a square selection and try again.", false)
g.exit("")
end
-- selection must be square, with an odd side length from 3 to 99
local x, y, wd, ht = table.unpack(selrect)
if wd ~= ht then
g.warn("Selection must be square.", false)
g.exit("")
end
if (wd & 1) ~= 1 then
g.warn("Selection dimension must be odd.", false)
g.exit("")
end
if wd < minlen or wd > maxlen then
g.warn("Selection dimension must be from "..minlen.." to "..maxlen..".", false)
g.exit("")
end
-- hex characters
local hexcharacters = "0123456789abcdef"
-- get the list of alive cells in the selection
local selcells = g.getcells(selrect)
-- build a bitmap of set cells
local bitmap = {}
for i = 1, wd * ht do
bitmap[i] = 0
end
-- populate bitmap from cells
local inc = 2
if (#selcells & 1) == 1 then inc = 3 end
for i = 1, #selcells - 1, inc do
offset = (selcells[i] - x) + wd * (selcells[i + 1] - y) + 1
bitmap[offset] = 1
end
-- build the hexadecimal custom neighborhood string from the bitmap
local midy = ht // 2 + 1
local midx = wd // 2 + 1
local i = 3;
local index = 1
local value = 0
local output = ""
for y = 1, ht do
for x = 1, wd do
-- ignore the middle cell
if not (y == midy and x == midx) then
-- convert each 4 cells into a hex digit
state = bitmap[index]
if state > 0 then
value = value | (1 << i)
end
i = i - 1
if i < 0 then
output = output..hexcharacters:sub(value + 1, value + 1)
i = 3
value = 0
end
end
index = index + 1
end
end
-- create a Custom rule with the neighborhood and range
local rule = g.getrule()
local algo = g.getalgo()
local numstates = g.numstates()
-- check whether to create an LtL or HROT format rule
if algo == "Larger than Life" and rule:find(",M") then
rule = "R"..(wd // 2)..",C"..numstates..",M0,S1..1,B1..1,N@"..output
g.setrule(rule)
else
rule = "R"..(wd // 2)..",C"..numstates..",S1,B1,N@"..output
g.setrule(rule)
end
g.note("Created Larger than Life rule with Custom Neighborhood:\n\n"..rule, false)
|
-- load module
luabt = require('luabt')
function create_timer_node(seconds)
local timer = nil
return function()
if timer == nil then
-- reset the timer
timer = os.clock() + seconds
end
-- has the timer expired?
if os.clock() > timer then
-- reset timer for next time
timer = nil
return false, true
else
return true
end
end
end
-- define a memory behavior tree
timer_root_node = {
type = "sequence*",
children = {
function()
print("waiting for one second...")
return false, true
end,
create_timer_node(1),
function()
print("waiting for three seconds...")
return false, true
end,
create_timer_node(3),
function()
print("waiting for two seconds...")
return false, true
end,
create_timer_node(2),
}
}
-- instantiate a behavior tree
timer_bt = luabt.create(timer_root_node)
-- tick the behavior tree until it has finished (running == false)
while timer_bt() do end
|
local EmaiUtil = {}
EmaiUtil.S_FORMAT_RESULT = {
STR_IS_EMPTY = 1; -- 邮箱账号为空
INCORRECT_FORMAT = 2; -- 邮箱格式错误
CORRECT_FORMAT = 3; -- 邮箱格式正确
}
-- 判断邮箱格式是否正确
function EmaiUtil.judgeEmailFormat(email)
if email == nil or string.trim(email) == "" then
return EmaiUtil.S_FORMAT_RESULT.STR_IS_EMPTY
elseif string.isRightEmail(email) then
return EmaiUtil.S_FORMAT_RESULT.CORRECT_FORMAT
end
return EmaiUtil.S_FORMAT_RESULT.INCORRECT_FORMAT
end
return EmaiUtil |
--[[---------------------------------------------------------------------------
DarkRP custom jobs
---------------------------------------------------------------------------
This file contains your custom jobs.
This file should also contain jobs from DarkRP that you edited.
Note: If you want to edit a default DarkRP job, first disable it in darkrp_config/disabled_defaults.lua
Once you've done that, copy and paste the job to this file and edit it.
The default jobs can be found here:
https://github.com/FPtje/DarkRP/blob/master/gamemode/config/jobrelated.lua
For examples and explanation please visit this wiki page:
https://darkrp.miraheze.org/wiki/DarkRP:CustomJobFields
Generated using: DarkRP | Job Generator
https://csite.io/tools/gmod-darkrp-job
---------------------------------------------------------------------------]]
TEAM_GUARD = DarkRP.createJob("Guard", {
color = Color(165, 0, 0, 255),
model = {
"models/player/odessa.mdl",
"models/player/mossman_arctic.mdl"
},
description = [[You are hired to protect people or property. Bankers usually hire you the most.]],
weapons = {"m9k_sig_p229r"},
command = "guard",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = true,
candemote = true,
category = "Citizens"
})
TEAM_BANK = DarkRP.createJob("Bank Worker", {
color = Color(55, 249, 0, 255),
model = {
"models/player/barney.mdl",
"models/player/gman_high.mdl",
"models/player/magnusson.mdl"
},
description = [[You can build in the "Official Bank" or make your own. Protect and manage people's possessions. You are the only person legally allowed to own/possess money printers. It is recommended that you hire a few guards.]],
weapons = {},
command = "banker",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens"
})
TEAM_GUN = DarkRP.createJob("Gun Dealer", {
color = Color(255, 150, 0, 255),
model = {"models/player/monk.mdl"},
description = [[Deal guns to anyone, but not kids, thats fucked up.]],
weapons = {},
command = "gund",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens"
})
TEAM_BMD = DarkRP.createJob("Black Market Dealer", {
color = Color(0, 0, 0, 255),
model = {
"models/player/eli.mdl",
"models/player/gman_high.mdl",
"models/player/mossman_arctic.mdl",
"models/player/leet.mdl"
},
description = [[You sell questionable things to questionable people.]],
weapons = {},
command = "bmd",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens"
})
TEAM_SHITMAN = DarkRP.createJob("Hitman", {
color = Color(25, 25, 170, 255),
model = {
"models/player/group01/male_01.mdl",
"models/player/group01/male_02.mdl",
"models/player/group01/male_03.mdl"
},
description = [[Kill all players, for money of course...]],
weapons = {"slownls_hitman_binoculars", "slownls_hitman_tablet"},
command = "slownls_hitman",
max = 4,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
category = "Citizens"
})
TEAM_DRUGD = DarkRP.createJob("Drug Dealer", {
color = Color(255, 181, 0, 255),
model = {
"models/player/soldier_stripped.mdl",
"models/player/voikanaa/snoop_dogg.mdl"
},
description = [[You work with drugs. It can be a passion or a drive for money, whatever you do, just don't let the police see.]],
weapons = {"zmlab_extractor"},
command = "drug_dealer",
max = 0,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = false,
category = "Citizens"
})
TEAM_CITYWORKER = DarkRP.createJob("City Worker", {
name = "City Worker",
color = Color( 5, 140, 0, 255 ),
model = {
"models/player/group01/male_01.mdl",
"models/player/group01/male_02.mdl",
"models/player/group01/male_03.mdl",
},
description = [[You maintain the city. Clean rubble, fix leaks, and work on electrical faults for money.]],
weapons = { "cityworker_pliers", "cityworker_shovel", "cityworker_wrench" },
command = "cityworker",
max = 0,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = false,
category = "Citizens"
})
TEAM_IA = DarkRP.createJob("State Officer", {
color = Color(0, 0, 255, 255),
model = {
"models/player/gasmask.mdl",
"models/player/guerilla.mdl"
},
description = [[Your authority is beyond the Mayor. Maintain Justice in this city. Fight corruption.]],
weapons = {"m9k_colt1911", "weapon_cuff_police"},
command = "policeadmin",
max = 0,
salary = 60,
admin = 2,
vote = false,
hasLicense = true,
candemote = false,
category = "Police",
ammo = {
["m9k_ammo_pistol"] = 35
},
PlayerSpawn = function(ply)
ply:SetArmor(100)
end
})
TEAM_POLICE = DarkRP.createJob("Police", {
color = Color(0, 0, 255, 255),
model = {
"models/player/police.mdl",
"models/player/police_fem.mdl"
},
description = [[Uphold the laws of the land to the best of your ability. Police brutality is sometimes needed and justified to maintain the order in these streets.]],
weapons = {"m9k_colt1911", "weapon_cuff_police", "zwf_sniffer"},
command = "police",
max = 6,
salary = 50,
admin = 0,
vote = false,
hasLicense = true,
candemote = true,
category = "Police",
ammo = {
["m9k_ammo_pistol"] = 35
},
PlayerSpawn = function(ply)
ply:SetArmor(50)
end
})
TEAM_CHIEF = DarkRP.createJob("Police Chief", {
color = Color(0, 0, 255, 255),
model = {
"models/player/combine_soldier_prisonguard.mdl",
"models/player/combine_soldier.mdl"
},
description = [[You command those that uphold the laws of this land. Lead to the best of your abilities, everything you and your subordinates do reflect you. Do your best to shine above the filth.]],
weapons = {"m9k_colt1911", "weapon_cuff_police", "zwf_sniffer"},
command = "police_chief",
max = 1,
salary = 70,
admin = 0,
vote = false,
hasLicense = true,
candemote = true,
category = "Police",
NeedToChangeFrom = TEAM_POLICE,
ammo = {
["m9k_ammo_pistol"] = 35
},
PlayerSpawn = function(ply)
ply:SetArmor(50)
end
})
TEAM_SWAT = DarkRP.createJob("SWAT Officer", {
color = Color(0, 72, 255, 255),
model = {
"models/player/riot.mdl",
"models/player/urban.mdl"
},
description = [[Backup the police, lead the raids, bring justice to the dirty DarkRP streets.]],
weapons = {"m9k_deagle", "weapon_cuff_police", "zwf_sniffer"},
command = "swatoff",
max = 5,
salary = 50,
admin = 0,
vote = false,
hasLicense = true,
candemote = true,
category = "Police",
ammo = {
["m9k_ammo_pistol"] = 35
},
PlayerSpawn = function(ply)
ply:SetArmor(100)
end
})
TEAM_SWATC = DarkRP.createJob("SWAT Chief", {
color = Color(0, 72, 255, 255),
model = {"models/player/swat.mdl"},
description = [[Lead the raiding team of the police.]],
weapons = {"m9k_deagle", "weapon_cuff_police", "zwf_sniffer"},
command = "swatchief",
max = 1,
salary = 70,
admin = 0,
vote = false,
hasLicense = true,
candemote = true,
category = "Police",
NeedToChangeFrom = TEAM_SWAT,
ammo = {
["m9k_ammo_pistol"] = 35
},
PlayerSpawn = function(ply)
ply:SetArmor(110)
end
})
TEAM_HOBO = DarkRP.createJob("Hobo", {
color = Color(0, 0, 0, 255),
model = {"models/player/corpse1.mdl", "models/half-dead/Gopniks/extra/playermodelonly.mdl"},
description = [[You are the lowest class. Hobo's are know to be extremely territorial. They KOS each other in the streets. Every hobo-on-hobo kill gains 100 max health. At 600 health you become the Hobo King.]],
weapons = {"m9k_fists", "weapon_angryhobo"},
command = "hobo",
max = 0,
salary = 0,
admin = 0,
vote = false,
hasLicense = false,
candemote = false,
category = "Citizens"
})
TEAM_HOBOK = DarkRP.createJob("Hobo King", {
color = Color(0, 0, 0, 255),
model = {"models/player/charple.mdl", "models/half-dead/Gopniks/extra/playermodelonly.mdl"},
description = [[You've earned this role through countless murders(6)... but can you maintain it? Or loose it terribly?]],
weapons = {"m9k_fists", "weapon_angryhoboking"},
command = "hobok",
max = 1,
salary = 10,
admin = 0,
vote = false,
hasLicense = false,
candemote = false,
category = "Citizens",
customCheck = function(ply)
return table.HasValue({TEAM_HOBO}, ply:Team())
end,
CustomCheckFailMsg = "You haven't met the real god.",
})
TEAM_MAYOR = DarkRP.createJob("Mayor", {
color = Color(0, 0, 255, 255),
model = {"models/player/breen.mdl"},
description = [[Set laws in place to protect your citizens. Or protect you from you citizens. You entirely decide the presence of the government in everyday life.]],
weapons = {"m9k_remington1858", "weapon_cuff_police", "zwf_sniffer"},
command = "mayor",
max = 1,
salary = 120,
admin = 0,
vote = true,
hasLicense = true,
candemote = true,
category = "Police",
mayor = true,
ammo = {
["m9k_ammo_357"] = 15
}
})
TEAM_GROVE = DarkRP.createJob("Grove Gangster", {
color = Color(0, 255, 30, 255),
model = {
"models/gang_groove/gang_1.mdl",
"models/gang_groove/gang_2.mdl",
"models/gang_chem/gang_groove_chem.mdl",
"models/gang_groove_boss/gang_groove_boss.mdl"
},
description = [[You are a gang member of the Grove Gang. You are KoS with the Ballas Gang.]],
weapons = {},
command = "grove_gang",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens"
})
TEAM_GROVE_BOSS = DarkRP.createJob("Grove Boss", {
color = Color(0, 255, 30, 255),
model = {
"models/gang_groove/gang_1.mdl",
"models/gang_groove/gang_2.mdl",
"models/gang_chem/gang_groove_chem.mdl",
"models/gang_groove_boss/gang_groove_boss.mdl"
},
description = [[You are a gang boss of the Grove Gang. You are KoS with the Ballas Gang.]],
weapons = {},
command = "grove_gang_boss",
max = 1,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens",
NeedToChangeFrom = TEAM_GROVE
})
TEAM_BALLAS = DarkRP.createJob("Ballas Gangster", {
color = Color(255, 0, 30, 255),
model = {
"models/gang_ballas/gang_ballas_1.mdl",
"models/gang_ballas/gang_ballas_2.mdl",
"models/gang_ballas_boss/gang_ballas_boss.mdl",
"models/gang_ballas_chem/gang_ballas_chem.mdl"
},
description = [[You are a gang member of the Ballas Gang. You are KoS with the Grove Gang.]],
weapons = {},
command = "balla_gang",
max = 5,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens"
})
TEAM_BALLAS_BOSS = DarkRP.createJob("Ballas Boss", {
color = Color(255, 0, 30, 255),
model = {
"models/gang_ballas/gang_ballas_1.mdl",
"models/gang_ballas/gang_ballas_2.mdl",
"models/gang_ballas_boss/gang_ballas_boss.mdl",
"models/gang_ballas_chem/gang_ballas_chem.mdl"
},
description = [[You are a gang boss of the Ballas Gang. You are KoS with the Grove Gang.]],
weapons = {},
command = "balla_gang_boss",
max = 1,
salary = 15,
admin = 0,
vote = false,
hasLicense = false,
candemote = true,
category = "Citizens",
NeedToChangeFrom = TEAM_BALLAS
})
--[[---------------------------------------------------------------------------
Define which team joining players spawn into and what team you change to if demoted
---------------------------------------------------------------------------]]
GAMEMODE.DefaultTeam = TEAM_CITIZEN
--[[---------------------------------------------------------------------------
Define which teams belong to civil protection
Civil protection can set warrants, make people wanted and do some other police related things
---------------------------------------------------------------------------]]
GAMEMODE.CivilProtection = {
[TEAM_POLICE] = true,
[TEAM_SWAT] = true,
[TEAM_SWATC] = true,
[TEAM_CHIEF] = true,
[TEAM_MAYOR] = true,
[TEAM_IA] = true,
}
--[[---------------------------------------------------------------------------
Jobs that are hitmen (enables the hitman menu)
---------------------------------------------------------------------------]]
--DarkRP.addHitmanTeam(TEAM_MOB)
|
local Locale = Class('Locale')
function Locale:initialize()
self.filename = 'lang'
self.langs = {
en = {
main_menu = {
ai = 'Play with AI',
player = 'Play with another player',
controls = 'Controls',
language = 'Change language',
credits = 'Credits',
quit = 'Quit',
},
credits = {
code = 'Code & sounds',
art = 'Art',
music = 'Music',
},
controls = {
player1 = 'Player1',
cast1 = 'Spell casting',
cast1value = 'WASD',
attack1 = 'Attack',
attack1value = 'Left ctrl or left shift',
effect = 'Toggle effect: F3',
fullscreen = 'Toggle fullscreen: F11',
player2 = 'Player 2',
cast2 = 'Spell casting',
cast2value = 'Arrows',
attack2 = 'Attack',
attack2value = 'Right ctrl or right shift',
},
dead_heat = 'Dead heat!',
paused = 'Paused',
win_title = 'Player %d wins!',
elapsed_time_title = 'Elapsed time is %d seconds.',
pause_info = 'Press space to enter to the main menu.',
win_info = 'Press space to start over.',
},
ru = {
main_menu = {
ai = 'Играть с ботом',
player = 'Друг против друга',
controls = 'Управление',
language = 'Сменить язык',
credits = 'Авторы',
quit = 'Выход',
},
credits = {
code = 'Код и звуки',
art = 'Спрайты и изображения',
music = 'Музыка',
},
controls = {
player1 = 'Игрок 1',
cast1 = 'Создание заклинания',
cast1value = 'WASD',
attack1 = 'Атака',
attack1value = 'Левый ctrl или левый shift',
effect = 'Переключить эффект: F3',
fullscreen = 'Полноэкранный режим: F11',
player2 = 'Игрок 2',
cast2 = 'Создание заклинания',
cast2value = 'Стрелки',
attack2 = 'Атака',
attack2value = 'Правый ctrl или правый shift',
},
dead_heat = 'Ничья!',
paused = 'Пауза',
win_title = 'Игрок %d одержал победу!',
elapsed_time_title = 'Матч длился %d с.',
pause_info = 'Нажмите пробел для выхода в главное меню.',
win_info = 'Нажмите пробел для нового матча.',
},
}
self.langs_order = {'en', 'ru'}
self.current_lang = 1
if love.filesystem.exists(self.filename) then
self.current_lang, _ = tonumber(love.filesystem.read(self.filename, 1), 10)
end
end
function Locale:get(...)
local lang = self.langs[self.langs_order[self.current_lang]]
for _, v in ipairs({...}) do
if not lang or not lang[v] then
return '<???>'
end
lang = lang[v]
end
return lang
end
function Locale:next_language()
self.current_lang = self.current_lang + 1
if self.current_lang > #self.langs_order then
self.current_lang = 1
end
love.filesystem.write(self.filename, self.current_lang, 1)
end
return Locale
|
local lspconfig = require("lspconfig")
local custom_attach = require("polarmutex.lsp.attach")
require("nlua.lsp.nvim").setup(lspconfig, {
on_attach = custom_attach,
root_dir = function(fname)
if string.find(vim.fn.fnamemodify(fname, ":p"), "neovim/") then
return vim.fn.expand("~/repos/dotfiles/neovim/")
end
return lspconfig_util.find_git_ancestor(fname) or
lspconfig_util.path.dirname(fname)
end,
globals = {
-- Colorbuddy
"Color", "c", "Group", "g", "s", -- Custom
"RELOAD",
},
})
|
--[[
! = Internal functins and shouldn't be used.
Functions:
SH Building.GetData( BuildingName ) Returns the building init-data.
SH Building.CanPlayerBuild( ply, BuildingName ) Returns true if the player can build said building.
SH Building.GetPlayerBuildings( ply ) Returns a list of buildings the given player made.
SH Building.CanPlaceOnFloor(BuildingName, vec, yaw, bAllowWater) Returns a bool, position and angle.
SH Building.CanPlaceOnFloorFast(BuildingName, vec, yaw, bAllowWater) Returns a bool.
SH Building.CanPlaceCore( node ) Returns true if the core can be placed at said node.
SH Building.GetCore() Returns the core building (If placed).
! SH Building.ApplyFunctions( ent ) Applies the building functions to the given building.
SH Building.CanTarget( ent ) Returns true if the building can target the entity.
SV Building.Create( BuildingName, ply , pos, ang ) Creats a building at the given position and angle.
Debug Functions:
SV Building.RespawnCore() Respawns the core at the same location.
]]
local building_size = Vector(95, 95, 95)
local cos,sin,rad,max = math.cos, math.sin, math.rad, math.max
Building = {}
local META = FindMetaTable("Entity")
function META:IsBuilding()
local cl = self:GetClass()
return cl == "yawd_building" or cl == "yawd_building_core" or cl == "yawd_building_solid"
end
local cores = ents.FindByClass( "yawd_building_core" )
if #cores > 0 then
GM.Building_Core = cores[1]
else
GM.Building_Core = NULL
end
local buildings = {}
local building_meta = {}
local default_building = {}
default_building.Name = "Unknown"
default_building.Health = 200
default_building.CanBuild = true
default_building.BuildClass = CLASS_ANY
default_building.Cost = 0
default_building.IsSolid = false
default_building.BuildingSize = {-Vector(95, 95, 10), Vector(95, 95, 95)}
default_building.HasFoundation = false
building_meta.__index = default_building
function building_meta:__tostring()
return 'BuildingData ["' .. self.Name .. '"]'
end
-- Load buildings
hook.Add("YAWDPreLoaded","YAWD_LoadBuildings",function()
local files,folders = file.Find( GM.FolderName .. "/gamemode/buildings/*.lua" ,"LUA")
for k,v in ipairs(files) do
local fil = GM.FolderName .. "/gamemode/buildings/" .. v
AddCSLuaFile(fil)
local t = include(fil)
if not t or type(t) ~= "table" then ErrorNoHalt("Empty building file [" .. fil .. "]") continue end
if not t.Name then ErrorNoHalt("Invalid building data [" .. fil .. "]") continue end
setmetatable(t, building_meta)
t.max_size = Vector( math.max( -t.BuildingSize[1].x, t.BuildingSize[2].x ), math.max( -t.BuildingSize[1].y, t.BuildingSize[2].y ),math.max( -t.BuildingSize[1].z, t.BuildingSize[2].z ))
buildings[t.Name] = t
end
end)
-- Buiilding functions
function Building.GetAll()
return table.GetKeys(buildings)
end
function Building.GetData( BuildingName )
return buildings[BuildingName]
end
local cache = {}
local function isClassAllowed( BuildingName, CLASS )
if CLASS == CLASS_ANY then return true end
if not cache[BuildingName] then cache[BuildingName] = {} end
if cache[BuildingName][CLASS] ~= nil then
return cache[BuildingName][CLASS]
end
local bd = Building.GetData( BuildingName )
if not bd then return false end
if bd.CanBuild ~= nil and bd.CanBuild == false then return false end
if type( bd.BuildClass ) == "table" then
for _,bclass in ipairs( bd.BuildClass ) do
if bclass == CLASS or bclass == CLASS_ANY then
cache[BuildingName][CLASS] = true
return true
end
end
elseif bd.BuildClass == CLASS_ANY or bd.BuildClass == CLASS then
cache[BuildingName][CLASS] = true
return true
end
cache[BuildingName][CLASS] = false
return false
end
function Building.CanClassBuild(BuildingName, CLASS)
return isClassAllowed(BuildingName, CLASS)
end
function Building.CanPlayerBuild( ply, BuildingName )
if not BuildingName then return false end
local bd = Building.GetData( BuildingName )
if not bd then return false end
// Check cost
local cost = bd.Cost
if cost < 0 then return false end
if ply:GetCurrency() < cost then return false end
// Check if class match
return isClassAllowed( BuildingName, ply:GetPlayerClass() )
end
function Building.GetPlayerBuildings( ply )
local t = {}
for _,ent in ipairs( ents.FindByClass( "yawd_building*" ) ) do
if not ent:IsBuilding() then continue end
local ow = ent:GetBuildingOwner()
if IsValid(ow) and ow == ply then
table.insert(t, ent)
end
end
return t
end
local max_angle = 6
local s_hull = building_size * 0.05
-- A mask that hits the map and water
local custom_mask = bit.bor( CONTENTS_EMPTY, CONTENTS_SOLID, CONTENTS_MOVEABLE, CONTENTS_WINDOW, CONTENTS_PLAYERCLIP, CONTENTS_WATER, CONTENTS_GRATE )
local function ET(vec1, vec2)
return util.TraceLine( {
start = vec1,
endpos = vec2,
mask = custom_mask
} )
end
local function ETHull(vec1, vec2, mins, maxs)
return util.TraceHull( {
start = vec1,
endpos = vec2,
maxs = maxs,
mins = mins,
mask = custom_mask
} )
end
local function CheckForBuilding(vec1, vec2, mins, maxs, ent)
local t = util.TraceHull( {
start = vec1,
endpos = vec2,
maxs = maxs,
mins = mins,
collisiongroup = COLLISION_GROUP_WEAPON,
ignoreworld = true,
filter = ent
} )
return t.Hit and t.Entity or nil
end
local function pointFree( vec )
local content = util.PointContents( vec )
if bit.band( content, CONTENTS_WATER ) == CONTENTS_WATER or bit.band( content, CONTENTS_SOLID ) == CONTENTS_SOLID then return false end
return true
end
local function AngleMerge( ang1, ang2, amount)
return math.ApproachAngle(ang1, ang2, math.AngleDifference(ang1, ang2) * amount) % 360
end
-- Checks to see if a building can be placed. Returns; success, position, angle. Position and angle for rendering.
function Building.CanPlaceOnFloor(BuildingName, vec, yaw, bAllowWater, e_IgnoreEntity, b_StopSnap)
if not yaw then yaw = 0 end
local size = buildings[BuildingName].max_size
-- Change the place location if there is a trap nearby
local height = Vector(0,0,50 + size.z * 2)
local m_size = size * 0.95
local ent = CheckForBuilding(vec + height, vec - height, -m_size, m_size, e_IgnoreEntity)
if ent and IsValid(ent) then -- We found a trap. Snap to it
if not ent:IsBuilding() or b_StopSnap then -- This is not a building. Can't snap.
return false, vec
end
local offset = vec - ent:GetPos()
vec = ent:GetPos()
if math.abs(offset.x) >= math.abs(offset.y) then -- X
if offset.x >= 0 then -- +
vec.x = vec.x + ent:OBBMaxs().x + size.x
else -- -
vec.x = vec.x + ent:OBBMins().x - size.x
end
else -- Y
if offset.y >= 0 then -- +
vec.y = vec.y + ent:OBBMaxs().y + size.y
else -- -
vec.y = vec.y + ent:OBBMins().y - size.y
end
end
-- We snapped, check if there is a building (or something else) at new location
if CheckForBuilding(vec + height, vec - height, -m_size, m_size, e_IgnoreEntity) then
return false, vec
end
end
local eye = vec + Vector(0,0,50)
local r = rad(yaw)
local TLO = Vector( cos(r) * size.x, sin(r) * size.y, 0 ) * 0.95
local r = rad(yaw - 90)
local TRO = Vector( cos(r) * size.x, sin(r) * size.y, 0 ) * 0.95
-- Check the corners (Anything solid)
local TR = vec + TLO + TRO + Vector(0,0,10)
local TL = vec + TLO - TRO + Vector(0,0,10)
local BL = vec - TLO - TRO + Vector(0,0,10)
local BR = vec - TLO + TRO + Vector(0,0,10)
if not pointFree(TR) then return false, vec end
if not pointFree(TL) then return false, vec end
if not pointFree(BL) then return false, vec end
if not pointFree(BR) then return false, vec end
-- Trace the ground from corners
local R_TL = ETHull(TL + Vector(0,0,40), TL - Vector(0,0,90), -s_hull, s_hull)
local R_TR = ETHull(TR + Vector(0,0,40), TR - Vector(0,0,90), -s_hull, s_hull)
local R_BL = ETHull(BL + Vector(0,0,40), BL - Vector(0,0,90), -s_hull, s_hull)
local R_BR = ETHull(BR + Vector(0,0,40), BR - Vector(0,0,90), -s_hull, s_hull)
if not R_TL.Hit or not R_TR.Hit or not R_BL.Hit or not R_BR.Hit then return false, vec end
-- Lifts the detection a bit
TL.z = R_TL.HitPos.z + 20
TR.z = R_TR.HitPos.z + 20
BL.z = R_BL.HitPos.z + 20
BR.z = R_BR.HitPos.z + 20
-- Check from center to corners (Solid)
local t = ET(TL, TR)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(TR, BR)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(BR, BL)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(BL, TL)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(TL, BR)
if t.Hit or t.StartSolid then return false, vec end
local R_Center = ETHull(eye, eye - Vector(0,0,90), -s_hull, s_hull)
-- Get the position
local center_z = max(( R_TL.HitPos.z + R_TR.HitPos.z + R_BL.HitPos.z + R_BR.HitPos.z ) / 4, R_Center.HitPos.z)
-- Calculate the yaw and pitch.
local p1,p2 = (R_TL.HitPos - R_TR.HitPos ):Angle().p, (R_BL.HitPos - R_BR.HitPos ):Angle().p
local Pitch = AngleMerge(p1,p2,0.5)
local r1,r2 = ( R_TR.HitPos - R_BR.HitPos ):Angle().p, ( R_TL.HitPos - R_BL.HitPos ):Angle().p
local Roll = AngleMerge(r1,r2,0.5)
-- Calculate the angle
local n_ang = Angle(0,yaw,0)
n_ang:RotateAroundAxis(n_ang:Forward(), -Pitch)
n_ang:RotateAroundAxis(n_ang:Right(), -Roll)
local n_pos = Vector(eye.x,eye.y,center_z)
if math.abs(math.AngleDifference(Pitch,0)) > max_angle then return false, n_pos, n_ang end
if math.abs(math.AngleDifference(Roll,0)) > max_angle then return false, n_pos, n_ang end
if not R_TR.Hit or (not bAllowWater and R_TR.MatType == MAT_SLOSH) then return false, n_pos, n_ang end
if not R_TL.Hit or (not bAllowWater and R_TL.MatType == MAT_SLOSH) then return false, n_pos, n_ang end
if not R_BL.Hit or (not bAllowWater and R_BL.MatType == MAT_SLOSH) then return false, n_pos, n_ang end
if not R_BR.Hit or (not bAllowWater and R_BR.MatType == MAT_SLOSH) then return false, n_pos, n_ang end
if not R_Center.Hit or (not bAllowWater and R_Center.MatType == MAT_SLOSH) then return false, n_pos, n_ang end
return true, n_pos, n_ang
end
-- Checks to see if a building can be placed. However this function is faster and doesn't calculate the angle.
function Building.CanPlaceOnFloorFast(BuildingName, vec, yaw, bAllowWater, e_IgnoreEntity, b_StopSnap)
if not yaw then yaw = 0 end
local size = buildings[BuildingName].max_size
-- Change the place location if there is a trap nearby
local height = Vector(0,0,50 + size.z * 2)
local m_size = size * 0.95
local ent = CheckForBuilding(vec + height, vec - height, -m_size, m_size, e_IgnoreEntity)
if ent and IsValid(ent) then -- We found a trap. Snap to it
if not ent:IsBuilding() or b_StopSnap then -- This is not a building. Can't snap.
return false, vec
end
local offset = vec - ent:GetPos()
vec = ent:GetPos()
if math.abs(offset.x) >= math.abs(offset.y) then -- X
if offset.x >= 0 then -- +
vec.x = vec.x + ent:OBBMaxs().x + size.x
else -- -
vec.x = vec.x + ent:OBBMins().x - size.x
end
else -- Y
if offset.y >= 0 then -- +
vec.y = vec.y + ent:OBBMaxs().y + size.y
else -- -
vec.y = vec.y + ent:OBBMins().y - size.y
end
end
-- We snapped, check if there is a building (or something else) at new location
if CheckForBuilding(vec + height, vec - height, -m_size, m_size, e_IgnoreEntity) then
return false, vec
end
end
local eye = vec + Vector(0,0,50)
local r = rad(yaw)
local TLO = Vector( cos(r) * size.x, sin(r) * size.y, 0 ) * 0.95
local r = rad(yaw - 90)
local TRO = Vector( cos(r) * size.x, sin(r) * size.y, 0 ) * 0.95
-- Check the corners (Anything solid)
local TR = vec + TLO + TRO + Vector(0,0,10)
local TL = vec + TLO - TRO + Vector(0,0,10)
local BL = vec - TLO - TRO + Vector(0,0,10)
local BR = vec - TLO + TRO + Vector(0,0,10)
if not pointFree(TR) then return false, vec end
if not pointFree(TL) then return false, vec end
if not pointFree(BL) then return false, vec end
if not pointFree(BR) then return false, vec end
-- Trace the ground from corners
local R_TL = ETHull(TL + Vector(0,0,40), TL - Vector(0,0,90), -s_hull, s_hull)
local R_TR = ETHull(TR + Vector(0,0,40), TR - Vector(0,0,90), -s_hull, s_hull)
local R_BL = ETHull(BL + Vector(0,0,40), BL - Vector(0,0,90), -s_hull, s_hull)
local R_BR = ETHull(BR + Vector(0,0,40), BR - Vector(0,0,90), -s_hull, s_hull)
if not R_TL.Hit or not R_TR.Hit or not R_BL.Hit or not R_BR.Hit then return false, vec end
TL.z = R_TL.HitPos.z + 20
TR.z = R_TR.HitPos.z + 20
BL.z = R_BL.HitPos.z + 20
BR.z = R_BR.HitPos.z + 20
-- Check from center to corners (Solid)
local t = ET(TL, TR)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(TR, BR)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(BR, BL)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(BL, TL)
if t.Hit or t.StartSolid then return false, vec end
local t = ET(TL, BR)
if t.Hit or t.StartSolid then return false, vec end
local R_Center = ETHull(eye, eye - Vector(0,0,90), -s_hull, s_hull)
-- Get the position
local center_z = max(( R_TL.HitPos.z + R_TR.HitPos.z + R_BL.HitPos.z + R_BR.HitPos.z ) / 4, R_Center.HitPos.z)
-- Calculate the yaw and pitch.
local p1,p2 = (R_TL.HitPos - R_TR.HitPos ):Angle().p, (R_BL.HitPos - R_BR.HitPos ):Angle().p
local Pitch = AngleMerge(p1,p2,0.5)
local r1,r2 = ( R_TR.HitPos - R_BR.HitPos ):Angle().p, ( R_TL.HitPos - R_BL.HitPos ):Angle().p
local Roll = AngleMerge(r1,r2,0.5)
if math.abs(math.AngleDifference(Pitch,0)) > max_angle then return false end
if math.abs(math.AngleDifference(Roll,0)) > max_angle then return false end
return true
end
-- Returns the buildingsize. (This is not the traparea)
function Building.GetSize( BuildingName )
local bd = Building.GetData( BuildingName )
if not bd or not bd.BuildingSize then return -Vector(95, 95, 1.7), Vector(95, 95, 95) end
return bd.BuildingSize
end
local n_c = {}
-- Returns a table of position and angle, if node is valid for the objective.
function Building.CanPlaceCore( node )
-- Check to see if the node is valid or cached
if not node then return false end
if n_c[node] ~= nil then return n_c[node] end
if not node:IsMapNode() then return false end
if #node:GetConnectedNodes(nil, nil, NODE_TYPE_GROUND) < 3 then -- Check to see if there are more than 3 nodes connected to this.
n_c[node] = false
return false
end
if not Building.CanPlaceOnFloorFast("Core", node:GetPos(), 0, false) then
n_c[node] = false
return false
end
local _,vec,ang = Building.CanPlaceOnFloor("Core", node:GetPos(), 0, false)
n_c[node] = {vec,ang}
return n_c[node]
end
-- A debug function to respawn the core.
function Building.RespawnCore()
local e = Building.GetCore()
local n = Building.Create( "Core", nil, e:GetPos(), e:GetAngles() )
SafeRemoveEntity(e)
end
-- Returns the core
function Building.GetCore()
return gmod.GetGamemode().Building_Core
end
-- Applies the functions
function Building.ApplyFunctions( ent )
local BuildingName = ent:GetBuildingName()
if not BuildingName then return end
local bd = Building.GetData( BuildingName )
if not bd then return end
ent.builddata = bd
for k,v in pairs( bd ) do
if k == "Init" and type(v) == "function" then
v(ent)
elseif k == "Health" and SERVER then
ent:SetMaxHealth( v )
ent:SetHealth( v )
elseif k == "TrapArea" and CLIENT then
ent:SetRenderBounds( v[1], v[2] )
ent[k] = v
elseif k == "Draw" then
ent.b_Draw = v
elseif k == "OnRemove" then
ent.b_OnRemove = v
elseif not (k == "Think" and ent:GetClass() == "yawd_building_ghost") then
ent[k] = v
end
end
end
-- Checks to see if the entity is an enemy
function Building.CanTarget( ent )
if ent:Health() <= 0 then return false end
if ent:IsNPC() or ent:IsNextBot() or ent:GetClass() == "yawd_npc_base" then
return true
end
return false
end
if SERVER then
-- Used to apply force on targets
function Building.ApplyTrapForce(target, vec)
if type(target) == "Player" then
target:SetVelocity(target:GetVelocity() + Vector(vec.x / 2, vec.y / 2, vec.z))
else
if target.GetRagdolled and target:GetRagdolled() then
return
end
if target.Fling and not target.m_CantBePushed then
target:Fling( vec )
else
local phys = target:GetPhysicsObject()
if IsValid(phys) then
phys:Wake()
target:SetVelocity(target:GetVelocity() + Vector(vec.x * 2, vec.y * 2, vec.z) )
end
end
end
end
-- Creats a building.
function Building.Create( BuildingName, owner, pos, ang )
local bd = Building.GetData( BuildingName )
if not bd then ErrorNoHalt("Unknown building [" .. BuildingName .. "]") return end
local c = "yawd_building"
if BuildingName == "Core" then
c = "yawd_building_core"
elseif bd.IsSolid then
c = "yawd_building_solid"
end
local e = ents.Create(c)
e:SetBuildingName( BuildingName )
e:SetPos( pos )
e:SetAngles( ang or Angle(0,0,0))
e.building_data = bd
e:SetBuildingOwner( owner )
Building.ApplyFunctions( e )
e:Spawn()
return e
end
-- Checks current buildings and disables those that aren't allowed.
hook.Add("YAWDPlayerSwitchedClass", "Buildings.Disable", function(ply, class)
for _,ent in ipairs( Building.GetPlayerBuildings( ply ) ) do
local allowed = isClassAllowed( ent:GetBuildingName() , ply:GetPlayerClass() )
if ent:GetDisabled() and allowed then
ent:SetDisabled(false)
elseif not ent:GetDisabled() and not allowed then
ent:SetDisabled(true)
end
end
end)
else
-- Easy StencilCut
-- Starts the stencil. Anything rendered will determined the area that gets rendered.
function Building.StencilMask()
render.ClearStencil();
render.SetStencilEnable( true );
render.SetStencilCompareFunction( STENCIL_ALWAYS );
render.SetStencilPassOperation( STENCIL_REPLACE );
render.SetStencilFailOperation( STENCIL_KEEP );
render.SetStencilZFailOperation( STENCIL_KEEP );
render.SetStencilWriteMask( 1 );
render.SetStencilTestMask( 1 );
render.SetStencilReferenceValue( 1 );
end
-- Anything rendered after this, will be cut to match the mask.
function Building.StencilRender()
render.SetStencilCompareFunction( STENCIL_EQUAL );
render.ClearBuffersObeyStencil( 0,0,0,0, true );
end
-- Ends the stencil.
function Building.StencilEnd()
render.SetStencilEnable( false )
end
end
-- Reload support
for _,ent in ipairs(ents.FindByClass("yawd_building*")) do
if not ent:IsBuilding() then continue end
Building.ApplyFunctions( ent )
end
|
function onCreate()
setProperty('gfGroup.visible', false);
end |
-- local dbg = require("debugger")
-- dbg.auto_where = 2
local api = require'nvimapi'
local cvcomplete = require'cvcomplete/cvcompleter'
local function complete()
local sel = api.get_selected_part()
local completion = cvcomplete(sel.selection, api.option('ft'))
api.set_selected_part(completion, sel)
end
return {
complete = complete,
}
|
local is_present_better_escape, better_escape = pcall(require, "better_escape")
if not is_present_better_escape then
return
end
better_escape.setup({})
|
local colours = {
{"black", "Black"},
{"cyan", "Cyan"},
{"brown", "Brown"},
{"dark_blue", "Dark Blue"},
{"dark_green", "Dark Green"},
{"dark_grey", "Dark Grey"},
{"dark_pink", "Dark Pink"},
{"green", "Green"},
{"grey", "Grey"},
{"orange", "Orange"},
{"pink", "Pink"},
{"purple", "Purple"},
{"red", "Red"},
{"white", "White"},
{"yellow", "Yellow"}
}
for _, row in ipairs(colours) do
local name = row[1]
local description = row[2]
minetest.register_node("colouredstonebricks:"..name, {
description = description.." Stone Brick",
tiles = {"colouredstonebricks_"..name..".png"},
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_craft({
type = "shapeless",
output = 'colouredstonebricks:'..name,
recipe = {
'dye:'..name, 'default:stonebrick',
}
})
-- Support for stairsplus mod
if minetest.get_modpath("moreblocks") then
stairsplus:register_all("colouredstonebricks", name, "colouredstonebricks:"..name, {
description = description.." Stone Brick",
tiles = {"colouredstonebricks_"..name..".png"},
groups = {cracky=3},
sounds = default.node_sound_stone_defaults(),
sunlight_propagates = true,
})
end
end
-- We don't have blue, violet or magenta coloured stone bricks (yet)
--minetest.register_alias("dye:dark_blue","dye:blue")
--minetest.register_alias("dye:dark_pink","dye:magenta")
--minetest.register_alias("dye:purple","dye:violet")
|
local node = AST.node
SPAWNS = {}
SPAWNS.F = {
Stmts__POS = function (me)
return SPAWNS.F.__stmts_flatten(me), true
end,
__stmts_flatten = function (stmts, new)
local new = new or node('Stmts', stmts.ln)
for _, sub in ipairs(stmts) do
if AST.is_node(sub) and sub.tag=='Stmts' then
SPAWNS.F.__stmts_flatten(sub, new)
else
AST.set(new, #new+1, sub)
end
end
return new
end,
}
AST.visit(SPAWNS.F)
SPAWNS.G = {
_SPAWN = function (par, I, spawn)
-- all statements after myself
local par_stmts = AST.asr(par, 'Stmts')
local cnt_stmts = { unpack(par_stmts, I+1) }
for i=I, #par_stmts do
par_stmts[i] = nil
end
return node('Par_Or', spawn.ln,
node('Stmts', spawn.ln,
spawn,
node('Await_Forever', spawn.ln)),
node('Stmts', spawn.ln,
unpack(cnt_stmts)))
end,
_Spawn_Block__PRE = function (me)
me.tag = 'Stmts'
return SPAWNS.G._SPAWN(me.__par, me.__i, me)
end,
_Abs_Spawn_Single__PRE = function (me)
me.tag = 'Abs_Await'
me.__adjs_is_spawn = true
return SPAWNS.G._SPAWN(me.__par, me.__i, me)
end,
_Finalize_X__PRE = function (me)
me.tag = 'Finalize'
return SPAWNS.G._SPAWN(me.__par, me.__i, me)
end,
Evt__PRE = 'Var__PRE',
Var__PRE = function (me)
if me.__spawns_ok then
return
else
me.__spawns_ok = true
end
local alias, tp, id = unpack(me)
if alias == '&?' and (me.tag=='Evt' or tp[1].tag~='ID_nat' or tp[2]~=nil) then
-- TODO: TYPES.is_nat
if not AST.par(me,'Code_Pars') then
return SPAWNS.G._SPAWN(me.__par, me.__i,
node('Stmts', me.ln,
me,
node('Await_Alias', me.ln, me.n)))
end
end
end,
Pool__PRE = function (me)
if me.__spawns_ok then
return
else
me.__spawns_ok = true
end
local alias = unpack(me)
if not alias then
return SPAWNS.G._SPAWN(me.__par, me.__i, me)
end
end,
}
AST.visit(SPAWNS.G)
|
local _stringformat = string.format
local _tonumber = tonumber
local _type = type
--VALIDATION
if(not KEYS[1]) then return redis.error_reply('NO SESSION KEY') end
if(not KEYS[2]) then return redis.error_reply('NO ROOM NAME KEY') end
if(not KEYS[3]) then return redis.error_reply('NO NODE TIME KEY') end
if(not cjson.decode(ARGV[1])) then return redis.error_reply('NO SUB DATA') end
--========================================================================
-- UTILITY Functions
--========================================================================
local createHexastore = function(key, subject,predicate,object)
return redis.call('zadd', key,
0,_stringformat("spo||%s||%s||%s",subject,predicate,object),
0,_stringformat("sop||%s||%s||%s",subject,object,predicate),
0,_stringformat("osp||%s||%s||%s",object,subject,predicate),
0,_stringformat("ops||%s||%s||%s",object,predicate,subject),
0,_stringformat("pos||%s||%s||%s",predicate,object,subject),
0,_stringformat("pso||%s||%s||%s",predicate,subject,object))
end
--removes the hex reservation
local removeHexReserve = function(sessionId,clientRoomName)
return redis.call('zrem', 'hex|sessions:rooms',
_stringformat("sop||%s||%s||%s", sessionId, clientRoomName, 'is-reserve-of'),
_stringformat("spo||%s||%s||%s", sessionId, 'is-reserve-of', clientRoomName),
_stringformat("ops||%s||%s||%s", clientRoomName, 'is-reserve-of', sessionId),
_stringformat("osp||%s||%s||%s", clientRoomName, sessionId, 'is-reserve-of'),
_stringformat("pso||%s||%s||%s", 'is-reserve-of', sessionId, clientRoomName),
_stringformat("pos||%s||%s||%s", 'is-reserve-of', clientRoomName, sessionId))
end
--removes the hex reservation
local checkHexSubscriber = function(subject,object)
local result = redis.call('zscore', 'hex|sessions:rooms', 'sop||'..subject..'||is-sub-of||'..object)
return result and result == 0
end
local retrieveSeatFromHexResult = function(result, strRemoval)
if(_type(result) ~= 'table' or _type(strRemoval) ~= 'string') then return false end
if(#result <= 0 or not result[1]) then return false end
if(_type(result[1]) ~= 'string') then return false end
return _tonumber(result[1]:sub(#strRemoval+1)) --+1 because sub starts @ 0
end
local function isValidRoomType(type)
return type and (type == 'realtime' or type == 'turnbased' or type == 'system' or type == 'standard') --todo: add different types here or reference table
end
--========================================================================
-- CORE Functions
--========================================================================
local sessionId = KEYS[1]
local clientRoomName = KEYS[2]
local nodeTime = _tonumber(KEYS[3])
local subParams = cjson.decode(ARGV[1])
local strAppendResponse = cjson.decode(ARGV[2])
local rk = {
countsRooms = "counts|rooms",
tickRooms = "tick|rooms",
tickSessions = "tick|sessions",
session = "sessions|"..KEYS[1],
sessionSubs = "sessions|"..KEYS[1].."|rooms",
sessionHistory = "sessions|"..KEYS[1].."|history",
roomName = "rooms|"..KEYS[2],
roomInfo = "rooms|"..KEYS[2].."|info",
roomHistory = "rooms|"..KEYS[2].."|history",
roomMessages = "rooms|"..KEYS[2].."|messages",
roomBots = "rooms|"..KEYS[2].."|bots",
roomReserves = "rooms|"..KEYS[2].."|reserves",
}
local roomExists, userId, roomType, roomSubscribeType, isClientBot
local isGameRoom,isTurnBased,seatKey, seat, searchTerm, hexastore, isSystem, reservesOnly
userId = strAppendResponse and strAppendResponse.userId or redis.call('hget', rk.session, 'userId')
--check if room exists
roomExists = redis.call('exists', rk.roomInfo) == 1 and redis.call('hexists',rk.roomInfo, 'destroying') == 0
if(not roomExists) then return redis.error_reply('ROOM NO EXIST - '..clientRoomName) end
--check if room is locked
if(not redis.call('exists', rk.roomName..':locked') == 0) then return redis.error_reply('ROOM LOCKED - '..clientRoomName) end
--check roomType
roomType = redis.call('hget', rk.roomInfo, 'roomType')
if(not isValidRoomType(roomType)) then return redis.error_reply('INVALID ROOM TYPE - '..clientRoomName) end
--check if user is already subbed
if(checkHexSubscriber(sessionId, clientRoomName)) then return redis.status_reply('SUBSCRIBE EXISTS') end
isGameRoom = redis.call('hexists', rk.roomInfo, 'isGameRoom') == 1
isTurnBased = redis.call('hexists', rk.roomInfo, 'isTurnBased') == 1
isSystem = redis.call('hexists', rk.roomInfo, 'isSystem') == 1
--todo: add check on subParams to return a hash
searchTerm = "open:seat:"
--check if reservations are required
roomSubscribeType = redis.call('hget', rk.roomInfo, 'roomSubscribeType')
reservesOnly = roomSubscribeType and roomSubscribeType == 'reserves'
if(reservesOnly) then
searchTerm = "reserved:seat:"
end
hexastore = redis.call('zrangebylex', rk.roomName, '['..searchTerm, '['..searchTerm..'\xff', 'LIMIT', 0, 1)
seat = retrieveSeatFromHexResult(hexastore, searchTerm)
if(not seat) then return redis.error_reply('NO SEAT NUMBER - '..clientRoomName) end
redis.call('zrem', rk.roomName, "open:seat:"..seat, "reserved:seat:"..seat)
redis.call('zadd', rk.roomName,0, "taken:seat:"..seat..":"..sessionId, 0, "taken:session:"..sessionId..":"..seat)
redis.call('zadd', rk.sessionSubs,nodeTime,clientRoomName)
--check if we need to remove/replace reservation with them
if(reservesOnly) then
--remove reservation from base table
redis.call('zrem', rk.roomReserves, sessionId)
--remove reservation from hexastore and error if does not exist
if(not removeHexReserve(sessionId, clientRoomName)) then return redis.error_reply('NO RESERVATION - '..sessionId) end
end
--add hex of user is subbed
if(not createHexastore('hex|sessions:rooms', sessionId, 'is-sub-of', clientRoomName)) then
return redis.error_reply('INVALID HEX RESPONSE')
end
--update tickers for room and session
redis.call('zadd',rk.tickRooms,'XX',nodeTime,clientRoomName)
redis.call('zadd',rk.tickSessions,'XX',nodeTime,sessionId)
redis.call('hset',rk.roomInfo,'updated',nodeTime)
redis.call('hincrby', rk.roomInfo, "subscribers", 1)
if(isGameRoom) then
--additionally add hexastore value of has-gameroom-of
if(not createHexastore('hex|sessions:rooms', sessionId, 'has-gameroom-of', clientRoomName)) then
return redis.error_reply('INVALID HEX GAME ROOM SUB RESPONSE')
end
end
isClientBot = redis.call('hexists', rk.session, 'bot') == 1
if(isClientBot) then
--update counts for bot field/key
redis.call('sadd', rk.roomBots, sessionId)
redis.call('hincrby', rk.roomInfo, "bots", 1)
end
--send a message to existing sessions
local publishSubscribe = function()
local response = strAppendResponse or {}
local dataToSend = {
sessionIds = nil,
messageId = -1,
message = {
phase = "subscribed",
room = clientRoomName,
response = response
}
}
local sessionIds, searchTerm, subscribers, numSubscribers
--overwrite or set to default some the message.response (to prevent meddling)
response.room = clientRoomName
response.sessionId = sessionId
response.roomType = redis.call('hget', rk.roomInfo, 'roomType')
response.isGameRoom = isGameRoom or nil
response.isTurnBased = isTurnBased or nil
response.isSystem = isSystem or nil
response.userId = userId
response.bot = isClientBot or nil
response.roomSubscribeType = redis.call('hget', rk.roomInfo, 'roomSubscribeType')
--set dataToSend.sessionIds
if(roomExists) then --for subscribe, we always want to be sure room is still here
sessionIds = {}
searchTerm = '[pos||is-sub-of||'..clientRoomName..'||'
subscribers = redis.call('zrangebylex', 'hex|sessions:rooms', searchTerm, searchTerm..'\xff')
--store count of subs
numSubscribers = #subscribers
for x=1, numSubscribers do
sessionIds[x] = subscribers[x]:sub(#searchTerm)
end
--set sessionIds to list of ids in the room
dataToSend.sessionIds = sessionIds
--increment message id
local nextId = redis.call('hincrby', rk.roomInfo, "nextMessageId", 1)
--add message id to ensure ordered messages by the time it reaches node
dataToSend.messageId = nextId
--send user connecting to room message list to be processed by room queue
redis.call('zadd', rk.roomMessages, nextId, cjson.encode(dataToSend.message))
--add user to the history, but set it to retrieve messages after their connecting message
redis.call('zadd', rk.roomHistory, nextId, sessionId)
--encode message and sessionId(s) for redis
local encoded = cjson.encode(dataToSend)
--https://redis.io/commands/eval#available-libraries
redis.call('publish', rk.roomName, encoded)
--return the sub message to retry if failure
return redis.status_reply('SUBSCRIBE OK')
end
return redis.error_reply('NO SUBSCRIBERS - '..clientRoomName)
end
return publishSubscribe()
|
local test = {}
local Class = require('charon.oop.Class')
local Departament = Class.new("Departament", "ActiveRecord")
local Employee = Class.new("Employee", "ActiveRecord")
Employee.belongsTo {
name = 'departament',
record = 'Departament',
foreignKey = 'departament_id'
}
test.beforeAll = function()
ActiveRecord.reset()
ActiveRecord.config = "config/active_record_sqlite.json"
local sql = [[
CREATE TABLE IF NOT EXISTS employee (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(250), observation TEXT,
departament_id INTEGER, total REAL,
created_at TEXT, updated_at TEXT
)]]
Employee.adapter():execute(sql)
local sql = [[
CREATE TABLE IF NOT EXISTS departament (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
description VARCHAR(250),
created_at TEXT, updated_at TEXT
)]]
Departament.adapter():execute(sql)
end
test.before = function()
ActiveRecord.begin()
end
test.after = function()
ActiveRecord.rollback()
end
test.afterAll = function()
ActiveRecord.config = nil
end
test.should_return_departament_instance = function()
local departament = Departament.new{ description = 'Directory' }
departament:save()
local employee = Employee.new{ name = "John", departament_id = departament.id }
employee:save()
assert( employee:departament() == departament )
end
test.should_return_departament_description = function()
local departament = Departament.new{ description = 'Directory' }
departament:save()
local employee = Employee.new{ name = "John", departament_id = departament.id }
employee:save()
assert( employee:departament().description == 'Directory', employee:departament().description )
end
test.should_return_nil_if_departament_id_is_nil = function()
local employee = Employee.new{ name = "John", departament_id = nil }
employee:save()
assert( employee:departament() == nil )
end
return test
|
local MessageType = require("messagetype")
local Message = require("message")
local utils = require("utils")
local config = require("syncdconfig")
local filesystem = require("filesystem")
local handlers = {
[MessageType.HELLO_OK] = function(msg, state)
log("Connected to %s (protocol version %s)", msg.serverName, msg.protocolVersion)
log("Asking for available subscriptions")
return Message(MessageType.GET_SUBSCRIPTIONS)
end,
[MessageType.HELLO_ERROR] = function(msg, state)
log("Error connecting to the server: %s", msg.reason)
end,
[MessageType.SEND_SUBSCRIPTIONS] = function(msg, state)
log("Got subscription list from the server:")
state.requestedSubs = {}
for _, entry in ipairs(msg.paths) do
log("%s, isDir: %s", entry.path, tostring(entry.isDir))
state.requestedSubs[#state.requestedSubs+1] = entry.path
end
log("Subscribing to all paths")
return Message(MessageType.SUBSCRIBE, #state.requestedSubs, state.requestedSubs)
end,
[MessageType.SUBSCRIBE_RESPONSE] = function(msg, state)
if not state.subs then
state.subs = {}
end
for _, entry in ipairs(msg.paths) do
state.subs[#state.subs+1] = entry
end
log("Failed to subscribe to paths:")
for _, failed in ipairs(msg.pathsFail) do
log("%s", failed.path)
end
local getAll = {}
for i, entry in ipairs(state.subs) do
if entry.isDir == 0 then
getAll[#getAll+1] = Message(MessageType.GET_FILE, entry.path)
else
filesystem.makeDirectory(filesystem.concat(config.localDir, entry.path))
end
end
return getAll
-- local toCompare = {}
-- if #state.subs > 0 then
-- for _, path in ipairs(state.subs) do
-- local serverPath = filesystem.canonical(path)
-- local localPath = filesystem.canonical(config.localDir)
-- -- translate server path to local path
-- local serverSegments = filesystem.segments(serverPath)
-- local localSegments = filesystem.segments(localPath)
-- local fullLocalPath = filesystem.concat(localPath, serverPath)
-- if not filesystem.isDirectory(fullLocalPath) then
-- -- if path doesn't exist size is 0
-- toCompare[#toCompare+1] = {path = serverPath, size = filesystem.size(fullLocalPath)}
-- else
-- -- if dir then create
-- end
-- end
-- end
-- return Message(MessageType.COMPARE_FILES, #toCompare, toCompare)
end,
[MessageType.SEND_HASHES] = function(msg, state) end,
[MessageType.SEND_FILE] = function(msg, state)
local targetPath = filesystem.concat(config.localDir, msg.path)
log("Got requested file %s, saving as %s", msg.path, targetPath)
filesystem.makeDirectory(filesystem.path(targetPath))
local file = io.open(targetPath, "w")
file:write(msg.contents)
file:close()
end,
[MessageType.SEND_FILE_ERROR] = function(msg, state)
log("Error requesting file %s, server responded with: %s", msg.path, msg.reason)
end,
[MessageType.NOTIFY_CHANGE] = function(msg, state)
log("%s modified", msg.path)
if msg.isDir == 0 then
return Message(MessageType.GET_FILE, msg.path)
end
end,
[MessageType.NOTIFY_DELETE] = function(msg, state)
log("%s deleted", msg.path)
filesystem.remove(filesystem.concat(config.localDir, msg.path))
end,
[MessageType.NOTIFY_CREATE] = function(msg, state)
log("%s created", msg.path)
local targetPath = filesystem.concat(config.localDir, msg.path)
if msg.isDir == 0 then
io.open(targetPath, "w"):close()
elseif msg.isDir == 1 then
filesystem.makeDirectory(targetPath)
log("Subscribing to new folder: %s", msg.path)
return Message(MessageType.SUBSCRIBE, 1, {msg.path})
end
end,
[MessageType.NOTIFY_MOVE] = function(msg, state)
log("%s moved to %s", msg.srcPath, msg.dstPath)
filesystem.rename(filesystem.concat(config.localDir, msg.srcPath), filesystem.concat(config.localDir, msg.dstPath))
filesystem.remove(filesystem.concat(config.localDir, msg.srcPath))
end,
}
local function messageHandler(data, state)
local message = Message(data)
local response = handlers[message.type](message, state)
if response then
if utils.isInstance(response, Message) then
return {response:toBytes()}
elseif type(response) == "table" then
for i = 1, #response do
response[i] = response[i]:toBytes()
end
return response
end
end
end
return messageHandler |
earths_spite = {
cast = function(player, target)
local duration = 425000
local magicCost = 500
if (not player:canCast(1, 1, 0)) then
return
end
if (player.magic < magicCost) then
player:sendMinitext("Not enough mana.")
return
end
if (target.state == 1) then
player:sendMinitext("That is no longer useful.")
return
end
if (target.blType == BL_PC and not player:canPK(target)) or target.blType == BL_NPC then
player:sendMinitext("You cannot attack that target.")
return
end
if target:checkIfCast(curses) or target.cursed == 1 then
player:sendMinitext("Another spell of this type is in effect.")
return
end
if target:checkIfCast(protections) then
player:sendMinitext("The target is already protected.")
return
end
if target:hasDuration("snare_trap") then
target:setDuration("snare_trap", 0)
end
player:sendAction(6, 20)
player.magic = player.magic - magicCost
player:sendStatus()
player:playSound(702)
player:sendMinitext("You cast Earths spite.")
target:setDuration("earths_spite", duration)
target:sendAnimation(1, 0)
if (target.blType == BL_MOB) then
target.armor = target.armor + 45
target.cursed = 1
elseif (target.blType == BL_PC and player:canPK(target)) then
target:sendMinitext(player.name .. " casts Earths spite on you.")
target:calcStat()
end
end,
while_cast = function(block)
if (block.blType == BL_MOB and block.charState ~= 2) then
block:sendAnimation(34, 0)
elseif (block.blType == BL_PC and block.state ~= 2) then
block:sendAnimation(34, 0)
end
end,
recast = function(target)
target.armor = target.armor + 45
target.cursed = 1
target:sendStatus()
end,
uncast = function(target)
target.armor = target.armor - 45
target.cursed = 0
target:sendStatus()
end,
requirements = function(player)
local level = 99
local items = {"il_san_surge", "star_staff", "scribes_book", 0}
local itemAmounts = {1, 2, 2, 40000}
local description = "Weaken your opponent for a short time"
return level, items, itemAmounts, description
end
}
|
zombie = class("zombie")
zombies = {}
local zombieQuadSheet = love.graphics.newImage("assets/gfx/zombies/zombiesheet1.png")
local zombieQuadSheetWidth = zombieQuadSheet:getWidth()
local zombieQuadSheetHeight = zombieQuadSheet:getHeight()
local zombieQuads = {
love.graphics.newQuad(0, 0, 17, 22, zombieQuadSheetWidth, zombieQuadSheetHeight),
love.graphics.newQuad(17, 0, 17, 22, zombieQuadSheetWidth, zombieQuadSheetHeight),
love.graphics.newQuad(17*2, 0, 17, 22, zombieQuadSheetWidth, zombieQuadSheetHeight),
love.graphics.newQuad(17*3, 0, 17, 22, zombieQuadSheetWidth, zombieQuadSheetHeight),
love.graphics.newQuad(17*4, 0, 17, 22, zombieQuadSheetWidth, zombieQuadSheetHeight),
}
local zombieSpawnerTimer = 0
zombieInterval = 5
local shadowImage = love.graphics.newImage("assets/gfx/misc/shadow.png")
function zombie:initialize()
self.x = math.random(10, pitch.width-1)
self.y = math.random(200, 400)
self.lastX = self.x
self.lastY = self.y
self.width = 17
self.height = 22
self.state = "spawning"
self.spawnTimer = 0
self.canDie = false
self.health = 3
self.speed = 30
self.type = "zombie"
self.sheet = love.graphics.newImage("assets/gfx/zombies/zombiespawn1.png")
self.grid = anim8.newGrid(17, 22, self.sheet:getWidth(), self.sheet:getHeight())
self.spawningAnimation = anim8.newAnimation(self.grid("1-7", 1), 0.3)
self.direction = 1
self.currentQuad = 1
self.up = false
self.left = false
self.down = false
self.right = false
self.closest = {4, 100000}
self.id = #zombies+1
table.insert(zombies, self)
collisionWorld:add(self, self.x, self.y, self.width, self.height)
end
function zombie:update(dt)
if self.state == "spawning" then
self:handleSpawning(dt)
else
self:movementAI(dt)
decideDirection(zombies[self.id])
self:collide(dt)
collisionWorld:update(self, self.x, self.y)
if self.health <= 0 then
zombies[self.id] = nil
collisionWorld:remove(self)
end
end
end
function zombie:draw()
if self.state == "spawning" then
self.spawningAnimation:draw(self.sheet, self.x, self.y)
else
local offset = 2 -- This could be better. Don't have time to improve
if self.currentQuad == 1 or self.currentQuad == 2 then
offset = 3
end
love.graphics.draw(shadowImage, self.x+offset, self.y + 15)
love.graphics.draw(zombieQuadSheet, zombieQuads[self.currentQuad], self.x, self.y)
end
end
function zombie:handleSpawning(dt)
self.spawningAnimation:update(dt)
self.spawnTimer = self.spawnTimer + dt
if self.spawnTimer >= 7*0.3 then
self.state = "roaming"
end
end
function zombie:movementAI(dt)
self.lastx = self.x
self.lastY = self.y
self:findClosestPlayer()
--Go towards closest player
if players[self.closest[1]] then
if self.x < players[self.closest[1]].x then
self.x = self.x + self.speed*dt
if self.x > players[self.closest[1]].x then
self.x = players[self.closest[1]].x
end
elseif self.x > players[self.closest[1]].x then
self.x = self.x - self.speed*dt
if self.x < players[self.closest[1]].x then
self.x = players[self.closest[1]].x
end
end
if self.y < players[self.closest[1]].y then
self.y = self.y + self.speed*dt
if self.y > players[self.closest[1]].y then
self.y = players[self.closest[1]].y
end
elseif self.y > players[self.closest[1]].y then
self.y = self.y - self.speed*dt
if self.y < players[self.closest[1]].y then
self.y = players[self.closest[1]].y
end
end
end
end
function zombie:collide(dt)
local actualX, actualY, cols, len = collisionWorld:check(self, self.x, self.y)
if #cols > 0 then
for i,v in pairs(cols) do
if v.other.type == "bullet" then
self.health = self.health - 1
--Destory bullet
bullets[v.other.id] = nil
collisionWorld:remove(v.other)
end
end
end
end
function zombie:findClosestPlayer()
for i, v in pairs(players) do
local distanceX = 0
local distanceY = 0
if v.x > self.x then
distanceX = v.x - self.x
else
distanceX = self.x - v.x
end
if v.y > self.y then
distanceY = v.y - self.y
else
distanceY = self.y - v.y
end
--How far away the player is from the zombie
local distance = distanceX + distanceY
if distance < self.closest[2] then
self.closest = {v.id, distance}
end
end
end
function updateZombies(dt)
for i,v in pairs(zombies) do
v:update(dt)
end
zombieSpawnerTimer = zombieSpawnerTimer + dt
if zombieSpawnerTimer >= zombieInterval then
zombie:new()
zombieSpawnerTimer = 0
end
end
function drawZombies()
for i,v in pairs(zombies) do
v:draw()
end
end
function removeAllZombies()
for i,v in pairs(zombies) do
collisionWorld:remove(v)
end
zombies = {}
zombieSpawnerTimer = 0
end |
--action event pack
--H_Kotori_02
return
{
["Attack1"] = {
[1] = {
type = "UserState",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true,
content = "KotoriFocus"
},
[2] = {
type = "AttackWindow",
time = Fixed64(65011712) --[[62]],
realTime = Fixed64(1603622) --[[1.529333]],
toggle = true,
isClear = true
},
[3] = {
type = "UserState",
time = Fixed64(104857600) --[[100]],
realTime = Fixed64(2586487) --[[2.466667]],
toggle = false,
content = "KotoriFocus"
}
},
["Attack2"] = {
[1] = {
type = "Forward",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
filePath = "H_Kotori/curve_Attack2"
},
[2] = {
type = "RushWindow",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[3] = {
type = "Attack",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(235930) --[[0.225]],
filePath = "H_Kotori/attack_Attack2",
damageRatio = Fixed64(314573) --[[0.3]]
},
[4] = {
type = "Effect",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(235930) --[[0.225]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_attact002",
boneNogType = "None",
isGlobalSpace = false,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[5] = {
type = "CameraEffect",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(235930) --[[0.225]],
cameraEffectId = Fixed64(0) --[[0]]
},
[6] = {
type = "Attack",
time = Fixed64(23068672) --[[22]],
realTime = Fixed64(346031) --[[0.33]],
filePath = "H_Kotori/attack_Attack2",
damageRatio = Fixed64(349176) --[[0.333]]
},
[7] = {
type = "Attack",
time = Fixed64(27262976) --[[26]],
realTime = Fixed64(408945) --[[0.39]],
filePath = "H_Kotori/attack_Attack2",
damageRatio = Fixed64(384828) --[[0.367]]
},
[8] = {
type = "AttackWindow",
time = Fixed64(31457280) --[[30]],
realTime = Fixed64(471860) --[[0.45]],
toggle = true,
isClear = false
},
[9] = {
type = "RunWindow",
time = Fixed64(73400320) --[[70]],
realTime = Fixed64(1101005) --[[1.05]],
toggle = true
}
},
["Attack3"] = {
[1] = {
type = "RushWindow",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[2] = {
type = "Forward",
time = Fixed64(15518925) --[[14.8]],
realTime = Fixed64(310379) --[[0.296]],
filePath = "H_Kotori/curve_Attack3"
},
[3] = {
type = "Attack",
time = Fixed64(19922944) --[[19]],
realTime = Fixed64(398458) --[[0.38]],
filePath = "H_Kotori/attack_Attack3",
damageRatio = Fixed64(314573) --[[0.3]]
},
[4] = {
type = "CameraEffect",
time = Fixed64(19922944) --[[19]],
realTime = Fixed64(398458) --[[0.38]],
cameraEffectId = Fixed64(0) --[[0]]
},
[5] = {
type = "Effect",
time = Fixed64(19922944) --[[19]],
realTime = Fixed64(398458) --[[0.38]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_attact003_02",
boneNogType = "None",
isGlobalSpace = false,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[6] = {
type = "Attack",
time = Fixed64(34603008) --[[33]],
realTime = Fixed64(692061) --[[0.66]],
filePath = "H_Kotori/attack_Attack3",
damageRatio = Fixed64(262144) --[[0.25]]
},
[7] = {
type = "Attack",
time = Fixed64(36175872) --[[34.5]],
realTime = Fixed64(723517) --[[0.69]],
filePath = "H_Kotori/attack_Attack3",
damageRatio = Fixed64(262144) --[[0.25]]
},
[8] = {
type = "CameraEffect",
time = Fixed64(36175872) --[[34.5]],
realTime = Fixed64(723517) --[[0.69]],
cameraEffectId = Fixed64(0) --[[0]]
},
[9] = {
type = "Attack",
time = Fixed64(38273024) --[[36.5]],
realTime = Fixed64(765461) --[[0.73]],
filePath = "H_Kotori/attack_Attack3",
damageRatio = Fixed64(209716) --[[0.2]]
},
[10] = {
type = "AttackWindow",
time = Fixed64(52428800) --[[50]],
realTime = Fixed64(1048576) --[[1]],
toggle = true,
isClear = false
},
[11] = {
type = "RunWindow",
time = Fixed64(73400320) --[[70]],
realTime = Fixed64(1468006) --[[1.4]],
toggle = true
}
},
["Attack4"] = {
[1] = {
type = "RushWindow",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[2] = {
type = "Forward",
time = Fixed64(7130317) --[[6.8]],
realTime = Fixed64(147360) --[[0.1405333]],
filePath = "H_Kotori/curve_Attack4"
},
[3] = {
type = "Attack",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(325059) --[[0.31]],
filePath = "H_Kotori/attack_Attack4",
damageRatio = Fixed64(314573) --[[0.3]]
},
[4] = {
type = "Effect",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(325059) --[[0.31]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_attact004",
boneNogType = "None",
isGlobalSpace = false,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[5] = {
type = "Attack",
time = Fixed64(24117248) --[[23]],
realTime = Fixed64(498423) --[[0.4753334]],
filePath = "H_Kotori/attack_Attack4",
damageRatio = Fixed64(349176) --[[0.333]]
},
[6] = {
type = "CameraEffect",
time = Fixed64(38797312) --[[37]],
realTime = Fixed64(801811) --[[0.7646667]],
cameraEffectId = Fixed64(0) --[[0]]
},
[7] = {
type = "Attack",
time = Fixed64(38797312) --[[37]],
realTime = Fixed64(801811) --[[0.7646667]],
filePath = "H_Kotori/attack_Attack4_1",
damageRatio = Fixed64(384828) --[[0.367]]
},
[8] = {
type = "Effect",
time = Fixed64(38797312) --[[37]],
realTime = Fixed64(801811) --[[0.7646667]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_attact004_01",
boneNogType = "None",
isGlobalSpace = true,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[9] = {
type = "RunWindow",
time = Fixed64(60817408) --[[58]],
realTime = Fixed64(1256893) --[[1.198667]],
toggle = true
}
},
["Skill1"] = {
[1] = {
type = "Forward",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
filePath = "H_Kotori/curve_Skill1"
},
[2] = {
type = "RushWindow",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[3] = {
type = "Attack",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(419431) --[[0.4]],
filePath = "H_Kotori/attack_Skill1",
damageRatio = Fixed64(314573) --[[0.3]]
},
[4] = {
type = "Effect",
time = Fixed64(15728640) --[[15]],
realTime = Fixed64(419431) --[[0.4]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_skill001",
boneNogType = "None",
isGlobalSpace = true,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[5] = {
type = "Effect",
time = Fixed64(41943040) --[[40]],
realTime = Fixed64(1118481) --[[1.066667]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_skill001_01",
boneNogType = "None",
isGlobalSpace = false,
isClear = true,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[6] = {
type = "Attack",
time = Fixed64(46137344) --[[44]],
realTime = Fixed64(1230329) --[[1.173333]],
filePath = "H_Kotori/attack_Skill1",
damageRatio = Fixed64(314573) --[[0.3]]
},
[7] = {
type = "Effect",
time = Fixed64(48234496) --[[46]],
realTime = Fixed64(1286253) --[[1.226667]],
filePath = "Effect/H_Kotori_01/H_Kotori_01_skill001_chixu",
boneNogType = "None",
isGlobalSpace = true,
isClear = false,
isCustomLifeTime = false,
customLifeTime = Fixed64(0) --[[0]]
},
[8] = {
type = "Attack",
time = Fixed64(56623104) --[[54]],
realTime = Fixed64(1509950) --[[1.44]],
filePath = "H_Kotori/attack_Skill1",
damageRatio = Fixed64(419431) --[[0.4]]
}
},
["Skill3"] = {
[1] = {
type = "RushWindow",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[2] = {
type = "Attack",
time = Fixed64(16252928) --[[15.5]],
realTime = Fixed64(503841) --[[0.4805]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(52429) --[[0.05]]
},
[3] = {
type = "Attack",
time = Fixed64(20971520) --[[20]],
realTime = Fixed64(650118) --[[0.62]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(52429) --[[0.05]]
},
[4] = {
type = "Attack",
time = Fixed64(26214400) --[[25]],
realTime = Fixed64(812647) --[[0.775]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(52429) --[[0.05]]
},
[5] = {
type = "Attack",
time = Fixed64(31457280) --[[30]],
realTime = Fixed64(975176) --[[0.9300001]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(52429) --[[0.05]]
},
[6] = {
type = "Forward",
time = Fixed64(39636172) --[[37.8]],
realTime = Fixed64(1228722) --[[1.1718]],
filePath = "H_Kotori/curve_Skill3_1"
},
[7] = {
type = "Attack",
time = Fixed64(44040192) --[[42]],
realTime = Fixed64(1365246) --[[1.302]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(209716) --[[0.2]]
},
[8] = {
type = "Attack",
time = Fixed64(47185920) --[[45]],
realTime = Fixed64(1462764) --[[1.395]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(209716) --[[0.2]]
},
[9] = {
type = "Attack",
time = Fixed64(50331648) --[[48]],
realTime = Fixed64(1560282) --[[1.488]],
filePath = "H_Kotori/attack_Skill3",
damageRatio = Fixed64(419431) --[[0.4]]
}
},
["Rush"] = {
[1] = {
type = "Super",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[2] = {
type = "SpaceCheck",
time = Fixed64(10485760) --[[10]],
realTime = Fixed64(76896) --[[0.07333334]],
toggle = true,
spaceTime = Fixed64(62914560) --[[60]],
spaceRealTime = Fixed64(461373) --[[0.44]]
},
[3] = {
type = "Forward",
time = Fixed64(23068672) --[[22]],
realTime = Fixed64(169170) --[[0.1613333]],
filePath = "H_Kotori/curve_Rush"
},
[4] = {
type = "RunWindow",
time = Fixed64(73400320) --[[70]],
realTime = Fixed64(538269) --[[0.5133333]],
toggle = true
},
[5] = {
type = "Super",
time = Fixed64(104857600) --[[100]],
realTime = Fixed64(768956) --[[0.7333333]],
toggle = false
}
},
["RushBack"] = {
[1] = {
type = "AttackWindow",
time = Fixed64(2936012) --[[2.8]],
realTime = Fixed64(17617) --[[0.0168]],
toggle = true,
isClear = false
},
[2] = {
type = "SpaceCheck",
time = Fixed64(10485760) --[[10]],
realTime = Fixed64(62915) --[[0.06]],
toggle = true,
spaceTime = Fixed64(62914560) --[[60]],
spaceRealTime = Fixed64(377488) --[[0.36]]
},
[3] = {
type = "Backward",
time = Fixed64(17825792) --[[17]],
realTime = Fixed64(106955) --[[0.102]],
filePath = "H_Kotori/curve_RushBack"
},
[4] = {
type = "RunWindow",
time = Fixed64(78643200) --[[75]],
realTime = Fixed64(471860) --[[0.45]],
toggle = true
}
},
["Start"] = {
[1] = {
type = "CameraSpecial",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
toggle = true
},
[2] = {
type = "CameraSpecial",
time = Fixed64(94371840) --[[90]],
realTime = Fixed64(4089447) --[[3.9]],
toggle = false
}
},
["Run"] = {
[1] = {
type = "Forward",
time = Fixed64(0) --[[0]],
realTime = Fixed64(0) --[[0]],
filePath = "H_Kotori/Run"
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.