content
stringlengths 5
1.05M
|
---|
--- A simple interface to mmap.
-- mmapfile uses `mmap` to provide a way of quickly storing and loading data
-- that's already in some kind of in-memory binary format.
--
-- `create` creates a new file and maps new memory to that file. You can
-- then write to the memory to write to the file.
--
-- `open` opens an existing file and maps its contents to memory, returning
-- a pointer to the memory and the length of the file.
--
-- `close` syncs memory to the file, closes the file, and deletes the
-- mapping between the memory and the file.
--
-- The "gc" variants of `create` and `open` (`gccreate` and `gcopen`) set
-- up a garbage collection callback for the pointer so that the file is
-- correctly closed when the pointer is no longer referenced. Not
-- appropriate if you might be storing the pointer in C, referencing it from
-- unmanaged memory, or casting it to another type!
--
-- All memory is mapped above 4G to try to keep away from the memory space
-- LuaJIT uses.
local S = require"syscall"
local ffi = require"ffi"
------------------------------------------------------------------------------
local function assert(condition, message)
if condition then return condition end
message = message or "assertion failed"
error(tostring(message), 2)
end
------------------------------------------------------------------------------
--- Call mmap until we get an address higher that 4 gigabytes.
-- mmapping over 4G means we don't step on LuaJIT's toes, and this usually
-- works first time.
-- See `man mmap` for explanation of parameters.
-- @treturn pointer: the memory allocated.
local function mmap_4G(
size, -- integer: size to allocate in bytes
prot, -- string: mmap's prot, as interpreted by syscall
flags, -- string: mmap's flags, as interpreted by syscall
fd, -- integer: file descriptor to map to
offset) -- ?integer: offset into file to map
offset = offset or 0
local base = 4 * 1024 * 1024 * 1024
local step = 2^math.floor(math.log(tonumber(size)) / math.log(2))
local addr
for _ = 1, 1024 do
addr = S.mmap(ffi.cast("void*", base), size, prot, flags, fd, offset)
if addr >= ffi.cast("void*", 4 * 1024 * 1024 * 1024) then break end
S.munmap(addr, size)
base = base + step
end
return addr
end
------------------------------------------------------------------------------
local malloced_sizes = {}
--- "Map" some anonymous memory that's not mapped to a file.
-- This makes mmap behave a bit like malloc, except that we can persuade it
-- to give us memory above 4G, and malloc will be a very, very slow allocator
-- so only use it infrequently on big blocks of memory.
-- This is really just a hack to get us memory above 4G. There's probably a
-- better solution.
-- @treturn pointer: the memory allocated.
local function malloc(
size, -- integer: number of bytes or `type`s to allocate.
type, -- ?string: type to allocate
data) -- ?pointer: data to copy to the mapped area.
if type then
size = size * ffi.sizeof(type)
end
local addr = assert(mmap_4G(size, "read, write", "anon, shared"))
malloced_sizes[tostring(ffi.cast("void*", addr))] = size
if data then
ffi.copy(addr, data, size)
end
if type then
return ffi.cast(type.."*", addr)
else
return addr
end
end
--- Free memory mapped with mmapfile.malloc
-- Just munmaps the memory.
local function free(
addr) -- pointer: the mapped address to unmap.
local s = tostring(ffi.cast("void*", addr))
local size = assert(malloced_sizes[s], "no mmapped block at this address")
assert(S.munmap(addr, size))
end
------------------------------------------------------------------------------
local open_fds = {}
--- Close a mapping between a file and an address.
-- `msync` the memory to its associated file, `munmap` the memory, and close
-- the file.
local function close(
addr) -- pointer: the mapped address to unmap.
local s = tostring(ffi.cast("void*", addr))
local fd = assert(open_fds[s], "no file open for this address")
open_fds[s] = nil
-- it seems that file descriptors get closed before final __gc calls in
-- some exit scenarios, so we don't worry too much if we can't
-- stat the fd
local st = fd:stat()
if st then
assert(S.msync(addr, st.size, "sync"))
assert(S.munmap(addr, st.size))
assert(fd:close())
end
end
--- Allocate memory and create a new file mapped to it.
-- Use create to set aside an area of memory to write to a file.
-- If `type` is supplied then the pointer to the allocated memory is cast
-- to the correct type, and `size` is the number of `type`, not bytes,
-- to allocate.
-- If `data` is supplied, then the data at `data` is copied into the mapped
-- memory (and so written to the file). It might make more sense just to
-- map the pointer `data` directly to the file, but that might require `data`
-- to be on a page boundary.
-- The file descriptor is saved in a table keyed to the address allocated
-- so that close can find the write fd to close when the memory is unmapped.
-- @treturn pointer: the memory allocated.
local function create(
filename, -- string: name of the file to create.
size, -- integer: number of bytes or `type`s to allocate.
type, -- ?string: type to allocate
data) -- ?pointer: data to copy to the mapped area.
local fd, message = S.open(filename, "RDWR, CREAT", "RUSR, WUSR, RGRP, ROTH")
if not fd then
error(("mmapfile.create: Error creating '%s': %s"):format(filename, message))
end
if type then
size = size * ffi.sizeof(type)
end
-- lseek gets stroppy if we try to seek the -1th byte, so let's just say
-- all files are at least one byte, even if theres's no actual data.
size = math.max(size, 1)
assert(fd:lseek(size-1, "set"))
assert(fd:write(ffi.new("char[1]", 0), 1))
local addr = assert(mmap_4G(size, "read, write", "file, shared", fd))
open_fds[tostring(ffi.cast("void*", addr))] = fd
if data then
ffi.copy(addr, data, size)
end
if type then
return ffi.cast(type.."*", addr)
else
return addr
end
end
--- Map an existing file to an area of memory.
-- If `type` is present, the the pointer returned is cast to the `type*` and
-- the size returned is the number of `types`, not bytes.
-- @treturn pointer: the memory allocated.
-- @treturn int: size of the file, in bytes or `type`s.
local function open(
filename, -- string: name of the file to open.
type, -- ?string: type to allocate (default void*)
mode, -- ?string: open mode for the file "r" or "rw" (default "r")
size, -- ?integer: size to map (in multiples of type). Default
-- is file size
offset) -- ?integer: offset into the file (default 0)
offset = offset or 0
mode = mode or "r"
local filemode, mapmode
if mode == "r" then
filemode = "rdonly"
mapmode = "read"
elseif mode == "rw" then
filemode = "rdwr"
mapmode = "read, write"
else
return nil, "unknown read/write mode"
end
local fd, message = S.open(filename, filemode, 0)
if not fd then
error(("mmapfile.open: Error opening %s: %s"):format(filename, message))
end
if not size then
local st = assert(fd:stat())
size = st.size
elseif type then
size = size * ffi.sizeof(type)
end
local addr = assert(mmap_4G(size, mapmode, "file, shared", fd, offset))
open_fds[tostring(ffi.cast("void*", addr))] = fd
if type then
return ffi.cast(type.."*", addr), math.floor(size / ffi.sizeof(type))
else
return addr, size
end
end
------------------------------------------------------------------------------
return
{
free = free,
malloc = malloc,
create = create,
open = open,
close = close,
}
------------------------------------------------------------------------------
|
--***********************************************************
--** THE INDIE STONE **
--***********************************************************
---@class ConnectToServer : ISPanelJoypad
ConnectToServer = ISPanelJoypad:derive("ConnectToServer")
local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small)
local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.Medium)
local FONT_HGT_LARGE = getTextManager():getFontHeight(UIFont.Large)
function ConnectToServer:create()
local buttonHgt = math.max(FONT_HGT_SMALL + 3 * 2, 25)
self.title = ISLabel:new(self.width / 2, 20, 50, "???", 1, 1, 1, 1, UIFont.Large, true)
self.title:initialise()
self.title:instantiate()
self.title:setAnchorLeft(true)
self.title:setAnchorRight(false)
self.title:setAnchorTop(true)
self.title:setAnchorBottom(false)
self.title.center = true
self:addChild(self.title)
self.serverName1 = ISLabel:new(self.width / 2 - 6, self.title:getBottom() + 40, FONT_HGT_MEDIUM, getText("UI_ConnectToServer_ServerName"), 0.7, 0.7, 0.7, 1, UIFont.Medium, false)
self.serverName1:initialise()
self.serverName1:instantiate()
self.serverName1:setAnchorLeft(true)
self.serverName1:setAnchorRight(false)
self.serverName1:setAnchorTop(true)
self.serverName1:setAnchorBottom(false)
self:addChild(self.serverName1)
self.userName1 = ISLabel:new(self.width / 2 - 6, self.serverName1:getBottom() + 8, FONT_HGT_MEDIUM, getText("UI_ConnectToServer_UserName"), 0.7, 0.7, 0.7, 1, UIFont.Medium, false)
self.userName1:initialise()
self.userName1:instantiate()
self.userName1:setAnchorLeft(true)
self.userName1:setAnchorRight(false)
self.userName1:setAnchorTop(true)
self.userName1:setAnchorBottom(false)
self:addChild(self.userName1)
local labelX = self.width / 2 + 6
self.serverName = ISLabel:new(labelX, self.title:getBottom() + 40, FONT_HGT_MEDIUM, "???", 1, 1, 1, 1, UIFont.Medium, true)
self.serverName:initialise()
self.serverName:instantiate()
self.serverName:setAnchorLeft(true)
self.serverName:setAnchorRight(false)
self.serverName:setAnchorTop(true)
self.serverName:setAnchorBottom(false)
self:addChild(self.serverName)
self.userName = ISLabel:new(labelX, self.serverName:getBottom() + 8, FONT_HGT_MEDIUM, "???", 1, 1, 1, 1, UIFont.Medium, true)
self.userName:initialise()
self.userName:instantiate()
self.userName:setAnchorLeft(true)
self.userName:setAnchorRight(false)
self.userName:setAnchorTop(true)
self.userName:setAnchorBottom(false)
self:addChild(self.userName)
self.connectLabel = ISLabel:new(self.width / 2, self.userName:getBottom() + 50, FONT_HGT_MEDIUM, "", 1, 1, 1, 1, UIFont.Medium, true)
self.connectLabel:initialise()
self.connectLabel:instantiate()
self.connectLabel:setAnchorLeft(true)
self.connectLabel:setAnchorRight(false)
self.connectLabel:setAnchorTop(true)
self.connectLabel:setAnchorBottom(false)
self.connectLabel.center = true
self:addChild(self.connectLabel)
self.richText = ISRichTextPanel:new(0, self.connectLabel:getBottom() + 150, self.width * 4 / 5, FONT_HGT_MEDIUM * 4)
self.richText:initialise()
self.richText:instantiate()
self.richText:noBackground()
self.richText:setMargins(0, 0, 0, 0)
self.richText.font = UIFont.Medium
self:addChild(self.richText)
self.richText.text = getSteamModeActive() and getText("UI_ConnectToServer_ReminderSteam") or getText("UI_ConnectToServer_ReminderNoSteam")
self.richText.text = " <CENTRE> " .. self.richText.text
self.richText:paginate()
self.richText:setX(self.width / 2 - self.richText.width / 2)
self.backBtn = ISButton:new((self.width - 100) / 2, self.height - 50, 100, buttonHgt, getText("UI_btn_back"), self, self.onBackButton)
self.backBtn.internal = "BACK"
self.backBtn:initialise()
self.backBtn:instantiate()
self.backBtn:setAnchorLeft(true)
self.backBtn:setAnchorRight(false)
self.backBtn:setAnchorTop(false)
self.backBtn:setAnchorBottom(true)
self:addChild(self.backBtn)
self.arrowBG = getTexture("media/ui/ArrowRight_Disabled.png")
self.arrowFG = getTexture("media/ui/ArrowRight.png")
ConnectToServer.instance = self
end
function ConnectToServer:prerender()
ISPanelJoypad.prerender(self)
ConnectToServer.instance = self
end
function ConnectToServer:render()
ISPanelJoypad.render(self)
if self.connecting then
local x = self.width / 2 - 15 * 1.5
local y = self.connectLabel.y - 25
self:drawTexture(self.arrowBG, x, y, 1, 1, 1, 1)
self:drawTexture(self.arrowBG, x + 15, y, 1, 1, 1, 1)
self:drawTexture(self.arrowBG, x + 30, y, 1, 1, 1, 1)
local ms = UIManager.getMillisSinceLastRender()
self.timerMultiplierAnim = (self.timerMultiplierAnim or 0) + ms
if self.timerMultiplierAnim <= 500 then
self.animOffset = -1
elseif self.timerMultiplierAnim <= 1000 then
self.animOffset = 0
elseif self.timerMultiplierAnim <= 1500 then
self.animOffset = 15
elseif self.timerMultiplierAnim <= 2000 then
self.animOffset = 30
else
self.timerMultiplierAnim = 0
end
if self.animOffset > -1 then
self:drawTexture(self.arrowFG, x + self.animOffset, y, 1, 1, 1, 1)
end
end
end
function ConnectToServer:onResize(width, height)
ISPanelJoypad.onResize(self, width, height)
if not self.title then return end
self.title:setX(width / 2)
self.serverName1:setX(width / 2 - 6 - self.serverName1.width)
self.userName1:setX(width / 2 - 6 - self.userName1.width)
self.serverName:setX(width / 2 + 6)
self.userName:setX(width / 2 + 6)
self.connectLabel:setX(width / 2)
self.richText:setX(width / 2 - self.richText.width / 2)
self.backBtn:setX(width / 2 - self.backBtn.width / 2)
end
function ConnectToServer:onBackButton()
if self.connecting or isClient() then
self.connecting = false
backToSinglePlayer()
end
self:setVisible(false)
if self.isCoop then
MainScreen.instance.bottomPanel:setVisible(true, self.joyfocus)
else
self.previousScreen:setVisible(true, self.joyfocus)
end
end
function ConnectToServer:connect(previousScreen, serverName, userName, password, IP, localIP, port, serverPassword)
previousScreen:setVisible(false)
self:setVisible(true, previousScreen.joyfocus)
self.previousScreen = previousScreen
self.title:setName(getText("UI_ConnectToServer_TitleDedicated"))
self.serverName1:setVisible(true)
self.serverName:setVisible(true)
if serverName == "" then
self.serverName1:setName(getText("UI_ConnectToServer_ServerIP"))
self.serverName:setName(IP)
else
self.serverName1:setName(getText("UI_ConnectToServer_ServerName"))
self.serverName:setName(serverName)
end
self.userName:setName(userName)
self.connectLabel.name = getText("UI_servers_Connecting")
self.failMessage = nil
self.backBtn:setTitle(getText("UI_coopscreen_btn_abort"))
self.connecting = true
self.isCoop = false
self:onResize(self.width, self.height)
serverConnect(userName, password, IP, localIP, port, serverPassword)
end
function ConnectToServer:connectCoop(previousScreen, serverSteamID)
previousScreen:setVisible(false)
self:setVisible(true, previousScreen.joyfocus)
self.previousScreen = previousScreen
self.title:setName(getText("UI_ConnectToServer_TitleCoop"))
self.serverName1:setVisible(false)
self.serverName:setVisible(false)
self.userName:setName(getCurrentUserProfileName())
self.connectLabel.name = getText("UI_servers_Connecting")
self.failMessage = nil
self.backBtn:setTitle(getText("UI_coopscreen_btn_abort"))
self.connecting = true
self.isCoop = true
self:onResize(self.width, self.height)
serverConnectCoop(serverSteamID)
end
function ConnectToServer:onGainJoypadFocus(joypadData)
ISPanelJoypad.onGainJoypadFocus(self, joypadData)
self:setISButtonForB(self.backBtn)
end
function ConnectToServer:OnConnected()
if not SystemDisabler.getAllowDebugConnections() and getDebug() and not isAdmin() and not isCoopHost() and
not SystemDisabler.getOverrideServerConnectDebugCheck() then
forceDisconnect()
return
end
self.connecting = false
self:setVisible(false)
local joypadData = JoypadState.getMainMenuJoypad()
if not checkSavePlayerExists() then
if MapSpawnSelect.instance:hasChoices() then
MapSpawnSelect.instance:fillList()
MapSpawnSelect.instance:setVisible(true, joypadData)
elseif WorldSelect.instance:hasChoices() then
WorldSelect.instance:fillList()
WorldSelect.instance:setVisible(true, joypadData)
else
MapSpawnSelect.instance:useDefaultSpawnRegion()
MainScreen.instance.charCreationProfession.previousScreen = nil
MainScreen.instance.charCreationProfession:setVisible(true, joypadData)
end
else
GameWindow.doRenderEvent(false)
--[[
-- menu activated via joypad, we disable the joypads and will re-set them automatically when the game is started
if joypadData then
joypadData.focus = nil
updateJoypadFocus(joypadData)
JoypadState.count = 0
JoypadState.players = {}
JoypadState.joypads = {}
JoypadState.forceActivate = joypadData.id
end
--]]
forceChangeState(GameLoadingState.new())
end
end
function ConnectToServer:OnConnectFailed(message, detail)
-- Other screens have Events.OnConnectFailed callbacks too
if not self:getIsVisible() then return end
if message == "ServerWorkshopItemsCancelled" then
self:onBackButton()
return
end
-- AccessDenied has a message from the server telling the client why the connection is refused.
-- But it is followed by ID_DISCONNECTION_NOTIFICATION which has no message.
-- So keep the first message we get after clicking the connect button.
if not self.failMessage then self.failMessage = message end
if not message then message = self.failMessage end
if message and string.match(message, "MODURL=") then
local test = string.split(message, "MODURL=")
message = test[1]
--[[
self.getModBtn:setVisible(true)
self.getModBtn:setX(5 + (getTextManager():MeasureStringX(UIFont.Medium, message)/2) + self.listbox.x + self.listbox.width/2)
self.getModBtn.url = test[2]
--]]
end
message = message or getText("UI_servers_connectionfailed")
if detail and detail ~= "" then
message = message .. "\n" .. detail
end
self.connectLabel.name = message
self.backBtn:setTitle(getText("UI_btn_back"))
self.connecting = false
end
function ConnectToServer:OnConnectionStateChanged(state, message)
if not self:getIsVisible() then return end
print(state .. ',' .. tostring(message))
if state == "Disconnected" then return end
if state == "Disconnecting" then return end
if state == "Failed" and message then self.failMessage = getText('UI_servers_'..message); return end
-- Set connecting to false so we don't draw the > > > in render()
if state == "Connected" then self.connecting = false end
self.connectLabel.name = state and getText('UI_servers_'..state) or "???"
end
local function OnConnected()
ConnectToServer.instance:OnConnected()
end
local function OnConnectFailed(message, detail)
ConnectToServer.instance:OnConnectFailed(message, detail)
end
local function OnConnectionStateChanged(state, message)
ConnectToServer.instance:OnConnectionStateChanged(state, message)
end
Events.OnConnected.Add(OnConnected)
Events.OnConnectFailed.Add(OnConnectFailed)
Events.OnDisconnect.Add(OnConnectFailed)
Events.OnConnectionStateChanged.Add(OnConnectionStateChanged)
|
-- a reference to the primary ActorFrame
local args = ...
local t = args[1]
local AlphabetWheels = args[2]
-- the highscore name character limit
local CharacterLimit = 4
-- Define the input handler
local InputHandler = function(event)
if not event.PlayerNumber or not event.button then
return false
end
-- a local function to delete a character from a player's highscore name
local function RemoveLastCharacter(pn)
if SL[pn].HighScores.Name:len() > 0 then
-- remove the last character
SL[pn].HighScores.Name = SL[pn].HighScores.Name:sub(1, -2)
-- update the display
t:GetChild("PlayerNameAndDecorations_"..pn):GetChild("PlayerName"):queuecommand("Set")
-- play the "delete" sound
t:GetChild("delete"):playforplayer(event.PlayerNumber)
else
-- there's nothing to delete, so play the "invalid" sound
t:GetChild("invalid"):playforplayer(event.PlayerNumber)
end
end
if event.type ~= "InputEventType_Release" then
local pn = ToEnumShortString(event.PlayerNumber)
if event.GameButton == "MenuRight" and SL[pn].HighScores.EnteringName then
-- scroll this player's AlphabetWheel right by 1
AlphabetWheels[pn]:scroll_by_amount(1)
t:GetChild("move"):playforplayer(event.PlayerNumber)
elseif event.GameButton == "MenuLeft" and SL[pn].HighScores.EnteringName then
-- scroll this player's AlphabetWheel left by 1
AlphabetWheels[pn]:scroll_by_amount(-1)
t:GetChild("move"):playforplayer(event.PlayerNumber)
elseif event.GameButton == "Start" then
if SL[pn].HighScores.EnteringName then
-- This gets us the value selected out of the PossibleCharacters table
-- for example, "A" or "2" or "back"
local SelectedCharacter = AlphabetWheels[pn]:get_info_at_focus_pos()
-- if the player has pressed START on an alphanumeric character
if not (SelectedCharacter == "ok" or SelectedCharacter == "back") then
if SL[pn].HighScores.Name:len() < CharacterLimit then
-- append the new character
SL[pn].HighScores.Name = SL[pn].HighScores.Name .. SelectedCharacter
-- update the display
t:GetChild("PlayerNameAndDecorations_"..pn):GetChild("PlayerName"):queuecommand("Set")
-- play the "enter" sound
t:GetChild("enter"):playforplayer(event.PlayerNumber)
else
t:GetChild("invalid"):playforplayer(event.PlayerNumber)
end
if SL[pn].HighScores.Name:len() >= CharacterLimit then
AlphabetWheels[pn]:scroll_to_pos(2)
end
elseif SelectedCharacter == "ok" then
SL[pn].HighScores.EnteringName = false
-- hide this player's cursor
t:GetChild("PlayerNameAndDecorations_"..pn):GetChild("Cursor"):queuecommand("Hide")
-- hide this player's AlphabetWheel
t:GetChild("AlphabetWheel_"..pn):queuecommand("Hide")
-- play the "enter" sound
t:GetChild("enter"):playforplayer(event.PlayerNumber)
elseif SelectedCharacter == "back" then
RemoveLastCharacter(pn)
end
end
-- check if we're ready to save scores and proceed to the next screen
t:queuecommand("AttemptToFinish")
elseif event.GameButton == "Select" and SL[pn].HighScores.EnteringName then
RemoveLastCharacter(pn)
end
end
return false
end
return InputHandler |
-- CONFIG
-- This is important!!
-- This defines the folder to store all remotes
-- It must be present before the game initiates
local remotesStorage = require(game.Nanoblox).shared.Remotes
local runService = game:GetService("RunService")
-- LOCAL
local ERROR_NO_LISTENER = "Failed to get remoteInstance %s for '%s': no remote is listening on the server."
local Remote = {}
local Signal = require(script.Parent.Signal)
local Maid = require(script.Parent.Maid)
local Promise = require(script.Parent.Promise)
-- BEHAVIOUR
local remotes = {}
remotesStorage.ChildAdded:Connect(function(child)
local name = child.Name
local remote = remotes[name]
if remote then
remote:_setupRemoteFolder()
end
end)
remotesStorage.ChildRemoved:Connect(function(child)
local name = child.Name
local remote = remotes[name]
if remote then
remote:destroy()
end
end)
-- CONSTRUCTOR
function Remote.new(name)
local self = {}
setmetatable(self, Remote)
local maid = Maid.new()
self._maid = maid
self.name = name
self.container = {}
self.remoteFolderAdded = Signal.new()
self.remoteFolder = nil
self:_setupRemoteFolder()
remotes[name] = self
return self
end
-- METAMETHODS
function Remote:__index(index)
local newIndex = Remote[index]
if not newIndex then
local remoteType, remoteInstance, indexFormatted = self:_checkRemoteInstance(index)
if remoteType then
if remoteInstance then
newIndex = remoteInstance[indexFormatted]
else
newIndex = {}
local events = {}
function newIndex:Connect(event)
table.insert(events, event)
end
self:_continueWhenRemoteInstanceLoaded(remoteType, function(newRemoteInstance)
newRemoteInstance[indexFormatted]:Connect(function(...)
for _, event in pairs(events) do
event(...)
end
end)
end)
end
end
end
return newIndex
end
function Remote:__newindex(index, customFunction)
local remoteType, remoteInstance, indexFormatted = self:_checkRemoteInstance(index)
if not remoteType then
rawset(self, index, customFunction)
return
end
self:_continueWhenRemoteInstanceLoaded(remoteType, function(newRemoteInstance)
newRemoteInstance[indexFormatted] = customFunction
end)
end
-- METHODS
function Remote:_continueWhenRemoteInstanceLoaded(remoteType, functionToCall)
local function continueFunc()
local remoteInstance = self:_getRemoteInstance(remoteType)
if remoteInstance then
functionToCall(remoteInstance)
else
local waitForChildRemote
waitForChildRemote = self._maid:give(self.remoteFolder.ChildAdded:Connect(function(child)
if child.Name == remoteType then
waitForChildRemote:Disconnect()
functionToCall(child)
end
end))
end
end
local remoteFolder = self.remoteFolder
if remoteFolder then
continueFunc()
else
local waitForRemoteFolderConnection
waitForRemoteFolderConnection = self._maid:give(self.remoteFolderAdded:Connect(function()
waitForRemoteFolderConnection:Disconnect()
continueFunc()
end))
end
end
function Remote:_setupRemoteFolder()
local remoteFolder = remotesStorage:FindFirstChild(self.name)
if remoteFolder then
for _, remoteInstance in pairs(remoteFolder:GetChildren()) do
local remoteType = remoteInstance.ClassName
self.container[remoteType] = remoteInstance
end
self._maid:give(remoteFolder.ChildAdded:Connect(function(remoteInstance)
local remoteType = remoteInstance.ClassName
self.container[remoteType] = remoteInstance
end))
self.remoteFolder = remoteFolder
self.remoteFolderAdded:Fire()
end
end
function Remote:_checkRemoteInstance(index)
local remoteTypes = {
["onClientEvent"] = "RemoteEvent",
["onClientInvoke"] = "RemoteFunction",
}
local remoteType = remoteTypes[index]
if remoteType then
local remoteInstance = self:_getRemoteInstance(remoteType)
local indexFormatted = index:sub(1,1):upper()..index:sub(2)
return remoteType, remoteInstance, indexFormatted
end
end
function Remote:_getRemoteInstance(remoteType)
local remoteInstance = self.container[remoteType]
if not remoteInstance then
return false
end
return remoteInstance
end
function Remote:fireServer(...)
local remoteType = "RemoteEvent"
local remoteInstance = self:_getRemoteInstance(remoteType)
if not remoteInstance then
-- error(ERROR_NO_LISTENER:format(remoteType, self.name))
return
end
remoteInstance:FireServer(...)
end
function Remote:invokeServer(...)
local remoteType = "RemoteFunction"
local remoteInstance = self:_getRemoteInstance(remoteType)
local args = table.pack(...)
return Promise.defer(function(resolve, reject)
if not remoteInstance then
local waitForRemoteInstance = self._maid:give(Signal.new())
self:_continueWhenRemoteInstanceLoaded(remoteType, function(newRemoteInstance)
runService.Heartbeat:Wait()
waitForRemoteInstance:Fire(newRemoteInstance)
end)
remoteInstance = waitForRemoteInstance:Wait()
waitForRemoteInstance:Destroy()
end
local results = table.pack(pcall(remoteInstance.InvokeServer, remoteInstance, table.unpack(args)))
local success = table.remove(results, 1)
if success then
resolve(table.unpack(results))
else
reject(table.unpack(results))
end
end)
end
function Remote:destroy()
remotes[self.name] = nil
self._maid:clean()
end
Remote.Destroy = Remote.destroy
return Remote |
ShowMouseCursor(true) -- keep this around so it's reset properly
LockMouseCursor(false) -- keep this around so it's reset properly
--disable_anchor()
--pause_on_nofocus = true
menu.ok_text:SetPoint("CENTER", UIParent, "CENTER", 0, 70)
menu.ok_text:SetText("Start")
menu.exit_text:SetPoint("CENTER", UIParent, "CENTER", 0, 250)
|
-- Titanium recipe & tech changes
--
local util = require("__bztitanium__.data-util");
if (not mods["bobplates"] and not mods["angelssmelting"]) then
util.replace_ingredient("power-armor", "steel", "titanium")
util.add_prerequisite("power-armor", util.titanium_processing)
-- All equipment that uses steel now uses titanium. Who wants to carry around steel!
for name, recipe in pairs(data.raw.recipe) do
if recipe.result ~= nil and recipe.result:find("equipment") then
util.steel_to_titanium(recipe)
end
end
end
-- Generally, steel-based equipment techs require solar panel tech, so only require
-- titanium processing for that.
util.add_prerequisite("solar-panel-equipment", util.titanium_processing)
-- Also add titanium to some nuclear steam-handling stuff
util.add_titanium_ingredient(20, "steam-turbine")
if not mods["pyrawores"] then
util.add_titanium_ingredient(20, "heat-exchanger")
util.add_prerequisite("nuclear-power", util.titanium_processing)
end
-- Krastorio 2 changes
if mods["Krastorio2"] then
util.add_prerequisite("kr-electric-mining-drill-mk2", util.titanium_processing)
util.add_prerequisite("kr-quarry-minerals-extraction", util.titanium_processing)
end
if mods["Aircraft"] then
util.add_prerequisite("advanced-aerodynamics", util.titanium_processing)
end
|
local function getCounter (class, id)
if not id then
SU.deprecated("class.getCounter", "class:getCounter", "0.13.0", "0.14.0")
class, id = SILE.documentState.documentClass, class
end
if not SILE.scratch.counters[id] then
SILE.scratch.counters[id] = { value = 0, display = "arabic", format = class.formatCounter }
end
return SILE.scratch.counters[id]
end
local function getMultilevelCounter (class, id)
if not id then
SU.deprecated("class.getMultilevelCounter", "class:getMultilevelCounter", "0.13.0", "0.14.0")
class, id = SILE.documentState.documentClass, class
end
local counter = SILE.scratch.counters[id]
if not counter then
counter = { value= { 0 }, display= { "arabic" }, format = class.formatMultilevelCounter }
SILE.scratch.counters[id] = counter
end
return counter
end
local function formatCounter (_, counter)
return SU.formatNumber(counter.value, counter.display)
end
local function formatMultilevelCounter (_, counter, options)
local maxlevel = options and options.level or #counter.value
local minlevel = options and options.minlevel or 1
local out = {}
for x = minlevel, maxlevel do
out[x - minlevel + 1] = formatCounter(nil, { display = counter.display[x], value = counter.value[x] })
end
return table.concat(out, ".")
end
SILE.formatCounter = function (counter)
SU.deprecated("SILE.formatCounter", "class:formatCounter", "0.13.0", "0.14.0")
return formatCounter(nil, counter)
end
SILE.formatMultilevelCounter = function (counter, options)
SU.deprecated("SILE.formatMultilevelCounter", "class:formatMultilevelCounter", "0.13.0", "0.14.0")
return formatMultilevelCounter(nil, counter, options)
end
local function init (_, _)
if not SILE.scratch.counters then
SILE.scratch.counters = {}
end
end
local function registerCommands (class)
SILE.registerCommand("increment-counter", function (options, _)
local counter = class:getCounter(options.id)
if (options["set-to"]) then
counter.value = tonumber(options["set-to"])
else
counter.value = counter.value + 1
end
if options.display then counter.display = options.display end
end, "Increments the counter named by the <id> option")
SILE.registerCommand("set-counter", function (options, _)
local counter = class:getCounter(options.id)
if options.value then counter.value = tonumber(options.value) end
if options.display then counter.display = options.display end
end, "Sets the counter named by the <id> option to <value>; sets its display type (roman/Roman/arabic) to type <display>.")
SILE.registerCommand("show-counter", function (options, _)
local counter = class:getCounter(options.id)
if options.display then counter.display = options.display end
SILE.typesetter:setpar(class:formatCounter(counter))
end, "Outputs the value of counter <id>, optionally displaying it with the <display> format.")
SILE.registerCommand("increment-multilevel-counter", function (options, _)
local counter = class:getMultilevelCounter(options.id)
local currentLevel = #counter.value
local level = tonumber(options.level) or currentLevel
if level == currentLevel then
counter.value[level] = counter.value[level] + 1
elseif level > currentLevel then
while level > currentLevel do
currentLevel = currentLevel + 1
counter.value[currentLevel] = (options.reset == false) and counter.value[currentLevel -1 ] or 1
counter.display[currentLevel] = counter.display[currentLevel - 1]
end
else -- level < currentLevel
counter.value[level] = counter.value[level] + 1
while currentLevel > level do
if not (options.reset == false) then counter.value[currentLevel] = nil end
counter.display[currentLevel] = nil
currentLevel = currentLevel - 1
end
end
if options.display then counter.display[currentLevel] = options.display end
end)
SILE.registerCommand("show-multilevel-counter", function (options, _)
local counter = class:getMultilevelCounter(options.id)
if options.display then counter.display[#counter.value] = options.display end
SILE.typesetter:typeset(class:formatMultilevelCounter(counter, options))
end, "Outputs the value of the multilevel counter <id>, optionally displaying it with the <display> format.")
end
return {
init = init,
registerCommands = registerCommands,
exports = {
formatCounter = formatCounter,
formatMultilevelCounter = formatMultilevelCounter,
getCounter = getCounter,
getMultilevelCounter = getMultilevelCounter
},
documentation = [[\begin{document}
Various parts of SILE such as the \autodoc:package{footnotes} package and the
sectioning commands keep a counter of things going on: the current
footnote number, the chapter number, and so on. The counters package
allows you to set up, increment and typeset named counters. It
provides the following commands:
\begin{itemize}
\item{\autodoc:command{\set-counter[id=<counter-name>, value=<value>]} — sets
the counter with the specified name to the given value.}
\item{\autodoc:command{\increment-counter[id=<counter-name>]} — does the
same as \autodoc:command{\set-counter} except that when no \autodoc:parameter{value}
parameter is given, the counter is incremented by one.}
\item{\autodoc:command{\show-counter[id=<counter-name>]} — this typesets the
value of the counter according to the counter’s declared display type.}
\end{itemize}
All of the commands in the counters package take an optional
\autodoc:parameter{display=<display-type>} parameter to set the \em{display type}
of the counter.
The available built-in display types are:
\begin{itemize}
\item{\code{arabic}, the default;}
\item{\code{alpha}, for lower-case alphabetic counting;}
\item{\code{Alpha}, for upper-case alphabetic counting;}
\item{\code{roman}, for lower-case Roman numerals; and,}
\item{\code{Roman} for upper-case Roman numerals.}
\end{itemize}
The ICU library also provides ways of formatting numbers in global (non-Latin)
scripts. You can use any of the display types in this list:
\url{http://www.unicode.org/repos/cldr/tags/latest/common/bcp47/number.xml}.
For example, \autodoc:parameter{display=beng} will format your numbers in Bengali digits.
So, for example, the following SILE code:
\begin{verbatim}
\line
\\set-counter[id=mycounter, value=2]
\\show-counter[id=mycounter]
\\increment-counter[id=mycounter]
\\show-counter[id=mycounter, display=roman]
\line
\end{verbatim}
produces:
\line
\examplefont{2
\noindent{}iii}
\line
\end{document}]] }
|
warren_altered_atst = Creature:new {
objectName = "@mob/creature_names:warren_agro_droid_atst",
socialGroup = "warren_imperial",
faction = "",
level = 46,
chanceHit = 0.36,
damageMin = 400,
damageMax = 600,
baseXp = 4000,
baseHAM = 12000,
baseHAMmax = 15000,
armor = 0,
resists = {30,30,40,40,-1,40,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE + AGGRESSIVE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/atst.iff"},
lootGroups = {},
conversationTemplate = "",
defaultAttack = "defaultdroidattack",
defaultWeapon = "object/weapon/ranged/vehicle/vehicle_atst_ranged.iff"
}
CreatureTemplates:addCreatureTemplate(warren_altered_atst, "warren_altered_atst")
|
local t = {}
for i = 1, 200000 do
t[i] = tostring(i)
end
local numStr = table.concat(t)
local d1 = tonumber(string.sub(numStr, 1, 1))
local d10 = tonumber(string.sub(numStr, 10, 10))
local d100 = tonumber(string.sub(numStr, 100, 100))
local d1000 = tonumber(string.sub(numStr, 1000, 1000))
local d10000 = tonumber(string.sub(numStr, 10000, 10000))
local d100000 = tonumber(string.sub(numStr, 100000, 100000))
local d1000000 = tonumber(string.sub(numStr, 1000000, 1000000))
print(d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000) |
local s
describe("Tests to make sure the say library is functional", function()
setup(function()
package.loaded['say'] = false -- busted uses it, must force to reload
s = require('init') -- devcode is in /src/init.lua not in /src/say/init.lua
end)
it("tests the set function metamethod", function()
s:set('herp', 'derp')
assert(s._registry.en.herp == 'derp')
end)
it("tests the __call metamethod", function()
s:set('herp', 'derp')
assert(s('herp') == 'derp')
s:set('herp', '%s')
assert(s('herp', {'test'}) == 'test')
s:set('herp', '%s%s')
assert(s('herp', {'test', 'test'}) == 'testtest')
end)
it("tests the substitution of variable types; boolean, number, string and table", function()
s:set('substitute_test', 'boolean = %s, number = %s, string = "%s", table = %s')
local atable = {}
assert(s('substitute_test', {true, 100, 'some text', atable}) == 'boolean = true, number = 100, string = "some text", table = ' .. tostring(atable))
end)
it("tests the substitution of variable types; nil", function()
s:set('substitute_test', 'boolean = %s, nil = %s, number = %s, string = "%s", table = %s')
local atable = {}
assert(s('substitute_test', {true, nil, 100, 'some text', atable, n = 5}) == 'boolean = true, nil = nil, number = 100, string = "some text", table = ' .. tostring(atable))
end)
it("tests the set_fallback method", function()
s:set_namespace('en')
s:set('herp', 'derp')
s:set_namespace('not-en')
s:set('not-herp', 'not-derp')
assert(s('not-herp') == 'not-derp')
assert(s('herp') == 'derp')
end)
it("errors on bad type of param table", function()
s:set_namespace('en')
s:set('herp', 'derp %s')
assert.has.error(function() s('herp', 1000) end, "expected parameter table to be a table, got 'number'")
end)
it("tests missing elements returns nil", function()
assert(s('this does not exist') == nil)
end)
end)
|
return {'dpi'} |
local NET = {}
function NET.packages()
require 'cudnn'
require 'utils/mathfuncs'
require 'utils/utilfuncs'
end
function NET.createModel(opt)
NET.packages()
local Convolution = cudnn.SpatialConvolution
local UpConvolution = cudnn.SpatialFullConvolution
local ReLU = nn.ReLU
local SBatchNorm = nn.SpatialBatchNormalization
local Max = nn.SpatialMaxPooling
-- building block
local function ConvBlock(mod, nIP, nOP)
mod:add(Convolution(nIP, nOP, 3,3, 1,1, 1,1))
mod:add(SBatchNorm(nOP, 1e-3))
mod:add(ReLU(true))
end
local function UpConvBlock(mod, nIP, nOP)
mod:add(UpConvolution(nIP, nOP, 2,2, 2,2, 0,0))
mod:add(SBatchNorm(nOP, 1e-3))
mod:add(ReLU(true))
end
local blocks = {64,128,256,512}
local nIP = 1
local function Unet(depth)
local unetIP = nIP
local unetOP = blocks[depth]
local model = nn.Sequential()
if depth == #blocks then
-- conv and upconv
ConvBlock(model, unetIP, unetOP)
UpConvBlock(model, unetOP, unetIP)
else
ConvBlock(model, unetIP, unetOP)
nIP = unetOP
-- concat with sub unet
local shortcut_subnet = nn.ConcatTable()
local subnet, subnetOP = Unet(depth+1)
local shortcut = nn.Identity()
local pool_subnet = nn.Sequential()
:add(Max(2,2,2,2,0,0))
:add(subnet)
shortcut_subnet:add(shortcut)
shortcut_subnet:add(pool_subnet)
model:add(shortcut_subnet)
model:add(nn.JoinTable(2))
-- conv and upconv
ConvBlock(model, unetOP+subnetOP, unetOP)
if depth > 1 then
UpConvBlock(model, unetOP, unetIP)
else
local nOP = opt.dataset == 'mnist-seg' and 10 or 1
model:add(Convolution(unetOP, nOP, 1,1, 1,1, 0,0))
model:add(SBatchNorm(nOP, 1e-3))
end
end
return model, unetIP
end
local unet = Unet(1)
unet:add(nn.Sigmoid())
-- initialization from MSR
local function MSRinit(net)
local function init(name)
for k,v in pairs(net:findModules(name)) do
local n = v.kW*v.kH*v.nOutputPlane
v.weight:normal(0,math.sqrt(2/n))
v.bias:zero()
end
end
-- have to do for both backends
init('nn.SpatialConvolution')
init('cudnn.SpatialConvolution')
end
MSRinit(unet)
return unet
end
function NET.createCriterion()
local criterion = nn.MultiCriterion()
criterion:add(nn.BCECriterion())
return criterion
end
function NET.trainOutputInit()
local info = {}
-- utilfuncs.newInfoEntry is defined in utils/train_eval_test_func.lua
info[#info+1] = utilfuncs.newInfoEntry('loss',0,0)
return info
end
function NET.trainOutput(info, outputs, labelsCPU, err, iterSize)
local batch_size = outputs:size(1)
info[1].value = err * iterSize
info[1].N = batch_size
end
function NET.testOutputInit()
local info = {}
info[#info+1] = utilfuncs.newInfoEntry('loss',0,0)
return info
end
function NET.testOutput(info, outputs, labelsCPU, err)
local batch_size = outputs:size(1)
info[1].value = err * OPT.iterSize
info[1].N = batch_size
end
function NET.trainRule(currentEpoch, opt)
-- exponentially decay
local delta = 3
local start = 1 -- LR: 10^-(star) ~ 10^-(start + delta)
local ExpectedTotalEpoch = opt.nEpochs
return {LR= 10^-((currentEpoch-1)*delta/(ExpectedTotalEpoch-1)+start),
WD= 5e-4}
end
function NET.arguments(cmd)
end
return NET
|
#!/usr/bin/env tarantool
local table_clear = require('table.clear')
box.cfg{
log = "tarantool.log"
}
local trigger = require('internal.trigger')
local test = require('tap').test('trigger')
test:plan(3)
local trigger_list = trigger.new("sweet trigger")
test:ok(trigger_list ~= nil, "test that trigger list is created")
test:test("simple trigger test", function(test)
test:plan(10)
local cnt = 0
local function trigger_cnt() cnt = cnt + 1 end
-- Append first trigger
trigger_list(trigger_cnt)
trigger_list:run()
test:is(cnt, 1, "check first run")
-- Append second trigger
trigger_list(trigger_cnt)
trigger_list:run()
test:is(cnt, 3, "check first run")
-- Check listing
local list_copy = trigger_list()
test:is(#list_copy, 2, "trigger() count")
table.remove(list_copy)
test:is(#trigger_list(), 2, "check that we've returned copy")
-- Delete both triggers
test:is(trigger_list(nil, trigger_cnt), trigger_cnt, "pop trigger")
trigger_list:run()
test:is(#trigger_list(), 1, "check trigger count after delete")
test:is(cnt, 4, "check third run")
test:is(trigger_list(nil, trigger_cnt), trigger_cnt, "pop trigger")
trigger_list:run()
test:is(#trigger_list(), 0, "check trigger count after delete")
-- Check that we've failed to delete trigger
local stat, err = pcall(getmetatable(trigger_list).__call, trigger_list,
nil, trigger_cnt)
test:ok(string.find(err, "is not found"), "check error")
end)
test:test("errored trigger test", function(test)
test:plan(6)
--
-- Check that trigger:run() fails on the first error
--
local cnt = 0
local function trigger_cnt() cnt = cnt + 1 end
local function trigger_errored() error("test error") end
test:is(#trigger_list(), 0, "check for empty triggers")
-- Append first trigger
trigger_list(trigger_cnt)
trigger_list:run()
test:is(cnt, 1, "check simple trigger")
-- Append errored trigger
trigger_list(trigger_errored)
local status = pcall(function() trigger_list:run() end)
test:is(cnt, 2, "check simple+error trigger")
-- Flush triggers
table_clear(trigger_list)
test:is(#trigger_list(), 0, "successfull flush")
-- Append first trigger
trigger_list(trigger_errored)
local status = pcall(function() trigger_list:run() end)
test:is(cnt, 2, "check error trigger")
-- Append errored trigger
trigger_list(trigger_cnt)
local status = pcall(function() trigger_list:run() end)
test:is(cnt, 2, "check error+simple trigger")
end)
os.exit(test:check() == true and 0 or -1)
|
-- Copyright (C) 2018-2021 by KittenOS NEO contributors
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-- THIS SOFTWARE.
-- app-taskmgr: Task manager
-- a-hello : simple test program for Everest.
local everest = neo.requireAccess("x.neo.pub.window", "main window")
local kill = neo.requestAccess("k.kill")
local sW, sH = 20, 8
local headlines = 2
local window = everest(sW, sH)
local lastIdleTimeTime = os.uptime()
local lastIdleTime = neo.totalIdleTime()
local cpuPercent = 100
local lastCPUTimeRecord = {}
local cpuCause = "(none)"
local camY = 1
-- elements have {pid, text}
local consistentProcList = {}
local function drawLine(n)
local red = false
local idx = (camY + n) - (headlines + 1)
local stat = ("~"):rep(sW)
if n == 1 then
-- x.everest redraw. Since this window only has one line...
local usage = math.floor((os.totalMemory() - os.freeMemory()) / 1024)
stat = usage .. "/" .. math.floor(os.totalMemory() / 1024) .. "K, CPU " .. cpuPercent .. "%"
red = true
elseif n == 2 then
stat = "MAX:" .. cpuCause
red = true
elseif consistentProcList[idx] then
if idx == camY then
stat = ">" .. consistentProcList[idx][2]
else
stat = " " .. consistentProcList[idx][2]
end
end
stat = unicode.safeTextFormat(stat)
while unicode.len(stat) < sW do stat = stat .. " " end
if red then
window.span(1, n, unicode.sub(stat, 1, sW), 0xFFFFFF, 0)
else
window.span(1, n, unicode.sub(stat, 1, sW), 0x000000, 0xFFFFFF)
end
end
local function updateConsistentProcList(pt, lp)
local tbl = {}
local tbl2 = {}
local tbl3 = {}
for _, v in ipairs(pt) do
table.insert(tbl, v[1])
tbl2[v[1]] = v[2] .. "/" .. v[1] .. " " .. tostring(lp[v[1]]) .. "%"
end
table.sort(tbl)
for k, v in ipairs(tbl) do
tbl3[k] = {v, tbl2[v]}
end
consistentProcList = tbl3
end
local p = os.uptime()
neo.scheduleTimer(p)
local ctrl = false
while true do
local n = {coroutine.yield()}
if n[1] == "x.neo.pub.window" then
if n[3] == "line" then
drawLine(n[4])
end
if n[3] == "close" then
return
end
if n[3] == "key" then
if n[5] == 29 then
ctrl = n[6]
elseif n[6] then
if ctrl then
if n[5] == 200 then
sH = math.max(headlines + 1, sH - 1)
window.setSize(sW, sH)
elseif n[5] == 208 then
sH = sH + 1
window.setSize(sW, sH)
elseif n[5] == 203 then
sW = math.max(20, sW - 1)
window.setSize(sW, sH)
elseif n[5] == 205 then
sW = sW + 1
window.setSize(sW, sH)
end
else
if n[4] == 8 or n[5] == 211 then
if consistentProcList[camY] then
kill(consistentProcList[camY][1])
end
end
if n[5] == 200 then
camY = camY - 1
if camY < 1 then camY = 1 end
for i = (headlines + 1), sH do drawLine(i) end
end
if n[5] == 208 then
camY = camY + 1
for i = (headlines + 1), sH do drawLine(i) end
end
end
end
end
end
if n[1] == "k.timer" then
local now = os.uptime()
local nowIT = neo.totalIdleTime()
local tD = now - lastIdleTimeTime
local iD = nowIT - lastIdleTime
cpuPercent = math.ceil(((tD - iD) / tD) * 100)
lastIdleTimeTime = now
lastIdleTime = nowIT
local newRecord = {}
cpuCause = "(none)"
local causeUsage = 0
local pt = neo.listProcs()
local localPercent = {}
for _, v in ipairs(pt) do
-- pkg, pid, cpuTime
local baseline = 0
if lastCPUTimeRecord[v[1]] then
baseline = lastCPUTimeRecord[v[1]]
end
local val = v[3] - baseline
localPercent[v[1]] = math.ceil(100 * (val / tD))
if causeUsage < val then
cpuCause = v[2] .. "/" .. v[1]
causeUsage = val
end
newRecord[v[1]] = v[3]
end
lastCPUTimeRecord = newRecord
updateConsistentProcList(pt, localPercent)
for i = 1, sH do drawLine(i) end
p = p + 1
neo.scheduleTimer(p)
end
end
|
if not init then
init = true
powerlevel = 5
smeltlevel = 23
xmat1 = 'basic_machines:gold_dust_66'
xmat2 ='basic_machines:gold_dust_33'
xmat3 = 'default:gold_ingot'
xmat3c = 'default:gold_ingot 10'
xmat4 = 'default:goldblock'
xoffset = 18
mat1 = 'basic_machines:mese_dust_66'
mat2 ='basic_machines:mese_dust_33'
mat3 = 'default:mese_crystal'
mat3c = 'default:mese_crystal 10'
mat4 = 'default:mese'
offset = -1
xmat1 = 'basic_machines:diamond_dust_66'
xmat2 ='basic_machines:diamond_dust_33'
xmat3 = 'default:diamond'
xmat3c = 'default:diamond 10'
xmat4 = 'default:diamondblock'
xoffset = 18
else
self.label(machine.energy())
if machine.energy() < 20 then
machine.generate_power('default:tree',powerlevel)
else
if check_inventory.self(mat1,'main') then
machine.smelt(mat1,smeltlevel)
else
if check_inventory.self(mat2,'main') then
machine.smelt(mat2,smeltlevel)
else
if check_inventory.self(mat3c,'main') then
if offset > 0 then
craft(mat4,offset)
else
craft(mat4)
end
end
if check_inventory.self(mat3,'main') then
machine.grind(mat3)
end
end
end
end
end |
-----------------------------------
--
-- tpz.effect.PROWESS
-- From GoV
-----------------------------------
function onEffectGain(target,effect)
target:addMod(tpz.mod.GOV_CLEARS, effect:getPower())
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
target:delMod(tpz.mod.GOV_CLEARS, effect:getPower())
end |
local vernam = require("vernam")
local secretKey = "iloveluaaa"
local text = "samelength"
local encrypted = vernam.encrypt(text, secretKey)
local decrypted = vernam.decrypt(encrypted, secretKey)
print("Original Text: " .. text)
print("Encrypted Text: " .. encrypted)
print("Decrypted Text: " .. decrypted)
assert(text == decrypted)
print("Tests Passed") |
button = workspace.Button
button.CanCollide = false
button.Transparency = 1
game:GetService("RunService").Heartbeat:connect(function(step)
button.CFrame = CFrame.new(game.Players.LocalPlayer.Character.Head.Position)
button.Size = Vector3.new(math.random(0,0), math.random(0,0), math.random(1,5))
wait()
button.CFrame=CFrame.new(game.Players.LocalPlayer.Character["Right Arm"].Position)
button.Size=Vector3.new(math.random(0,0), math.random(0,0), math.random(0,0))
wait()
button.CFrame=CFrame.new(game.Players.LocalPlayer.Character.Torso.Position)
button.Size=Vector3.new(math.random(0,0), math.random(0,0), math.random(0,0))
wait()
button.CFrame=CFrame.new(game.Players.LocalPlayer.Character["Left Arm"].Position)
button.Size=Vector3.new(math.random(0,0), math.random(0,0), math.random(0,0))
wait()
button.Size=Vector3.new(math.random(0,0), math.random(0,0), math.random(0,0))
button.CFrame=CFrame.new(game.Players.LocalPlayer.Character["Left Leg"].Position)
wait()
button.Size = Vector3.new(math.random(0,0), math.random(0,0), math.random(0,0))
button.CFrame = CFrame.new(game.Players.LocalPlayer.Character["Right Leg"].Position)
end) |
object_draft_schematic_armor_component_test_an_armor_layer = object_draft_schematic_armor_component_shared_test_an_armor_layer:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_armor_component_test_an_armor_layer, "object/draft_schematic/armor/component/test_an_armor_layer.iff")
|
--[[ List of Functions
getData(table,dirLocation,filename,tokenCheck) -- Used for getting data from text files and splitting into chunks
makeTable(array,pos,fill) -- A shortcut function for making a table out of an array
makeBaseTable() -- Base information used in all systems
makeWrapperTemplateTable() -- Wrapper Templates
makeCivilzationTable() -- Civilzation System
makeClassTable(spellcheck) -- Class System
makeFeatTable() -- Class System | Feat SubSystem
makeSpellTable() -- Class System | Spell SubSystem
makeEnhancedBuildingTable() -- Enhanced System
makeEnhancedCreatureTable() -- Enhanced System
makeEnhancedItemTable() -- Enhanced System
makeEnhancedMaterialTable()
makeEnhancedReactionTable()
makeEventTable() -- Event System
makeDiplomacyTable() -- Civilization System | Diplomacy SubSystem
makeEntityTable(entity) -- Make a persistent table for the declared entity
makeGlobalTable() -- Make a global persistent table used in all systems
makeItemTable(item) -- Make a persistent table for the declared item
makeUnitTable(unit) -- Make a persistent table for the declared unit
makeUnitTableSecondary(unit,secondary) -- Add a secondary (attribute/skill/etc) table for the declared unit
makeUnitTableClass(unit,class) -- Add a class table for the declared unit
makeUnitTableSpell(unit,spell) -- Add a spell table for the declared unit
makeUnitTableSide(unit) -- Add a table tracking allegiance information for the declared unit
makeUnitTableSummon(unit) -- Add a table tracking summoning information for the declared unit
makeUnitTableTransform(unit) -- Add a table tracking transformation information for the declared unit
]]
---------------------------------------------------------------------------------------------
-------- Functions that are shared between multiple other functions in this file ------------
---------------------------------------------------------------------------------------------
function getData(table,dirLocation,filename,tokenCheck,test,verbose)
local utils = require 'utils'
local split = utils.split_string
if verbose then print('Searching for an '..table..' file') end
local files = {}
local dir = dfhack.getDFPath()
local locations = {'/raw/objects/',dirLocation..'/','/raw/scripts/'}
local n = 1
if test then filename = filename..'_test' end
for _,location in ipairs(locations) do
local path = dir..location
if verbose then print('Looking in '..location) end
if dfhack.internal.getDir(path) then
for _,fname in pairs(dfhack.internal.getDir(path)) do
if (split(fname,'_')[1] == filename or fname == filename..'.txt') and string.match(fname,'txt') then
files[n] = path..fname
n = n + 1
end
end
end
end
if #files >= 1 then
if verbose then
print(table..' files found:')
printall(files)
end
else
if verbose then print('No '..table..' files found') end
return false
end
local data = {}
local dataInfo = {}
for _,file in ipairs(files) do
data[file] = {}
local iofile = io.open(file,"r")
local lineCount = 1
while true do
local line = iofile:read("*line")
if line == nil then break end
data[file][lineCount] = line
lineCount = lineCount + 1
end
iofile:close()
dataInfo[file] = {}
local count = 1
for i,line in ipairs(data[file]) do
if split(line,':')[1] == tokenCheck then
if #split(line,':') == 3 then
dataInfo[file][count] = {split(line,':')[2]..':'..split(split(line,':')[3],']')[1],i,0}
else
dataInfo[file][count] = {split(split(line,':')[2],']')[1],i,0}
end
count = count + 1
end
end
end
return data, dataInfo, files
end
function makeTable(array,pos,fill)
local temp = {}
local temptable = {select(pos,table.unpack(array))}
local strint = '1'
for _,v in pairs(temptable) do
temp[strint] = v
strint = tostring(strint+1)
end
if fill then
if tonumber(strint)-1 < tonumber(fill)+1 then
while tonumber(strint)-1 < tonumber(fill)+1 do
temp[strint] = temp[tostring(strint-1)]
strint = tostring(strint+1)
end
end
end
return temp
end
---------------------------------------------------------------------------------------------
-------- Functions for making persistent tables from text files (used in Systems) -----------
---------------------------------------------------------------------------------------------
function makeBaseTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.BaseTable = {}
print('Searching for an included base file')
local files = {}
local dir = dfhack.getDFPath()
local locations = {'/raw/objects/','/raw/systems/','/raw/scripts/'}
local n = 1
local filename = 'base.txt'
if test then filename = 'base_test.txt' end
for _,location in ipairs(locations) do
local path = dir..location
if verbose then print('Looking in '..location) end
if dfhack.internal.getDir(path) then
for _,fname in pairs(dfhack.internal.getDir(path)) do
if (fname == filename) then
files[n] = path..fname
n = n + 1
end
end
end
end
base = persistTable.GlobalTable.roses.BaseTable
base.ExperienceRadius = '-1'
base.FeatGains = '100:25'
base.CustomAttributes = {}
base.CustomSkills = {}
base.CustomResistances = {}
base.CustomStats = {}
base.Types = {}
base.Spheres = {}
base.Schools = {}
base.Disciplines = {}
base.SubDisciplines = {}
base.Equations = {}
if #files < 1 then
print('No Base file found, assuming defaults')
base.Types = {}
base.Types['1'] = 'MAGICAL'
base.Types['2'] = 'PHYSICAL'
else
if verbose then printall(files) end
for _,file in ipairs(files) do
local data = {}
local iofile = io.open(file,"r")
local lineCount = 1
while true do
local line = iofile:read("*line")
if line == nil then break end
data[lineCount] = line
lineCount = lineCount + 1
end
iofile:close()
for i,line in pairs(data) do
test = line:gsub("%s+","")
test = split(test,':')[1]
array = split(line,':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[EXPERIENCE_RADIUS' then
base.ExperienceRadius = array[2]
elseif test == '[FEAT_GAINS' then
base.FeatGains = array[2]..':'..array[3]
elseif test == '[SKILL' then
base.CustomSkills[#base.CustomSkills+1] = array[3]
elseif test == '[ATTRIBUTE' then
base.CustomAttributes[#base.CustomAttributes+1] = array[2]
elseif test == '[RESISTANCE' then
base.CustomResistances[#base.CustomResistances+1] = array[2]
elseif test == '[STAT' then
base.CustomStats[#base.CustomStats+1] = array[2]
elseif test == '[TYPE' then
for arg = 2,#array,1 do
base.Types[#base.Types+1] = array[arg]
end
elseif test == '[SPHERE' then
for arg = 2,#array,1 do
base.Spheres[#base.Spheres+1] = array[arg]
end
elseif test == '[SCHOOL' then
for arg = 2,#array,1 do
base.Schools[#base.Schools+1] = array[arg]
end
elseif test == '[DISCIPLINE' then
for arg = 2,#array,1 do
base.Disciplines[#base.Disciplines+1] = array[arg]
end
elseif test == '[SUBDISCIPLINE' then
for arg = 2,#array,1 do
base.SubDisciplines[#base.SubDisciplines+1] = array[arg]
end
elseif test == '[EQUATION' then
base.Equations[array[2]] = array[3]
end
end
end
end
for _,n in pairs(base.CustomResistances._children) do
resistance = base.CustomResistances[n]
base.CustomStats[#base.CustomStats+1] = resistance..'_SKILL_PENETRATION'
end
for _,TSSDS in pairs({'Types','Spheres','Schools','Disciplines','SubDisciplines'}) do
for _,n in pairs(base[TSSDS]._children) do
temp = base[TSSDS][n]
if TSSDS == 'Schools' then base.CustomSkills[#base.CustomSkills+1] = temp..'_SPELL_CASTING' end
base.CustomStats[#base.CustomStats+1] = temp..'_CRITICAL_CHANCE'
base.CustomStats[#base.CustomStats+1] = temp..'_CRITICAL_BONUS'
base.CustomStats[#base.CustomStats+1] = temp..'_CASTING_SPEED'
base.CustomStats[#base.CustomStats+1] = temp..'_ATTACK_SPEED'
base.CustomStats[#base.CustomStats+1] = temp..'_SKILL_PENETRATION'
base.CustomStats[#base.CustomStats+1] = temp..'_HIT_CHANCE'
base.CustomResistances[#base.CustomResistances+1] = temp
end
end
end
function makeWrapperTemplateTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.WrapperTemplateTable = {}
templates = persistTable.GlobalTable.roses.WrapperTemplateTable
dataFiles,dataInfoFiles,files = getData('Wrapper Template','/raw/systems/','templates','[TEMPLATE',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
templateToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
templates[templateToken] = {}
template = templates[templateToken]
template.Level = {}
template.Positions = {}
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
template.Name = array[2]
elseif test == '[INPUT' then
template.Input = array[2]
end
end
end
end
end
-- Start Civilization System Functions
function makeCivilizationTable(test,verbose)
function tchelper(first, rest)
return first:upper()..rest:lower()
end
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.CivilizationTable = {}
civilizations = persistTable.GlobalTable.roses.CivilizationTable
dataFiles,dataInfoFiles,files = getData('Civilization','/raw/systems/Civilizations','civilizations','[CIVILIZATION',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
civilizationToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
civilizations[civilizationToken] = {}
civilization = civilizations[civilizationToken]
civilization.Level = {}
civilization.Positions = {}
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
civilization.Name = array[2]
elseif test == '[LEVELS' then
civilization.Levels = array[2]
elseif test == '[LEVEL_METHOD' then
civilization.LevelMethod = array[2]
civilization.LevelPercent = array[3]
elseif test == '[LEVEL' then
level = array[2]
civilization.Level[level] = {}
civsLevel = civilization.Level[level]
civsLevel.Required = {}
elseif test == '[LEVEL_NAME' then
civsLevel.Name = array[2]
elseif test == '[LEVEL_REQUIREMENT' then
if array[2] == 'COUNTER_MAX' then
civsLevel.Required.CounterMax = civsLevel.Required.CounterMax or {}
civsLevel.Required.CounterMax[array[3]] = array[4]
elseif array[2] == 'COUNTER_MIN' then
civsLevel.Required.CounterMin = civsLevel.Required.CounterMin or {}
civsLevel.Required.CounterMin[array[3]] = array[4]
elseif array[2] == 'COUNTER_EQUAL' then
civsLevel.Required.CounterEqual = civsLevel.Required.CounterEqual or {}
civsLevel.Required.CounterEqual[array[3]] = array[4]
elseif array[2] == 'TIME' then
civsLevel.Required.Time = array[3]
elseif array[2] == 'POPULATION' then
civsLevel.Required.Population = array[3]
elseif array[2] == 'SEASON' then
civsLevel.Required.Season = array[3]
elseif array[2] == 'TREES_CUT' then
civsLevel.Required.TreeCut = array[3]
elseif array[2] == 'FORTRESS_RANK' then
civsLevel.Required.Rank = array[3]
elseif array[2] == 'PROGRESS_RANK' then
if array[3] == 'POPULATION' then civsLevel.Required.ProgressPopulation = array[4] end
if array[3] == 'TRADE' then civsLevel.Required.ProgressTrade = array[4] end
if array[3] == 'PRODUCTION' then civsLevel.Required.ProgressProduction = array[4] end
elseif array[2] == 'ARTIFACTS' then
civsLevel.Required.NumArtifacts = array[3]
elseif array[2] == 'TOTAL_DEATHS' then
civsLevel.Required.TotDeaths = array[3]
elseif array[2] == 'TOTAL_INSANITIES' then
civsLevel.Required.TotInsanities = array[3]
elseif array[2] == 'TOTAL_EXECUTIONS' then
civsLevel.Required.TotExecutions = array[3]
elseif array[2] == 'MIGRANT_WAVES' then
civsLevel.Required.MigrantWaves = array[3]
elseif array[2] == 'WEALTH' then
civsLevel.Required.Wealth = civsLevel.Required.Wealth or {}
civsLevel.Required.Wealth[array[3]] = array[4]
elseif array[2] == 'BUILDING' then
civsLevel.Required.Building = civsLevel.Required.Building or {}
civsLevel.Required.Building[array[3]] = array[4]
elseif array[2] == 'SKILL' then
civsLevel.Required.Skill = civsLevel.Required.Skill or {}
civsLevel.Required.Skill[array[3]] = array[4]
elseif array[2] == 'CLASS' then
civsLevel.Required.Class = civsLevel.Required.Class or {}
civsLevel.Required.Class[array[3]] = array[4]
elseif array[2] == 'ENTITY_KILLS' then
civsLevel.Required.EntityKills = civsLevel.Required.EntityKills or {}
civsLevel.Required.EntityKills[array[3]] = array[4]
elseif array[2] == 'CREATURE_KILLS' then
civsLevel.Required.CreatureKills = civsLevel.Required.CreatureKills or {}
civsLevel.Required.CreatureKills[array[3]] = civsLevel.Required.CreatureKills[array[3]] or {}
civsLevel.Required.CreatureKills[array[3]][array[4]] = array[5]
elseif array[2] == 'ENTITY_DEATHS' then
civsLevel.Required.EntityDeaths = civsLevel.Required.EntityDeaths or {}
civsLevel.Required.EntityDeaths[array[3]] = array[4]
elseif array[2] == 'CREATURE_DEATHS' then
civsLevel.Required.CreatureDeaths = civsLevel.Required.CreatureDeaths or {}
civsLevel.Required.CreatureDeaths[array[3]] = civsLevel.Required.CreatureDeaths[array[3]] or {}
civsLevel.Required.CreatureDeaths[array[3]][array[4]] = array[5]
elseif array[2] == 'TRADES' then
civsLevel.Required.Trades = civsLevel.Required.Trades or {}
civsLevel.Required.Trades[array[3]] = array[4]
elseif array[2] == 'SIEGES' then
civsLevel.Required.Sieges = civsLevel.Required.Sieges or {}
civsLevel.Required.Sieges[array[3]] = array[4]
elseif array[2] == 'DIPLOMACY' then
civsLevel.Required.Diplomacy = civsLevel.Required.Diplomacy or {}
civsLevel.Required.Diplomacy[array[3]..':'..array[4]..':'..array[5]..':'..array[6]] = '1'
end
elseif test == '[LEVEL_REMOVE' then
subType = array[3]:gsub("(%a)([%w_']*)", tchelper)
civsLevel.Remove = civsLevel.Remove or {}
if array[2] == 'CREATURE' then
civsLevel.Remove.Creature = civsLevel.Remove.Creature or {}
civsLevel.Remove.Creature[subType] = civsLevel.Remove.Creature[subType] or {}
civsLevel.Remove.Creature[subType][array[4]] = array[5]
elseif array[2] == 'INORGANIC' then
civsLevel.Remove.Inorganic = civsLevel.Remove.Inorganic or {}
civsLevel.Remove.Inorganic[subType] = civsLevel.Remove.Inorganic[subType] or {}
civsLevel.Remove.Inorganic[subType][array[4]] = array[4]
elseif array[2] == 'ORGANIC' then
civsLevel.Remove.Organic = civsLevel.Remove.Organic or {}
civsLevel.Remove.Organic[subType] = civsLevel.Remove.Organic[subType] or {}
civsLevel.Remove.Organic[subType][array[4]] = array[5]
elseif array[2] == 'REFUSE' then
civsLevel.Remove.Refuse = civsLevel.Remove.Refuse or {}
civsLevel.Remove.Refuse[subType] = civsLevel.Remove.Refuse[subType] or {}
civsLevel.Remove.Refuse[subType][array[4]] = array[5]
elseif array[2] == 'ITEM' then
civsLevel.Remove.Item = civsLevel.Remove.Item or {}
civsLevel.Remove.Item[subType] = civsLevel.Remove.Item[subType] or {}
civsLevel.Remove.Item[subType][array[4]] = array[4]
elseif array[2] == 'MISC' then
civsLevel.Remove.Misc = civsLevel.Remove.Misc or {}
civsLevel.Remove.Misc[subType] = civsLevel.Remove.Misc[subType] or {}
civsLevel.Remove.Misc[subType][array[4]] = array[5]
elseif array[2] == 'PRODUCT' then
civsLevel.Remove.Product = civsLevel.Remove.Product or {}
civsLevel.Remove.Product[subType] = civsLevel.Remove.Product[subType] or {}
civsLevel.Remove.Product[subType][array[4]] = array[5]
end
elseif test == '[LEVEL_ADD' then
subType = array[3]:gsub("(%a)([%w_']*)", tchelper)
civsLevel.Add = civsLevel.Add or {}
if array[2] == 'CREATURE' then
civsLevel.Add.Creature = civsLevel.Add.Creature or {}
civsLevel.Add.Creature[subType] = civsLevel.Add.Creature[subType] or {}
civsLevel.Add.Creature[subType][array[4]] = array[5]
elseif array[2] == 'INORGANIC' then
civsLevel.Add.Inorganic = civsLevel.Add.Inorganic or {}
civsLevel.Add.Inorganic[subType] = civsLevel.Add.Inorganic[subType] or {}
civsLevel.Add.Inorganic[subType][array[4]] = array[4]
elseif array[2] == 'ORGANIC' then
civsLevel.Add.Organic = civsLevel.Add.Organic or {}
civsLevel.Add.Organic[subType] = civsLevel.Add.Organic[subType] or {}
civsLevel.Add.Organic[subType][array[4]] = array[5]
elseif array[2] == 'REFUSE' then
civsLevel.Add.Refuse = civsLevel.Add.Refuse or {}
civsLevel.Add.Refuse[subType] = civsLevel.Add.Refuse[subType] or {}
civsLevel.Add.Refuse[subType][array[4]] = array[5]
elseif array[2] == 'ITEM' then
civsLevel.Add.Item = civsLevel.Add.Item or {}
civsLevel.Add.Item[subType] = civsLevel.Add.Item[subType] or {}
civsLevel.Add.Item[subType][array[4]] = array[4]
elseif array[2] == 'MISC' then
civsLevel.Add.Misc = civsLevel.Add.Misc or {}
civsLevel.Add.Misc[subType] = civsLevel.Add.Misc[subType] or {}
civsLevel.Add.Misc[subType][array[4]] = array[5]
elseif array[2] == 'PRODUCT' then
civsLevel.Add.Product = civsLevel.Add.Product or {}
civsLevel.Add.Product[subType] = civsLevel.Add.Product[subType] or {}
civsLevel.Add.Product[subType][array[4]] = array[5]
end
elseif testa== '[LEVEL_CHANGE_ETHICS' then
civsLevel.Ethics = civsLevel.Ethics or {}
civsLevel.Ethics[array[2]] = array[3]
elseif testa== '[LEVEL_CHANGE_VALUES' then
civsLevel.Values = civsLevel.Values or {}
civsLevel.Values[array[2]] = array[3]
elseif testa== '[LEVEL_CHANGE_SKILLS' then
civsLevel.Skills = civsLevel.Skills or {}
civsLevel.Skills[array[2]] = array[3]
elseif testa== '[LEVEL_CHANGE_CLASSES' then
civsLevel.Classes = civsLevel.Classes or {}
civsLevel.Classes[array[2]] = array[3]
elseif test == '[LEVEL_CHANGE_METHOD' then
civsLevel.LevelMethod = array[2]
civsLevel.LevelPercent = array[3]
elseif test == '[LEVEL_REMOVE_POSITION' then
civsLevel.RemovePosition = civsLevel.RemovePosition or {}
civsLevel.RemovePosition[array[2]] = array[2]
elseif test == '[LEVEL_ADD_POSITION' then
civsLevel.AddPosition = civsLevel.AddPosition or {}
position = array[2]
civsLevel.AddPosition[position] = position
civilization.Positions[position] = {}
civsAddPosition = civilization.Positions[position]
civsAddPosition.AllowedCreature = {}
civsAddPosition.AllowedClass = {}
civsAddPosition.RejectedCreature = {}
civsAddPosition.RejectedClass = {}
civsAddPosition.Responsibility = {}
civsAddPosition.AppointedBy = {}
civsAddPosition.Flags = {}
elseif test == '[ALLOWED_CREATURE' then
civsAddPosition.AllowedCreature[array[2]] = array[3]
elseif test == '[REJECTED_CREATURE' then
civsAddPosition.RejectedCreature[array[2]] = array[3]
elseif test == '[ALLOWED_CLASS' then
civsAddPosition.AllowedClass[array[2]] = array[2]
elseif test == '[REJECTED_CLASS' then
civsAddPosition.RejectedClass[array[2]] = array[2]
elseif test == '[NAME' then
civsAddPosition.Name = array[2]..':'..array[3]
elseif test == '[NAME_MALE' then
civsAddPosition.NameMale = array[2]..':'..array[3]
elseif test == '[NAME_FEMALE' then
civsAddPosition.NameFemale = array[2]..':'..array[3]
elseif test == '[SPOUSE' then
civsAddPosition.Spouse = array[2]..':'..array[3]
elseif test == '[SPOUSE_MALE' then
civsAddPosition.SpouseMale = array[2]..':'..array[3]
elseif test == '[SPOUSE_FEMALE' then
civsAddPosition.SpouseFemale = array[2]..':'..array[3]
elseif test == '[NUMBER' then
civsAddPosition.Number = array[2]
elseif test == '[SUCCESSION' then
civsAddPosition.Sucession = array[2]
elseif test == '[LAND_HOLDER' then
civsAddPosition.LandHolder = array[2]
elseif test == '[LAND_NAME' then
civsAddPosition.LandName = array[2]
elseif test == '[APPOINTED_BY' then
civsAddPosition.AppointedBy[array[2]] = array[2]
elseif test == '[REPLACED_BY' then
civsAddPosition.ReplacedBy = array[2]
elseif test == '[RESPONSIBILITY' then
civsAddPosition.Responsibility[array[2]] = array[2]
elseif test == '[PRECEDENCE' then
civsAddPosition.Precedence = array[2]
elseif test == '[REQUIRES_POPULATION' then
civsAddPosition.RequiresPopulation = array[2]
elseif test == '[REQUIRED_BOXES' then
civsAddPosition.RequiredBoxes = array[2]
elseif test == '[REQUIRED_CABINETS' then
civsAddPosition.RequiredCabinets = array[2]
elseif test == '[REQUIRED_RACKS' then
civsAddPosition.RequiredRacks = array[2]
elseif test == '[REQUIRED_STANDS' then
civsAddPosition.RequiredStands = array[2]
elseif test == '[REQUIRED_OFFICE' then
civsAddPosition.RequiredOffice = array[2]
elseif test == '[REQUIRED_BEDROOM' then
civsAddPosition.RequiredBedroom = array[2]
elseif test == '[REQUIRED_DINING' then
civsAddPosition.RequiredDining = array[2]
elseif test == '[REQUIRED_TOMB' then
civsAddPosition.RequiredTomb = array[2]
elseif test == '[MANDATE_MAX' then
civsAddPosition.MandateMax = array[2]
elseif test == '[DEMAND_MAX' then
civsAddPosition.DemandMax = array[2]
elseif test == '[COLOR' then
civsAddPosition.Color = array[2]..':'..array[3]..':'..array[4]
elseif test == '[SQUAD' then
civsAddPosition.Squad = array[2]..':'..array[3]..':'..array[4]
elseif test == '[COMMANDER' then
civsAddPosition.Commander = array[2]..':'..array[3]
elseif test == '[FLAGS' then
civsAddPosition.Flags[array[2]] = 'true'
else
-- if position then civsAddPosition[split(split(data[j],']')[1],'%[')[2]] = 'true' end
end
end
end
end
if not test then
for id,entity in pairs(df.global.world.entities.all) do
makeEntityTable(id)
end
end
return true
end
-- End Civilization System Functions
-- Start Class System Functions
function makeClassTable(spellCheck,test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.ClassTable = {}
classes = persistTable.GlobalTable.roses.ClassTable
if not spellCheck then
if verbose then print('No spell files found. Generating spell tables from class files') end
persistTable.GlobalTable.roses.SpellTable = {}
end
dataFiles,dataInfoFiles,files = getData('Class','/raw/systems/Classes','classes','[CLASS',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
classToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
classes[classToken] = {}
class = classes[classToken]
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
if test == '[NAME' then
class.Name = split(split(data[j],':')[2],']')[1]
elseif test == '[LEVELS' then
class.Levels = split(split(data[j],':')[2],']')[1]
end
if class.Name and class.Levels then break end
end
class.Spells = {}
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[AUTO_UPGRADE' then
class.AutoUpgrade = array[2]
elseif test == '[EXP' then
class.Experience = {}
local temptable = {select(2,table.unpack(array))}
strint = '1'
for _,v in pairs(temptable) do
class.Experience[strint] = v
strint = tostring(strint+1)
end
if tonumber(strint)-1 < tonumber(class.Levels) then
print('Incorrect amount of experience numbers, must be equal to number of levels. Assuming linear progression for next experience level')
while (tonumber(strint)-1) < tonumber(class.Levels) do
-- print('Incorrect amount of experience numbers, must be equal to number of levels. Assuming linear progression for next experience level')
class.Experience[strint] = tostring(2*tonumber(class.Experience[tostring(strint-1)])-tonumber(class.Experience[tostring(strint-2)]))
strint = tostring(tonumber(strint)+1)
end
end
elseif test == '[REQUIREMENT_CLASS' then
class.RequiredClass = class.RequiredClass or {}
class.RequiredClass[array[2]] = array[3]
elseif test == '[FORBIDDEN_CLASS' then
class.ForbiddenClass = class.ForbiddenClass or {}
class.ForbiddenClass[array[2]] = array[3]
elseif test == '[REQUIREMENT_SKILL' then
class.RequiredSkill = class.RequiredSkill or {}
class.RequiredSkill[array[2]] = array[3]
elseif test == '[REQUIREMENT_TRAIT' then
class.RequiredTrait = class.RequiredTrait or {}
class.RequiredTrait[array[2]] = array[3]
elseif test == '[REQUIREMENT_COUNTER' then
class.RequiredCounter = class.RequiredCounter or {}
class.RequiredCounter[array[2]] = array[3]
elseif test == '[REQUIREMENT_PHYS' or test == '[REQUIREMENT_MENT' or test == '[REQUIREMENT_ATTRIBUTE' then
class.RequiredAttribute = class.RequiredAttribute or {}
class.RequiredAttribute[array[2]] = array[3]
elseif test == '[REQUIREMENT_CREATURE' then
class.RequiredCreature = class.RequiredCreature or {}
class.RequiredCreature[array[2]] = array[3]
elseif test == '[LEVELING_BONUS' then
class.LevelBonus = class.LevelBonus or {}
if array[2] == 'PHYSICAL' or array[2] == 'MENTAL' or array[2] == 'ATTRIBUTE' then
class.LevelBonus.Attribute = class.LevelBonus.Attribute or {}
class.LevelBonus.Attribute[array[3]] = {}
tempTable = makeTable(array,4,class.Levels)
for x,y in pairs(tempTable) do
class.LevelBonus.Attribute[array[3]][tostring(x)] = y
end
elseif array[2] == 'SKILL' then
class.LevelBonus.Skill = class.LevelBonus.Skill or {}
class.LevelBonus.Skill[array[3]] = {}
tempTable = makeTable(array,4,class.Levels)
for x,y in pairs(tempTable) do
class.LevelBonus.Skill[array[3]][tostring(x)] = y
end
elseif array[2] == 'RESISTANCE' then
class.LevelBonus.Resistance = class.LevelBonus.Resistance or {}
class.LevelBonus.Resistance[array[3]] = {}
tempTable = makeTable(array,4,class.Levels)
for x,y in pairs(tempTable) do
class.LevelBonus.Resistance[array[3]][tostring(x)] = y
end
elseif array[2] == 'STAT' then
class.LevelBonus.Stat = class.LevelBonus.Stat or {}
class.LevelBonus.Stat[array[3]] = {}
tempTable = makeTable(array,4,class.Levels)
for x,y in pairs(tempTable) do
class.LevelBonus.Stat[array[3]][tostring(x)] = y
end
elseif array[2] == 'TRAIT' then
class.LevelBonus.Trait = class.LevelBonus.Trait or {}
class.LevelBonus.Trait[array[3]] = {}
tempTable = makeTable(array,4,class.Levels)
for x,y in pairs(tempTable) do
class.LevelBonus.Trait[array[3]][tostring(x)] = y
end
end
elseif test == '[BONUS_PHYS' or test == '[BONUS_MENT' or test == '[BONUS_ATTRIBUTE' then
class.BonusAttribute = class.BonusAttribute or {}
class.BonusAttribute[array[2]] = {}
tempTable = makeTable(array,3,class.Levels)
for x,y in pairs(tempTable) do
class.BonusAttribute[array[2]][tostring(x)] = y
end
elseif test == '[BONUS_TRAIT' then
class.BonusTrait = class.BonusTrait or {}
class.BonusTrait[array[2]] = {}
tempTable = makeTable(array,3,class.Levels)
for x,y in pairs(tempTable) do
class.BonusTrait[array[2]][tostring(x)] = y
end
elseif test == '[BONUS_SKILL' then
class.BonusSkill = class.BonusSkill or {}
class.BonusSkill[array[2]] = {}
tempTable = makeTable(array,3,class.Levels)
for x,y in pairs(tempTable) do
class.BonusSkill[array[2]][tostring(x)] = y
end
elseif test == '[BONUS_STAT' then
class.BonusStat = class.BonusStat or {}
class.BonusStat[array[2]] = {}
tempTable = makeTable(array,3,class.Levels)
for x,y in pairs(tempTable) do
class.BonusStat[array[2]][tostring(x)] = y
end
elseif test == '[BONUS_RESISTANCE' then
class.BonusResistance = class.BonusResistance or {}
class.BonusResistance[array[2]] = {}
tempTable = makeTable(array,3,class.Levels)
for x,y in pairs(tempTable) do
class.BonusResistance[array[2]][tostring(x)] = y
end
elseif test == '[SPELL' then
spell = array[2]
if not spellCheck then
persistTable.GlobalTable.roses.SpellTable[spell] = {}
spellTable = persistTable.GlobalTable.roses.SpellTable[spell]
spellTable.Cost = '0'
else
spellTable = {}
spellTable.Cost = '0'
end
class.Spells[spell] = {}
spells = class.Spells[spell]
spells.RequiredLevel = array[3]
if spells.RequiredLevel == 'AUTO' then
spells.RequiredLevel = '0'
spells.AutoLearn = 'true'
end
elseif test == '[SPELL_REQUIRE_PHYS' or test == '[SPELL_REQUIRE_MENT' or test == '[SPELL_REQUIRE_ATTRIBUTE' then
spellTable.RequiredAttribute = spellTable.RequiredAttribute or {}
spellTable.RequiredAttribute[array[2]] = array[3]
elseif test == '[SPELL_FORBIDDEN_SPELL' then
spellTable.ForbiddenSpell = spellTable.ForbiddenSpell or {}
spellTable.ForbiddenSpell[array[2]] = array[2]
elseif test == '[SPELL_FORBIDDEN_CLASS' then
spellTable.ForbiddenClass = spellTable.ForbiddenClass or {}
spellTable.ForbiddenClass[array[2]] = array[3]
elseif test == '[SPELL_UPGRADE' then
spellTable.Upgrade = array[2]
elseif test == '[SPELL_COST' then
spellTable.Cost = array[2]
elseif test == '[SPELL_EXP_GAIN' then
spellTable.ExperienceGain = array[2]
elseif test == '[SPELL_AUTO_LEARN]' then
spells.AutoLearn = 'true'
end
end
end
end
return true
end
function makeSpellTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.SpellTable = {}
spells = persistTable.GlobalTable.roses.SpellTable
dataFiles,dataInfoFiles,files = getData('Spell','/raw/systems/Classes','spells','[SPELL',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
spellToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
spells[spellToken] = {}
spell = spells[spellToken]
spell.Cost = '0'
spell.Script = {}
scriptNum = 0
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
spell.Name = array[2]
elseif test == '[DESCRIPTION' then
spell.Description = array[2]
elseif test == '[TYPE' then
spell.Type = array[2]
elseif test == '[SPHERE' then
spell.Sphere = array[2]
elseif test == '[SCHOOL' then
spell.School = array[2]
elseif test == '[DISCIPLINE' then
spell.Discipline = array[2]
elseif test == '[SUBDISCIPLINE' then
spell.SubDiscipline = array[2]
elseif test == '[LEVEL' then
spell.Level = array[2]
elseif test == '[EFFECT' then
spell.Effect = array[2]
elseif test == '[ANNOUNCEMENT' then
spell.Announcement = array[2]
elseif test == '[RESISTABLE]' then
spell.Resistable = 'true'
elseif test == '[CAN_CRIT]' then
spell.CanCrit = 'true'
elseif test == '[PENETRATE' then
spell.Penetration = array[2]
elseif test == '[HIT_MODIFIER' then
spell.HitModifier = array[2]
elseif test == '[HIT_MODIFIER_PERC' then
spell.HitModifierPerc = array[2]
elseif test == '[SOURCE_PRIMARY_ATTRIBUTES' then
spell.SourcePrimaryAttribute = {}
tempTable = makeTable(array,2)
for x,y in pairs(tempTable) do
spell.SourcePrimaryAttribute[tostring(x)] = y
end
elseif test == '[SOURCE_SECONDARY_ATTRIBUTES' then
spell.SourceSecondaryAttribute = {}
tempTable = makeTable(array,2)
for x,y in pairs(tempTable) do
spell.SourceSecondaryAttribute[tostring(x)] = y
end
elseif test == '[TARGET_PRIMARY_ATTRIBUTES' then
spell.TargetPrimaryAttribute = {}
tempTable = makeTable(array,2)
for x,y in pairs(tempTable) do
spell.TargetPrimaryAttribute[tostring(x)] = y
end
elseif test == '[TARGET_SECONDARY_ATTRIBUTES' then
spell.TargetSecondaryAttribute = {}
tempTable = makeTable(array,2)
for x,y in pairs(tempTable) do
spell.TargetSecondaryAttribute[tostring(x)] = y
end
elseif test == '[SCRIPT' then
script = data[j]:gsub("%s+","")
script = table.concat({select(2,table.unpack(split(script,':')))},':')
script = string.sub(script,1,-2)
spell.Script[scriptNum] = script
scriptNum = scriptNum + 1
elseif test == '[EXP_GAIN' then
spell.ExperienceGain = array[2]
elseif test == '[SKILL_GAIN' then
spell.SkillGain = spell.SkillGain or {}
spell.SkillGain[array[2]] = array[3]
elseif test == '[UPGRADE' then
spell.Upgrade = array[2]
elseif test == '[COST' then
spell.Cost = array[2]
elseif test == '[CAST_TIME' then
spell.CastTime = array[2]
elseif test == '[EXHAUSTION' then
spell.CastExhaustion = array[2]
elseif test == '[REQUIREMENT_PHYS' or test == '[REQUIREMENT_MENT' or test == '[REQUIREMENT_ATTRIBUTE' then
spell.RequiredAttribute = spell.RequiredAttribute or {}
spell.RequiredAttribute[array[2]] = array[3]
elseif test == '[FORBIDDEN_CLASS' then
spell.ForbiddenClass = spell.ForbiddenClass or {}
spell.ForbiddenClass[array[2]] = array[3]
elseif test == '[FORBIDDEN_SPELL' then
spell.ForbiddenSpell = spell.ForbiddenSpell or {}
spell.ForbiddenSpell[array[2]] = array[2]
end
end
end
end
return true
end
function makeFeatTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.FeatTable = {}
feats = persistTable.GlobalTable.roses.FeatTable
dataFiles,dataInfoFiles,files = getData('Feat','/raw/systems/Classes','feats','[FEAT',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
featToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
feats[featToken] = {}
feat = feats[featToken]
feat.Cost = '1'
feat.Effect = {}
feat.Script = {}
num = 0
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
feat.Name = array[2]
elseif test == '[DESCRIPTION' then
feat.Description = array[2]
elseif test == '[REQUIRED_CLASS' then
feat.RequiredClass = feat.RequiredClass or {}
feat.RequiredClass[array[2]] = array[3]
elseif test == '[FORBIDDEN_CLASS' then
feat.ForbiddenClass = feat.ForbiddenClass or {}
feat.ForbiddenClass[array[2]] = array[3]
elseif test == '[REQUIRED_FEAT' then
feat.RequiredFeat = feat.RequiredFeat or {}
feat.RequiredFeat[array[2]] = array[2]
elseif test == '[FORBIDDEN_FEAT' then
feat.ForbiddenFeat = feat.ForbiddenFeat or {}
feat.ForbiddenFeat[array[2]] = array[2]
elseif test == '[COST' then
feat.Cost = array[2]
elseif test == '[EFFECT' then
feat.Effect[#feat.Effect+1] = array[2]
elseif test == '[SCRIPT' then
script = data[j]:gsub("%s+","")
script = table.concat({select(2,table.unpack(split(script,':')))},':')
script = string.sub(script,1,-2)
feat.Script[num] = script
num = num + 1
end
end
feat.Scripts = tostring(num)
end
end
return true
end
-- End Class System Functions
-- Start Enhanced System Functions
function makeEnhancedBuildingTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EnhancedBuildingTable = {}
buildings = persistTable.GlobalTable.roses.EnhancedBuildingTable
dataFiles,dataInfoFiles,files = getData('Enhanced Building','/raw/systems/Enhanced','Ebuildings','[BUILDING',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
buildingToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
buildings[buildingToken] = {}
building = buildings[buildingToken]
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
building.Name = array[2]
elseif test == '[DESCRIPTION' then
building.Description = array[2]
elseif test == '[MULTI_STORY' then
building.MultiStory = array[2]
elseif test == '[TREE_BUILDING' then
building.TreeBuilding = array[2]
elseif test == '[BASEMENT' then
building.Basement = array[2]
elseif test == '[ROOF' then
building.Roof = array[2]
elseif test == '[WALLS' then
building.Walls = array[2]
elseif test == '[STAIRS' then
building.Stairs = array[2]
elseif test == '[UPGRADE' then
building.Upgrade = array[2]
elseif test == '[SPELL' then
spell = array[2]
building.Spells = building.Spells or {}
building.Spells[spell] = {}
building.Spells[spell].Frequency = array[3]
elseif test == '[REQUIRED_WATER' then
building.RequiredWater = array[2]
elseif test == '[REQUIRED_MAGMA' then
building.RequiredMagma = array[2]
elseif test == '[MAX_AMOUNT' then
building.MaxAmount = array[2]
elseif test == '[OUTSIDE_ONLY]' then
building.OutsideOnly = 'true'
elseif test == '[INSIDE_ONLY]' then
building.InsideOnly = 'true'
elseif test == '[REQUIRED_BUILDING' then
building.RequiredBuildings = building.RequiredBuildings or {}
building.RequiredBuildings[array[2]] = array[3]
elseif test == '[FORBIDDEN_BUILDING' then
building.ForbiddenBuildings = building.ForbiddenBuildings or {}
building.ForbiddenBuildings[array[2]] = array[3]
end
end
end
end
return true
end
function makeEnhancedCreatureTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EnhancedCreatureTable = {}
creatures = persistTable.GlobalTable.roses.EnhancedCreatureTable
dataFiles,dataInfoFiles,files = getData('Enhanced Creature','/raw/systems/Enhanced','Ecreatures','[CREATURE',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
creatureToken = split(x[1],':')[1]
casteToken = split(x[1],':')[2]
startLine = x[2]+1
if i == #dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
creatures[creatureToken] = {}
creatures[creatureToken][casteToken] = {}
creature = creatures[creatureToken][casteToken]
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
creature.Name = array[2]
elseif test == '[DESCRIPTION' then
creature.Description = array[2]
elseif test == '[BODY_SIZE' then
creature.Size = {}
creature.Size.Baby = array[2]
creature.Size.Child = array[3]
creature.Size.Adult = array[4]
creature.Size.Max = array[5]
creature.Size.Variance = array[6]
elseif test == '[ATTRIBUTE' then
creature.Attributes = creature.Attributes or {}
creature.Attributes[array[2]] = {}
creature.Attributes[array[2]]['1'] = array[3]
creature.Attributes[array[2]]['2'] = array[4] or array[3]
creature.Attributes[array[2]]['3'] = array[5] or array[3]
creature.Attributes[array[2]]['4'] = array[6] or array[3]
creature.Attributes[array[2]]['5'] = array[7] or array[3]
creature.Attributes[array[2]]['6'] = array[8] or array[3]
creature.Attributes[array[2]]['7'] = array[9] or array[3]
elseif test == '[NATURAL_SKILL' then
creature.Skills = creature.Skills or {}
creature.Skills[array[2]] = {}
creature.Skills[array[2]].Min = array[3]
creature.Skills[array[2]].Max = array[4] or array[3]
elseif test == '[STAT' then
creature.Stats = creature.Stats or {}
creature.Stats[array[2]] = {}
creature.Stats[array[2]].Min = array[3]
creature.Stats[array[2]].Max = array[4] or array[3]
elseif test == '[RESISTANCE' then
creature.Resistances = creature.Resistances or {}
creature.Resistances[array[2]] = array[3]
elseif test == '[CLASS' then
creature.Classes = creature.Classes or {}
creature.Classes[array[2]] = {}
creature.Classes[array[2]].Level = array[3]
creature.Classes[array[2]].Interactions = array[4]
elseif test =='[INTERACTION' then
creature.Interactions = creature.Interactions or {}
creature.Interactions[array[2]] = {}
creature.Interactions[array[2]].Probability = array[3]
end
end
end
end
-- Copy any ALL caste data into the respective CREATURE:CASTE combo, CASTE caste data is given priority
for _,creatureToken in pairs(creatures._children) do
for n,creature in pairs(df.global.world.raws.creatures.all) do
if creatureToken == creature.id then
creatureID = n
break
end
end
if creatureID then
for _,caste in pairs(creature.caste) do
if not creatures[creatureToken][caste.id] then
creatures[creatureToken][caste.id] = {}
end
end
end
if creatures[creatureToken].ALL then
for _,casteToken in pairs(creatures[creatureToken]._children) do
if not casteToken == 'ALL' then
for _,x in pairs(creatures[creatureToken].ALL._children) do
if not creatures[creatureToken][casteToken][x] then
creatures[creatureToken][casteToken][x] = creatures[creatureToken].ALL[x]
else
for _,y in pairs(creatures[creatureToken].ALL[x]._children) do
if not creatures[creatureToken][casteToken][x][y] then
creatures[creatureToken][casteToken][x][y] = creatures[creatureToken].ALL[x][y]
end
end
end
end
end
end
end
end
return true
end
function makeEnhancedItemTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EnhancedItemTable = {}
items = persistTable.GlobalTable.roses.EnhancedItemTable
dataFiles,dataInfoFiles,files = getData('Enhanced Item','/raw/systems/Enhanced','Eitems','[ITEM',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
itemToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
items[itemToken] = {}
item = items[itemToken]
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
test = array[1]
if test == '[NAME' then
item.Name = array[2]
elseif test == '[DESCRIPTION' then
item.Description = array[2]
elseif test == '[CLASS' then
item.Class = array[2]
elseif test == '[ON_EQUIP' then
item.OnEquip = item.OnEquip or {}
onTable = item.OnEquip
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_STRIKE' then
item.OnStrike = item.OnStrike or {}
onTable = item.OnStrike
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_PARRY' then
item.OnParry = item.OnParry or {}
onTable = item.OnParry
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_DODGE' then
item.OnDodge = item.OnDodge or {}
onTable = item.OnDodge
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ATTRIBUTE_CHANGE' then
onTable.Attributes = onTable.Attributes or {}
onTable.Attributes[array[2]] = array[3]
elseif test == '[SKILL_CHANGE' then
onTable.Skills = onTable.Skills or {}
onTable.Skills[array[2]] = array[3]
elseif test == '[TRAIT_CHANGE' then
onTable.Traits = onTable.Traits or {}
onTable.Traits[array[2]] = array[3]
elseif test == '[STAT_CHANGE' then
onTable.Stats = onTable.Stats or {}
onTable.Stats[stat] = array[3]
elseif test == '[RESISTANCE_CHANGE' then
onTable.Resistances = onTable.Resistances or {}
onTable.Resistances[array[2]] = array[3]
elseif test == '[INTERACTION_ADD' then
onTable.Interactions = onTable.Interactions or {}
onTable.Interactions[#onTable.Interactions+1] = array[2]
elseif test == '[SYNDROME_ADD' then
onTable.Syndromes = onTable.Syndromes or {}
onTable.Syndromes[#onTable.Syndromes+1] = array[2]
elseif test == '[ATTACKER_ATTRIBUTE_CHANGE' then
onTable.AttackerAttributes = onTable.AttackerAttributes or {}
onTable.AttackerAttributes[array[2]] = array[3]
elseif test == '[ATTACKER_SKILL_CHANGE' then
onTable.AttackerSkills = onTable.AttackerSkills or {}
onTable.AttackerSkills[array[2]] = array[3]
elseif test == '[ATTACKER_TRAIT_CHANGE' then
onTable.AttackerTraits = onTable.AttackerTraits or {}
onTable.AttackerTraits[array[2]] = array[3]
elseif test == '[ATTACKER_STAT_CHANGE' then
onTable.AttackerStats = onTable.AttackerStats or {}
onTable.AttackerStats[stat] = array[3]
elseif test == '[ATTACKER_RESISTANCE_CHANGE' then
onTable.AttackerResistances = onTable.AttackerResistances or {}
onTable.AttackerResistances[array[2]] = array[3]
elseif test == '[ATTACKER_INTERACTION_ADD' then
onTable.AttackerInteractions = onTable.AttackerInteractions or {}
onTable.AttackerInteractions[#onTable.AttackerInteractions+1] = array[2]
elseif test == '[ATTACKER_SYNDROME_ADD' then
onTable.AttackerSyndromes = onTable.AttackerSyndromes or {}
onTable.AttackerSyndromes[#onTable.SAttackeryndromes+1] = array[2]
elseif test == '[ATTACKER_CHANGE_DUR' then
onTable.AttackerDur = array[2]
elseif test == '[DEFENDER_ATTRIBUTE_CHANGE' then
onTable.DefenderAttributes = onTable.DefenderAttributes or {}
onTable.DefenderAttributes[array[2]] = array[3]
elseif test == '[DEFENDER_SKILL_CHANGE' then
onTable.DefenderSkills = onTable.DefenderSkills or {}
onTable.DefenderSkills[array[2]] = array[3]
elseif test == '[DEFENDER_TRAIT_CHANGE' then
onTable.DefenderTraits = onTable.DefenderTraits or {}
onTable.DefenderTraits[array[2]] = array[3]
elseif test == '[DEFENDER_STAT_CHANGE' then
onTable.DefenderStats = onTable.DefenderStats or {}
onTable.DefenderStats[stat] = array[3]
elseif test == '[DEFENDER_RESISTANCE_CHANGE' then
onTable.DefenderResistances = onTable.DefenderResistances or {}
onTable.DefenderResistances[array[2]] = array[3]
elseif test == '[DEFENDER_INTERACTION_ADD' then
onTable.DefenderInteractions = onTable.DefenderInteractions or {}
onTable.DefenderInteractions[#onTable.DefenderInteractions+1] = array[2]
elseif test == '[DEFENDER_SYNDROME_ADD' then
onTable.DefenderSyndromes = onTable.DefenderSyndromes or {}
onTable.DefenderSyndromes[#onTable.DefenderSyndromes+1] = array[2]
elseif test == '[DEFENDER_CHANGE_DUR' then
onTable.DefenderDur = array[2]
end
end
if not test then
base = 'modtools/item-trigger -itemType '..itemToken
equip = '-command [ enhanced/item-equip -unit \\UNIT_ID -item \\ITEM_ID'
action = '-command [ enhanced/item-action -attacker \\ATTACKER_ID -defender \\DEFENDER_ID -item \\ITEM_ID'
if item.OnEquip then
dfhack.run_command(base..' -onEquip '..equip..' -equip ]')
dfhack.run_command(base..' -onUnequip '..equip..' ]')
end
if item.OnStrike then dfhack.run_command(base..' -onStrike '..action..' -action Strike ]') end
if item.OnDodge then dfhack.run_command(base..' -onStrike '..action..' -action Dodge ]') end
if item.OnParry then dfhack.run_command(base..' -onStrike '..action..' -action Parry ]') end
end
end
end
return true
end
function makeEnhancedMaterialTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EnhancedMaterialTable = {}
persistTable.GlobalTable.roses.EnhancedMaterialTable.Inorganic = {}
persistTable.GlobalTable.roses.EnhancedMaterialTable.Creature = {}
persistTable.GlobalTable.roses.EnhancedMaterialTable.Plant = {}
persistTable.GlobalTable.roses.EnhancedMaterialTable.Misc = {}
materials = persistTable.GlobalTable.roses.EnhancedMaterialTable
dataFiles,dataInfoFiles,files = getData('Enhanced Material','/raw/systems/Enhanced','Ematerials','[MATERIAL',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
materialToken = split(x[1],':')[1]
materialIndex = split(x[1],':')[2]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
test = array[1]
material = {}
if test == '[NAME' then
material.Name = array[2]
elseif test == '[DESCRIPTION' then
material.Description = array[2]
elseif test == '[ON_EQUIP' then
material.OnEquip = material.OnEquip or {}
onTable = material.OnEquip
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_STRIKE' then
material.OnStrike = material.OnStrike or {}
onTable = material.OnStrike
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_PARRY' then
material.OnParry = material.OnParry or {}
onTable = material.OnParry
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ON_DODGE' then
material.OnDodge = material.OnDodge or {}
onTable = material.OnDodge
onTable.Script = onTable.Script or {}
onTable.Script[#onTable.Script+1] = array[2]
elseif test == '[ATTRIBUTE_CHANGE' then
onTable.Attributes = onTable.Attributes or {}
onTable.Attributes[array[2]] = array[3]
elseif test == '[SKILL_CHANGE' then
onTable.Skills = onTable.Skills or {}
onTable.Skills[array[2]] = array[3]
elseif test == '[TRAIT_CHANGE' then
onTable.Traits = onTable.Traits or {}
onTable.Traits[array[2]] = array[3]
elseif test == '[STAT_CHANGE' then
onTable.Stats = onTable.Stats or {}
onTable.Stats[stat] = array[3]
elseif test == '[RESISTANCE_CHANGE' then
onTable.Resistances = onTable.Resistances or {}
onTable.Resistances[array[2]] = array[3]
elseif test == '[INTERACTION_ADD' then
onTable.Interactions = onTable.Interactions or {}
onTable.Interactions[#onTable.Interactions+1] = array[2]
elseif test == '[SYNDROME_ADD' then
onTable.Syndromes = onTable.Syndromes or {}
onTable.Syndromes[#onTable.Syndromes+1] = array[2]
elseif test == '[ATTACKER_ATTRIBUTE_CHANGE' then
onTable.AttackerAttributes = onTable.AttackerAttributes or {}
onTable.AttackerAttributes[array[2]] = array[3]
elseif test == '[ATTACKER_SKILL_CHANGE' then
onTable.AttackerSkills = onTable.AttackerSkills or {}
onTable.AttackerSkills[array[2]] = array[3]
elseif test == '[ATTACKER_TRAIT_CHANGE' then
onTable.AttackerTraits = onTable.AttackerTraits or {}
onTable.AttackerTraits[array[2]] = array[3]
elseif test == '[ATTACKER_STAT_CHANGE' then
onTable.AttackerStats = onTable.AttackerStats or {}
onTable.AttackerStats[stat] = array[3]
elseif test == '[ATTACKER_RESISTANCE_CHANGE' then
onTable.AttackerResistances = onTable.AttackerResistances or {}
onTable.AttackerResistances[array[2]] = array[3]
elseif test == '[ATTACKER_INTERACTION_ADD' then
onTable.AttackerInteractions = onTable.AttackerInteractions or {}
onTable.AttackerInteractions[#onTable.AttackerInteractions+1] = array[2]
elseif test == '[ATTACKER_SYNDROME_ADD' then
onTable.AttackerSyndromes = onTable.AttackerSyndromes or {}
onTable.AttackerSyndromes[#onTable.SAttackeryndromes+1] = array[2]
elseif test == '[ATTACKER_CHANGE_DUR' then
onTable.AttackerDur = array[2]
elseif test == '[DEFENDER_ATTRIBUTE_CHANGE' then
onTable.DefenderAttributes = onTable.DefenderAttributes or {}
onTable.DefenderAttributes[array[2]] = array[3]
elseif test == '[DEFENDER_SKILL_CHANGE' then
onTable.DefenderSkills = onTable.DefenderSkills or {}
onTable.DefenderSkills[array[2]] = array[3]
elseif test == '[DEFENDER_TRAIT_CHANGE' then
onTable.DefenderTraits = onTable.DefenderTraits or {}
onTable.DefenderTraits[array[2]] = array[3]
elseif test == '[DEFENDER_STAT_CHANGE' then
onTable.DefenderStats = onTable.DefenderStats or {}
onTable.DefenderStats[stat] = array[3]
elseif test == '[DEFENDER_RESISTANCE_CHANGE' then
onTable.DefenderResistances = onTable.DefenderResistances or {}
onTable.DefenderResistances[array[2]] = array[3]
elseif test == '[DEFENDER_INTERACTION_ADD' then
onTable.DefenderInteractions = onTable.DefenderInteractions or {}
onTable.DefenderInteractions[#onTable.DefenderInteractions+1] = array[2]
elseif test == '[DEFENDER_SYNDROME_ADD' then
onTable.DefenderSyndromes = onTable.DefenderSyndromes or {}
onTable.DefenderSyndromes[#onTable.DefenderSyndromes+1] = array[2]
elseif test == '[DEFENDER_CHANGE_DUR' then
onTable.DefenderDur = array[2]
end
end
-- Seperate materials into Inorganic, Creature, and Plant
if materialToken == 'INORGANIC' then
materials.Inorganic[materialIndex] = material
else
creatureCheck = false
plantCheck = false
for _,creature in pairs(df.global.world.raws.creatures.all) do
if creature.creature_id == materialToken then
materials.Creature[materialToken] = materials.Creature[materialToken] or {}
materials.Creature[materialToken][materialIndex] = material
creatureCheck = true
break
end
end
if not creatureCheck then
for _,plant in pairs(df.global.world.raws.plants.all) do
if plant.id == materialToken then
materials.Plant[materialToken] = materials.Plant[materialToken] or {}
materials.Plant[materialToken][materialIndex] = material
plantCheck = true
break
end
end
end
if not creatureCheck and not plantCheck then
materials.Misc[materialToken] = materials.Misc[materialToken] or {}
materials.Misc[materialToken][materialIndex] = material
end
end
end
end
-- Copy any ALL material data into the respective MATERIAL:INDEX combo, INDEX material data is given priority
-- No need for inorganics
-- Creatures
for _,materialToken in pairs(materials.Creature._children) do
for n,creature in pairs(df.global.world.raws.creatures.all) do
if materialToken == creature.creature_id then
creatureID = n
break
end
end
if creatureID and materials.Creature[materialToken].ALL then
for _,material in pairs(creature.caste[0].materials) do
if not materials.Creature[materialToken][material.id] then
materials.Creature[materialToken][material.id] = {}
end
end
end
if materials.Creature[materialToken].ALL then
for _,materialIndex in pairs(materials.Creature[materialToken]._children) do
if not materialIndex == 'ALL' then
for _,x in pairs(materials.Creature[materialToken].ALL._children) do
if not materials.Creature[materialToken][materialIndex][x] then
materials.Creature[materialToken][materialIndex][x] = materials.Creature[materialToken].ALL[x]
else
for _,y in pairs(materials.Creature[materialToken].ALL[x]._children) do
if not materials.Creature[materialToken][materialIndex][x][y] then
materials.Creature[materialToken][materialIndex][x][y] = materials.Creature[materialToken].ALL[x][y]
end
end
end
end
end
end
end
end
-- Plants
for _,materialToken in pairs(materials.Plant._children) do
for n,plant in pairs(df.global.world.raws.plants.all) do
if materialToken == plant.id then
plantID = n
break
end
end
if plantID and materials.Plant[materialToken].ALL then
for _,material in pairs(df.global.world.raws.plants.all[plantID].material) do
if not materials.Plant[materialToken][material.id] then
materials.Plant[materialToken][material.id] = {}
end
end
end
if materials.Plant[materialToken].ALL then
for _,materialIndex in pairs(materials.Plant[materialToken]._children) do
if not materialIndex == 'ALL' then
for _,x in pairs(materials.Plant[materialToken].ALL._children) do
if not materials.Plant[materialToken][materialIndex][x] then
materials.Plant[materialToken][materialIndex][x] = materials.Plant[materialToken].ALL[x]
else
for _,y in pairs(materials.Plant[materialToken].ALL[x]._children) do
if not materials.Plant[materialToken][materialIndex][x][y] then
materials.Plant[materialToken][materialIndex][x][y] = materials.Plant[materialToken].ALL[x][y]
end
end
end
end
end
end
end
end
if not test then
for _,materialToken in pairs(materials.Inorganic._children) do
material = materials.Inorganic[materialToken]
base = 'modtools/item-trigger -mat '..materialToken
equip = '-command [ enhanced/item-equip -unit \\UNIT_ID -item \\ITEM_ID -mat'
action = '-command [ enhanced/item-action -attacker \\ATTACKER_ID -defender \\DEFENDER_ID -item \\ITEM_ID -mat'
if material.OnEquip then
dfhack.run_command(base..' -onEquip '..equip..' -equip ]')
dfhack.run_command(base..' -onUnequip '..equip..' ]')
end
if material.OnStrike then dfhack.run_command(base..' -onStrike '..action..' -action Strike ]') end
if material.OnDodge then dfhack.run_command(base..' -onStrike '..action..' -action Dodge ]') end
if material.OnParry then dfhack.run_command(base..' -onStrike '..action..' -action Parry ]') end
end
for _,materialToken in pairs(materials.Creature._children) do
for _,materialIndex in pairs(materials.Creature[materialToken]._children) do
if not materialIndex == 'ALL' then
material = materials.Creature[materialToken][materialIndex]
base = 'modtools/item-trigger -mat '..'CREATURE_MAT:'..materialToken..':'..materialIndex
equip = '-command [ enhanced/item-equip -unit \\UNIT_ID -item \\ITEM_ID -mat'
action = '-command [ enhanced/item-action -attacker \\ATTACKER_ID -defender \\DEFENDER_ID -item \\ITEM_ID -mat'
if material.OnEquip then
dfhack.run_command(base..' -onEquip '..equip..' -equip ]')
dfhack.run_command(base..' -onUnequip '..equip..' ]')
end
if material.OnStrike then dfhack.run_command(base..' -onStrike '..action..' -action Strike ]') end
if material.OnDodge then dfhack.run_command(base..' -onStrike '..action..' -action Dodge ]') end
if material.OnParry then dfhack.run_command(base..' -onStrike '..action..' -action Parry ]') end
end
end
end
for _,materialToken in pairs(materials.Plant._children) do
for _,materialIndex in pairs(materials.Plant[materialToken]._children) do
if not materialIndex == 'ALL' then
material = materials.Plant[materialToken][materialIndex]
base = 'modtools/item-trigger -mat '..'PLANT_MAT:'..materialToken..':'..materialIndex
equip = '-command [ enhanced/item-equip -unit \\UNIT_ID -item \\ITEM_ID -mat'
action = '-command [ enhanced/item-action -attacker \\ATTACKER_ID -defender \\DEFENDER_ID -item \\ITEM_ID -mat'
if material.OnEquip then
dfhack.run_command(base..' -onEquip '..equip..' -equip ]')
dfhack.run_command(base..' -onUnequip '..equip..' ]')
end
if material.OnStrike then dfhack.run_command(base..' -onStrike '..action..' -action Strike ]') end
if material.OnDodge then dfhack.run_command(base..' -onStrike '..action..' -action Dodge ]') end
if material.OnParry then dfhack.run_command(base..' -onStrike '..action..' -action Parry ]') end
end
end
end
end
return true
end
function makeEnhancedReactionTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EnhancedReactionTable = {}
reactions = persistTable.GlobalTable.roses.EnhancedReactionTable
dataFiles,dataInfoFiles,files = getData('Enhanced Reaction','/raw/systems/Enhanced','Ereactions','[REACTION',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
reactionToken = x[1]
startLine = x[2]+1
if i == #dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
reactions[reactionToken] = {}
reaction = reactions[reactionToken]
reaction.Frozen = 'false'
reaction.Disappear = 'false'
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
reaction.Name = array[2]
elseif test == '[DESCRIPTION' then
reaction.Description = array[2]
elseif test == '[BASE_DURATION' then
reaction.BaseDur = array[2]
elseif test == '[SKILL' then
reaction.Skill = array[2]
elseif test == '[SKILL_DURATION' then
reaction.SkillDur = makeTable(array,2,20)
elseif test == '[DURATION_REDUCTION' then
reaction.DurReduction = {}
reaction.DurReduction.Increment = array[2]
reaction.DurReduction.MaxReduction = array[3]
elseif test == '[ADDITIONAL_PRODUCT' then
reaction.Products = reaction.Products or {}
num = #reaction.Products + 1
reaction.Products[num] = {}
reaction.Products[num].Chance = array[2]
reaction.Products[num].Number = array[3]
reaction.Products[num].MaterialType = array[4]
reaction.Products[num].MaterialSubType = array[5]
reaction.Products[num].ItemType = array[6]
reaction.Products[num].ItemSubType = array[7]
elseif test == '[FREEZE]' then
reaction.Frozen = 'true'
elseif test == '[REMOVE]' then
reaction.Disappear = 'true'
end
end
end
end
return true
end
-- End Enhanced System Functions
-- Start Event System Functions
function makeEventTable(test,verbose)
local utils = require 'utils'
local split = utils.split_string
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.EventTable = {}
events = persistTable.GlobalTable.roses.EventTable
dataFiles,dataInfoFiles,files = getData('Event','/raw/systems/Events','events','[EVENT',test,verbose)
if not dataFiles then return false end
for _,file in ipairs(files) do
dataInfo = dataInfoFiles[file]
data = dataFiles[file]
for i,x in ipairs(dataInfo) do
eventToken = x[1]
startLine = x[2]+1
if i ==#dataInfo then
endLine = #data
else
endLine = dataInfo[i+1][2]-1
end
events[eventToken] = {}
event = events[eventToken]
event.Effect = {}
event.Required = {}
event.Delay = {}
numberOfEffects = 0
for j = startLine,endLine,1 do
test = data[j]:gsub("%s+","")
test = split(test,':')[1]
array = split(data[j],':')
for k = 1, #array, 1 do
array[k] = split(array[k],']')[1]
end
if test == '[NAME' then
event.Name = array[2]
elseif test == '[CHECK' then
event.Check = array[2]
elseif test == '[CHANCE' then
event.Chance = array[2]
elseif test == '[DELAY' then
event.Delay[array[2]] = array[3]
elseif test == '[REQUIREMENT' then
if array[2] == 'COUNTER_MAX' then
event.Required.CounterMax = event.Required.CounterMax or {}
event.Required.CounterMax[array[3]] = array[4]
elseif array[2] == 'COUNTER_MIN' then
event.Required.CounterMin = event.Required.CounterMin or {}
event.Required.CounterMin[array[3]] = array[4]
elseif array[2] == 'COUNTER_EQUAL' then
event.Required.CounterEqual = event.Required.CounterEqual or {}
event.Required.CounterEqual[array[3]] = array[4]
elseif array[2] == 'TIME' then
event.Required.Time = array[3]
elseif array[2] == 'POPULATION' then
event.Required.Population = array[3]
elseif array[2] == 'SEASON' then
event.Required.Season = array[3]
elseif array[2] == 'TREES_CUT' then
event.Required.TreeCut = array[3]
elseif array[2] == 'FORTRESS_RANK' then
event.Required.Rank = array[3]
elseif array[2] == 'PROGRESS_RANK' then
if array[3] == 'POPULATION' then event.Required.ProgressPopulation = array[4] end
if array[3] == 'TRADE' then event.Required.ProgressTrade = array[4] end
if array[3] == 'PRODUCTION' then event.Required.ProgressProduction = array[4] end
elseif array[2] == 'ARTIFACTS' then
event.Required.NumArtifacts = array[3]
elseif array[2] == 'TOTAL_DEATHS' then
event.Required.TotDeaths = array[3]
elseif array[2] == 'TOTAL_INSANITIES' then
event.Required.TotInsanities = array[3]
elseif array[2] == 'TOTAL_EXECUTIONS' then
event.Required.TotExecutions = array[3]
elseif array[2] == 'MIGRANT_WAVES' then
event.Required.MigrantWaves = array[3]
elseif array[2] == 'WEALTH' then
event.Required.Wealth = event.Required.Wealth or {}
event.Required.Wealth[array[3]] = array[4]
elseif array[2] == 'BUILDING' then
event.Required.Building = event.Required.Building or {}
event.Required.Building[array[3]] = array[4]
elseif array[2] == 'SKILL' then
event.Required.Skill = event.Required.Skill or {}
event.Required.Skill[array[3]] = array[4]
elseif array[2] == 'CLASS' then
event.Required.Class = event.Required.Class or {}
event.Required.Class[array[3]] = array[4]
elseif array[2] == 'ENTITY_KILLS' then
event.Required.EntityKills = event.Required.EntityKills or {}
event.Required.EntityKills[array[3]] = array[4]
elseif array[2] == 'CREATURE_KILLS' then
event.Required.CreatureKills = event.Required.CreatureKills or {}
event.Required.CreatureKills[array[3]] = event.Required.CreatureKills[array[3]] or {}
event.Required.CreatureKills[array[3]][array[4]] = array[5]
elseif array[2] == 'ENTITY_DEATHS' then
event.Required.EntityDeaths = event.Required.EntityDeaths or {}
event.Required.EntityDeaths[array[3]] = array[4]
elseif array[2] == 'CREATURE_DEATHS' then
event.Required.CreatureDeaths = event.Required.CreatureDeaths or {}
event.Required.CreatureDeaths[array[3]] = event.Required.CreatureDeaths[array[3]] or {}
event.Required.CreatureDeaths[array[3]][array[4]] = array[5]
elseif array[2] == 'TRADES' then
event.Required.Trades = event.Required.Trades or {}
event.Required.Trades[array[3]] = array[4]
elseif array[2] == 'SIEGES' then
event.Required.Sieges = event.Required.Sieges or {}
event.Required.Sieges[array[3]] = array[4]
elseif array[2] == 'DIPLOMACY' then
event.Required.Diplomacy = event.Required.Diplomacy or {}
event.Required.Diplomacy[array[3]..':'..array[4]..':'..array[5]..':'..array[6]] = '1'
end
elseif test == '[EFFECT' then
number = array[2]
numberOfEffects = numberOfEffects + 1
event.Effect[number] = {}
effect = event.Effect[number]
effect.Arguments = '0'
effect.Argument = {}
effect.Required = {}
effect.Script = {}
effect.Delay = {}
effect.Scripts = '0'
elseif test == '[EFFECT_NAME' then
effect.Name = array[2]
elseif test == '[EFFECT_CHANCE' then
effect.Chance = array[2]
elseif test == '[EFFECT_CONTINGENT_ON' then
effect.Contingent = array[2]
elseif test == '[EFFECT_DELAY' then
effect.Delay[array[2]] = array[3]
elseif test == '[EFFECT_REQUIREMENT' then
if array[2] == 'COUNTER_MAX' then
effect.Required.CounterMax = effect.Required.CounterMax or {}
effect.Required.CounterMax[array[3]] = array[4]
elseif array[2] == 'COUNTER_MIN' then
effect.Required.CounterMin = effect.Required.CounterMin or {}
effect.Required.CounterMin[array[3]] = array[4]
elseif array[2] == 'COUNTER_EQUAL' then
effect.Required.CounterEqual = effect.Required.CounterEqual or {}
effect.Required.CounterEqual[array[3]] = array[4]
elseif array[2] == 'TIME' then
effect.Required.Time = array[3]
elseif array[2] == 'POPULATION' then
effect.Required.Population = array[3]
elseif array[2] == 'SEASON' then
effect.Required.Season = array[3]
elseif array[2] == 'TREES_CUT' then
effect.Required.TreeCut = array[3]
elseif array[2] == 'FORTRESS_RANK' then
effect.Required.Rank = array[3]
elseif array[2] == 'PROGRESS_RANK' then
if array[3] == 'POPULATION' then effect.Required.ProgressPopulation = array[4] end
if array[3] == 'TRADE' then effect.Required.ProgressTrade = array[4] end
if array[3] == 'PRODUCTION' then effect.Required.ProgressProduction = array[4] end
elseif array[2] == 'ARTIFACTS' then
effect.Required.NumArtifacts = array[3]
elseif array[2] == 'TOTAL_DEATHS' then
effect.Required.TotDeaths = array[3]
elseif array[2] == 'TOTAL_INSANITIES' then
effect.Required.TotInsanities = array[3]
elseif array[2] == 'TOTAL_EXECUTIONS' then
effect.Required.TotExecutions = array[3]
elseif array[2] == 'MIGRANT_WAVES' then
effect.Required.MigrantWaves = array[3]
elseif array[2] == 'WEALTH' then
effect.Required.Wealth = effect.Required.Wealth or {}
effect.Required.Wealth[array[3]] = array[4]
elseif array[2] == 'BUILDING' then
effect.Required.Building = effect.Required.Building or {}
effect.Required.Building[array[3]] = array[4]
elseif array[2] == 'SKILL' then
effect.Required.Skill = effect.Required.Skill or {}
effect.Required.Skill[array[3]] = array[4]
elseif array[2] == 'CLASS' then
effect.Required.Class = effect.Required.Class or {}
effect.Required.Class[array[3]] = array[4]
elseif array[2] == 'ENTITY_KILLS' then
effect.Required.EntityKills = effect.Required.EntityKills or {}
effect.Required.EntityKills[array[3]] = array[4]
elseif array[2] == 'CREATURE_KILLS' then
effect.Required.CreatureKills = effect.Required.CreatureKills or {}
effect.Required.CreatureKills[array[3]] = effect.Required.CreatureKills[array[3]] or {}
effect.Required.CreatureKills[array[3]][array[4]] = array[5]
elseif array[2] == 'ENTITY_DEATHS' then
effect.Required.EntityDeaths = effect.Required.EntityDeaths or {}
effect.Required.EntityDeaths[array[3]] = array[4]
elseif array[2] == 'CREATURE_DEATHS' then
effect.Required.CreatureDeaths = effect.Required.CreatureDeaths or {}
effect.Required.CreatureDeaths[array[3]] = effect.Required.CreatureDeaths[array[3]] or {}
effect.Required.CreatureDeaths[array[3]][array[4]] = array[5]
elseif array[2] == 'TRADES' then
effect.Required.Trades = effect.Required.Trades or {}
effect.Required.Trades[array[3]] = array[4]
elseif array[2] == 'SIEGES' then
effect.Required.Sieges = effect.Required.Sieges or {}
effect.Required.Sieges[array[3]] = array[4]
elseif array[2] == 'DIPLOMACY' then
effect.Required.Diplomacy = effect.Required.Diplomacy or {}
effect.Required.Diplomacy[array[3]..':'..array[4]..':'..array[5]..':'..array[6]] = '1'
end
elseif test == '[EFFECT_UNIT' then
effect.Unit = {}
local temptable = {select(2,table.unpack(array))}
strint = '1'
for _,v in pairs(temptable) do
effect.Unit[strint] = v
strint = tostring(strint+1)
end
elseif test == '[EFFECT_LOCATION' then
effect.Location = {}
local temptable = {select(2,table.unpack(array))}
strint = '1'
for _,v in pairs(temptable) do
effect.Location[strint] = v
strint = tostring(strint+1)
end
elseif test == '[EFFECT_BUILDING' then
effect.Building = {}
local temptable = {select(2,table.unpack(array))}
strint = '1'
for _,v in pairs(temptable) do
effect.Building[strint] = v
strint = tostring(strint+1)
end
elseif test == '[EFFECT_ITEM' then
effect.Item = {}
local temptable = {select(2,table.unpack(array))}
strint = '1'
for _,v in pairs(temptable) do
effect.Item[strint] = v
strint = tostring(strint+1)
end
elseif test == '[EFFECT_ARGUMENT' then
argnumber = array[2]
effect.Arguments = tostring(effect.Arguments + 1)
effect.Argument[argnumber] = {}
argument = effect.Argument[argnumber]
elseif test == '[ARGUMENT_WEIGHTING' then
argument.Weighting = array[2]
elseif test == '[ARGUMENT_EQUATION' then
argument.Equation = array[2]
elseif test == '[ARGUMENT_VARIABLE' then
argument.Variable = array[2]
elseif test == '[EFFECT_SCRIPT' then
effect.Scripts = tostring(effect.Scripts + 1)
script = data[j]:gsub("%s+","")
script = table.concat({select(2,table.unpack(split(script,':')))},':')
script = string.sub(script,1,-2)
effect.Script[effect.Scripts] = script
end
end
event.Effects = tostring(numberOfEffects)
end
end
return true
end
--End Event System Functions
---------------------------------------------------------------------------------------------
-------- Functions for making persistent tables for tracking in-game information ------------
---------------------------------------------------------------------------------------------
function makeDiplomacyTable(verbose)
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.DiplomacyTable = persistTable.GlobalTable.roses.DiplomacyTable or {}
for _,civ1 in pairs(persistTable.GlobalTable.roses.EntityTable._children) do
persistTable.GlobalTable.roses.DiplomacyTable[civ1] = persistTable.GlobalTable.roses.DiplomacyTable[civ1] or {}
for _,civ2 in pairs(persistTable.GlobalTable.roses.EntityTable._children) do
if civ1 == civ2 then
persistTable.GlobalTable.roses.DiplomacyTable[civ1][civ2] = '1000'
else
persistTable.GlobalTable.roses.DiplomacyTable[civ1][civ2] = '0'
end
end
end
return true
end
function makeEntityTable(entity,verbose)
if tonumber(entity) then
civid = tonumber(entity)
else
civid = entity.id
end
key = tostring(civid)
entity = df.global.world.entities.all[civid]
local persistTable = require 'persist-table'
local key = tostring(entity.id)
local entity = entity.entity_raw.code
local civilizations = persistTable.GlobalTable.roses.CivilizationTable
local entityTable = persistTable.GlobalTable.roses.EntityTable
if entityTable[key] then
return
else
entityTable[key] = {}
entityTable = entityTable[key]
entityTable.Kills = {}
entityTable.Deaths = {}
entityTable.Trades = '0'
entityTable.Sieges = '0'
if civilizations then
if civilizations[entity] then
entityTable.Civilization = {}
entityTable.Civilization.Name = entity
entityTable.Civilization.Level = '0'
entityTable.Civilization.CurrentMethod = civilizations[entity].LevelMethod
entityTable.Civilization.CurrentPercent = civilizations[entity].LevelPercent
entityTable.Civilization.Classes = {}
if civilizations[entity].Level then
if civilizations[entity].Level['0'] then
for _,mtype in pairs(civilizations[entity].Level['0'].Remove._children) do
local depth1 = civilizations[entity].Level['0'].Remove[mtype]
for _,stype in pairs(depth1._children) do
local depth2 = depth1[stype]
for _,mobj in pairs(depth2._children) do
local sobj = depth2[mobj]
dfhack.script_environment('functions/entity').changeResources(key,mtype,stype,mobj,sobj,-1,true)
end
end
end
for _,mtype in pairs(civilizations[entity].Level['0'].Add._children) do
local depth1 = civilizations[entity].Level['0'].Add[mtype]
for _,stype in pairs(depth1._children) do
local depth2 = depth1[stype]
for _,mobj in pairs(depth2._children) do
local sobj = depth2[mobj]
dfhack.script_environment('functions/entity').changeResources(key,mtype,stype,mobj,sobj,1,true)
end
end
end
if civilizations[entity].Level['0'].Classes then
for _,class in pairs(civilizations[entity].Level['0'].Classes._children) do
level = tonumber(civilizations[entity].Level['0'].Classes[class])
if level > 0 then
entityTable.Civilization.Classes[class] = tostring(level)
else
entityTable.Civilization.Classes[class] = nil
end
end
end
end
end
end
end
end
end
function makeGlobalTable(verbose)
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.GlobalTable = {}
persistTable.GlobalTable.roses.GlobalTable.Kills = {}
persistTable.GlobalTable.roses.GlobalTable.Deaths = {}
persistTable.GlobalTable.roses.GlobalTable.Trades = {}
persistTable.GlobalTable.roses.GlobalTable.Sieges = {}
end
function makeItemTable(item,verbose)
if tonumber(item) then
item = df.item.find(tonumber(item))
end
itemID = item.id
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.ItemTable[tostring(itemID)] = {}
itemTable = persistTable.GlobalTable.roses.ItemTable[tostring(itemID)]
itemTable.Material = {}
itemTable.Material.Base = dfhack.matinfo.getToken(item.mat_type,item.mat_index)
itemTable.Material.Current = dfhack.matinfo.getToken(item.mat_type,item.mat_index)
itemTable.Material.StatusEffects = {}
itemTable.Quality = {}
itemTable.Quality.Base = tostring(item.quality)
itemTable.Quality.Current = tostring(item.quality)
itemTable.Quality.StatusEffects = {}
itemTable.Subtype = {}
itemTable.Subtype.Base = dfhack.items.getSubtypeDef(item:getType(),item:getSubtype()).id
itemTable.Subtype.Current = dfhack.items.getSubtypeDef(item:getType(),item:getSubtype()).id
itemTable.Subtype.StatusEffects = {}
itemTable.Stats = {}
itemTable.Stats.Kills = '0'
end
function makeUnitTable(unit,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)] = {}
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
if unit.civ_id >= 0 then
if safe_index(persistTable,'GlobalTable','roses','EntityTable',tostring(unit.civ_id),'Civilization') then
unitTable.Civilization = persistTable.GlobalTable.roses.EntityTable[tostring(unit.civ_id)].Civilization.Name
end
end
unitTable.SyndromeTrack = {}
unitTable.Attributes = {}
unitTable.Skills = {}
unitTable.Traits = {}
unitTable.Feats = {}
unitTable.Resistances = {}
unitTable.General = {}
unitTable.Stats = {}
unitTable.Stats.Kills = '0'
unitTable.Stats.Deaths = '0'
unitTable.Classes = {}
if persistTable.GlobalTable.roses.ClassTable then
unitTable.Classes.Current = {}
unitTable.Classes.Current.Name = 'NONE'
unitTable.Classes.Current.TotalExp = tostring(0)
unitTable.Classes.Current.FeatPoints = tostring(0)
end
unitTable.Spells = {}
if persistTable.GlobalTable.roses.SpellTable then
unitTable.Spells.Active = {}
end
end
function makeUnitTableSecondary(unit,table,token,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable[table][token] = {}
unitTable[table][token].Base = '0'
unitTable[table][token].Change = '0'
unitTable[table][token].Class = '0'
unitTable[table][token].Item = '0'
unitTable[table][token].StatusEffects = {}
_,base = dfhack.script_environment('functions/unit').getUnit(unit,table,token,'initialize',verbose)
unitTable[table][token].Base = tostring(base)
end
function makeUnitTableClass(unit,class,test,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable.Classes[class] = {}
unitTable.Classes[class].Level = '0'
unitTable.Classes[class].Experience = '0'
unitTable.Classes[class].SkillExp = '0'
end
function makeUnitTableSpell(unit,spell,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable.Spells[spell] = '0'
end
function makeUnitTableSide(unit,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable.General.Side = {}
unitTable.General.Side.StatusEffects = {}
end
function makeUnitTableTransform(unit,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable.General.Transform = {}
unitTable.General.Transform.Race = {}
unitTable.General.Transform.Race.Base = tostring(unit.race)
unitTable.General.Transform.Race.Current = tostring(unit.race)
unitTable.General.Transform.Caste = {}
unitTable.General.Transform.Caste.Base = tostring(unit.caste)
unitTable.General.Transform.Caste.Current = tostring(unit.caste)
unitTable.General.Transform.StatusEffects = {}
end
function makeUnitTableSummon(unit,verbose)
if tonumber(unit) then
unit = df.unit.find(tonumber(unit))
end
local persistTable = require 'persist-table'
unitTable = persistTable.GlobalTable.roses.UnitTable[tostring(unit.id)]
unitTable.General.Summoned = {}
unitTable.General.Summoned.Creator = tostring(-1)
unitTable.General.Summoned.End = tostring(-1)
unitTable.General.Summoned.Syndrome = tostring(-1)
end
|
box = require 'box'
Entity = class(box.Dynamic)
function Entity:new(x, y, w, h)
box.Dynamic.new(self, x, y, w, h)
self.gravity = 0
self.gravityAcceleration = 0
self.jumpForce = 0
self.jumpDecelaration = 0
self.movement = { x = 0, y = 0}
self.maxFallSpeed = 3
self:fall(self.maxFallSpeed, 0.5)
end
function Entity:jump(height, seconds)
-- calculate the values for a jump
local steps = seconds / (1.0 / 60)
local force = height * (1.0 / steps) * 2.0
self.jumpDecelaration = force / math.max(steps - 1.0, 1.0)
self.jumpForce = -force
-- check for platform and correct jump force to include platform y velocity
if self.contactSurface.down and self.contactSurface.down:is_a(box.Moving) then
self.jumpForce = self.jumpForce + self.contactSurface.down.vel.y
end
end
function Entity:fall(maxSpeed, seconds)
local steps = seconds / (1.0 / 60)
self.gravityAcceleration = maxSpeed / (math.max(steps - 1, 0.1));
end
function Entity:update(dt)
box.Dynamic.update(self, dt)
-- jump forces and gravity are handles differently
-- this makes the whole system easier and more friendly to gameplay tweaking
if self.jumpForce < self.maxFallSpeed and self.jumpDecelaration ~= 0 then
self.jumpForce = self.jumpForce + self.jumpDecelaration
self.vel.y = (self.movement.y * dt) + self.jumpForce
self.gravity = self.jumpForce
if self.contactSurface.down and self.vel.y > 0 then
self.jumpForce = 0
self.gravity = 0
end
else
-- check whether we're falling
if not self.contactSurface.down then
self.gravity = self.gravity + self.gravityAcceleration
if self.gravity > self.maxFallSpeed then
self.gravity = self.maxFallSpeed
end
else
self.gravity = 0
-- check for platforms and make the entity move downwards with them
if self.contactSurface.down:is_a(box.Moving) then
self.gravity = self.contactSurface.down.vel.y
end
end
self.vel.y = (self.movement.y * dt) + self.gravity
end
-- check for platform and x velocity to include platform x velocity
self.vel.x = (self.movement.x * dt)
if self.contactSurface.down and self.contactSurface.down:is_a(box.Moving) then
local mx = self.contactSurface.down.vel.x
if self.vel.x == 0 or (self.vel.x > 0 and mx > 0) or (self.vel.x < 0 and mx < 0) then
self.vel.x = (self.movement.x * dt) + mx
end
end
end
function Entity:draw()
box.Dynamic.draw(self)
end
|
local mod = get_mod("Gib")
local pl = require'pl.import_into'()
fassert(pl, "Gib must be lower than Penlight Lua Libraries in your launcher's load order.")
UnitGibSettings_b = UnitGibSettings_b or table.clone(UnitGibSettings)
mod:hook(GenericHitReactionExtension, "_execute_effect", function(func, self, unit, effect_template, biggest_hit, parameters, t, dt)
if mod:get(mod.SETTING_NAMES.ALWAYS_DISMEMBER) then
effect_template = table.clone(effect_template)
effect_template.do_dismember = true
end
if mod:get(mod.SETTING_NAMES.FORCE_DISMEMBER) then
parameters = table.clone(parameters)
parameters.force_dismember = true
end
if mod:get(mod.SETTING_NAMES.ALWAYS_RAGDOLL) then
self.force_ragdoll_on_death = true
end
return func(self, unit, effect_template, biggest_hit, parameters, t, dt)
end)
mod:hook(GenericHitReactionExtension, "_do_push", function(func, self, unit, dt)
local breed = Unit.get_data(unit, "breed")
breed.scale_death_push = mod:get(mod.SETTING_NAMES.DEATH_PUSH_MULTIPLIER)
return func(self, unit, dt)
end)
mod:hook(DamageUtils, "calculate_stagger_player", function(func, stagger_table, target_unit, attacker_unit, hit_zone_name, original_power_level, boost_curve_multiplier, is_critical_strike, damage_profile, target_index, blocked, damage_source)
local stagger_type, stagger_duration, stagger_distance, stagger_value, stagger_strength
= func(stagger_table, target_unit, attacker_unit, hit_zone_name, original_power_level, boost_curve_multiplier, is_critical_strike, damage_profile, target_index, blocked, damage_source)
mod:pcall(function()
stagger_distance = stagger_distance * mod:get(mod.SETTING_NAMES.STAGGER_MULTIPLIER)/100
end)
return stagger_type, stagger_duration, stagger_distance, stagger_value, stagger_strength
end)
mod.on_setting_changed = function(setting_name)
if setting_name == mod.SETTING_NAMES.GIB_PUSH_FORCE then
mod.apply_gib_push_force()
end
end
mod.apply_gib_push_force = function()
for _, breed_gib_data in pairs( UnitGibSettings ) do
for _, part in pairs( breed_gib_data.parts ) do
part.gib_push_force = mod:get(mod.SETTING_NAMES.GIB_PUSH_FORCE)
end
end
end
mod.on_enabled = function()
mod.apply_gib_push_force()
end
mod.on_disabled = function()
UnitGibSettings = table.clone(UnitGibSettings_b)
end
|
local Cinematic = Cinematic
local RenderScene = RenderScene
local Shared = Shared
local Client = Client
local Server = Server
local old = getupvalue(TunnelUserMixin.OnProcessSpectate, "UpdateTunnelEffects")
local kTunnelUseScreenCinematic = getupvalue(old, "kTunnelUseScreenCinematic")
local function UpdateTunnelEffects(self)
local isInTunnel = self.inTunnel
if self.clientIsInTunnel ~= isInTunnel then
local cinematic = Client.CreateCinematic(RenderScene.Zone_ViewModel)
cinematic:SetCinematic(kTunnelUseScreenCinematic)
cinematic:SetRepeatStyle(Cinematic.Repeat_None)
if isInTunnel then
self:TriggerEffects("tunnel_enter_2D")
else
self:TriggerEffects("tunnel_exit_2D")
end
self.clientIsInTunnel = isInTunnel
self.clientTimeTunnelUsed = Shared.GetTime()
end
end
setupvalue(TunnelUserMixin.OnProcessSpectate, "UpdateTunnelEffects", UpdateTunnelEffects)
do
local old = getupvalue(TunnelUserMixin.OnUpdate, "SharedUpdate")
local UpdateSinkIn = getupvalue(old, "UpdateSinkIn")
local UpdateExitTunnel = getupvalue(old, "UpdateExitTunnel")
local kTunnelUseTimeout = getupvalue(old, "kTunnelUseTimeout")
if Server then
local function SharedUpdate(self, deltaTime)
if self.canUseTunnel then
if self:GetIsEnteringTunnel() then
UpdateSinkIn(self, deltaTime)
else
self.timeSinkInStarted = nil
local tunnel = self.inTunnel
if tunnel then
UpdateExitTunnel(self, deltaTime, tunnel)
end
end
end
self.canUseTunnel = self.timeTunnelUsed + kTunnelUseTimeout < Shared.GetTime()
end
setupvalue(TunnelUserMixin.OnUpdate, "SharedUpdate", SharedUpdate)
elseif Client then
local function SharedUpdate(self, deltaTime)
if self.canUseTunnel and self:GetIsEnteringTunnel() then
UpdateSinkIn(self, deltaTime)
end
if self.GetIsLocalPlayer and self:GetIsLocalPlayer() then
self.inTunnel = GetIsPointInGorgeTunnel(self:GetOrigin())
UpdateTunnelEffects(self)
end
end
setupvalue(TunnelUserMixin.OnUpdate, "SharedUpdate", SharedUpdate)
end
end
do
local old = TunnelUserMixin.__initmixin
function TunnelUserMixin:__initmixin()
old(self)
self.inTunnel = false
end
end
|
include("shared.lua")
function ENT:Draw()
self.BaseClass.Draw(self)
if self:IsDroneWorkable() and not DRONES_REWRITE.ClientCVars.NoGlows:GetBool() then
local dlight = DynamicLight(self:EntIndex())
if dlight then
dlight.pos = self:LocalToWorld(Vector(12, 0, 0))
dlight.r = 0
dlight.g = 255
dlight.b = 255
dlight.brightness = 1
dlight.Decay = 1000
dlight.Size = 80
dlight.DieTime = CurTime() + 0.1
end
if not self.Emitter then self.Emitter = ParticleEmitter(Vector(0, 0, 0)) return end
if math.random(1, 15) == 1 then
local p = self.Emitter:Add("particle/smokesprites_000" .. math.random(1, 9), self:LocalToWorld(Vector(-7.5, 16, 0)))
p:SetDieTime(math.Rand(0.5, 1.5))
p:SetStartAlpha(70)
p:SetEndAlpha(0)
p:SetStartSize(math.Rand(0.5, 1))
p:SetRoll(math.Rand(-10, 10))
p:SetRollDelta(math.Rand(-1, 1))
p:SetEndSize(5)
p:SetCollide(true)
p:SetGravity(Vector(0, 0, 5))
p:SetVelocity(VectorRand() * 2 - self:GetRight() * 7 - self:GetForward() * 6)
p:SetColor(0, 255, 255)
end
end
end
function ENT:OnRemove()
if IsValid(self.Emitter) then self.Emitter:Finish() end
end |
--- when join run this
addEventHandler('onPlayerJoin', root, function()
---spawn
spawnPlayer(source, 0, 0, 5)
--fade
fadeCamera(source, true)
setCameraTarget(source, source)
end) |
local cmd = vim.cmd -- to execute Vim commands e.g. cmd('pwd')
local opt = vim.opt -- to set options
cmd 'colorscheme Base2Tone_MeadowDark'
opt.termguicolors = true -- True color support
opt.background = 'dark'
|
--pine tree schematic
local _ = {name = "air", prob = 0}
local l = {name = "default:pine_needles", prob = 255}
local t = {name = "default:pine_tree", prob = 255}
bd_basic_biomes.pinetree = {
size = {x = 7, y = 11, z = 7},
yslice_prob = {
{ypos = 0, prob = 127}, -- trunk
{ypos = 1, prob = 127},
{ypos = 2, prob = 127},
{ypos = 5, prob = 127}, -- leaves
{ypos = 7, prob = 127},
},
data = {
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,l,l,l,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,l,l,l,l,l,_,
_,_,_,l,_,_,_,
_,_,l,l,l,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,t,_,_,_,
_,_,_,t,_,_,_,
_,_,_,t,_,_,_,
_,_,_,t,_,_,_,
_,_,_,t,_,_,_,
_,_,l,t,l,_,_,
l,l,l,t,l,l,l,
_,_,l,t,l,_,_,
_,l,l,t,l,l,_,
_,_,l,t,l,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,l,l,l,l,l,_,
_,_,_,l,_,_,_,
_,_,l,l,l,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,l,l,l,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,l,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
_,_,_,_,_,_,_,
}
}
|
local combatF = CreateFrame("Frame")
local Aura = CreateFrame("Frame")
local class = CreateFrame("Frame")
local antispam = false
local SpellID = {
ES = 192106,
LS = 79949,
WS = 204288
}
local SpellName = {
ES = "Earth Shield",
LS = "Lightning Shield",
WS = "Water Shield"
}
class:RegisterEvent("ADDON_LOADED")
class:SetScript("OnEvent", function(self, event, arg1, ...) -- check if shaman class is played
if (event == 'ADDON_LOADED') and arg1 == 'Shieldify' then
local class, _, _ = UnitClass('player')
if class == 'Shaman' then
combatF:RegisterEvent("PLAYER_REGEN_DISABLED")
combatF:RegisterEvent("PLAYER_REGEN_ENABLED")
combatF:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED")
end
end
end)
combatF:SetScript("OnEvent", function(self, event, arg1, arg2, arg3, ...)
if (event == "PLAYER_REGEN_DISABLED") then -- COMBAT
Aura:RegisterUnitEvent("UNIT_AURA", "player")
if _shieldInBuffs() then
_displayupdate()
antispam = true
elseif not _shieldInBuffs() then
_displayupdate(1, _Sfy_SetAlert())
antispam = false
end
end
if (event == "PLAYER_REGEN_ENABLED") then -- EXIT COMBAT
_displayupdate()
Aura:UnregisterEvent("UNIT_AURA")
end
end)
Aura:SetScript("OnEvent", function(self, event, ...)
if (event == "UNIT_AURA") then
if not _shieldInBuffs() and antispam == false then
_displayupdate(1, _Sfy_SetAlert())
antispam = true
elseif _shieldInBuffs() and antispam == true then
antispam = false
_displayupdate()
end
end
end)
function _shieldInBuffs()
local buffs, i = { }, 1
local buff = UnitBuff("player", i)
while buff do
buffs[#buffs + 1] = buff
i = i + 1
buff = UnitBuff("player", i)
end
for i=1,#buffs do
if (buffs[i] == SpellName['LS']) or (buffs[i] == SpellName['WS']) or (buffs[i] == SpellName['ES']) then
_displayupdate()
return true
end
end
end
|
--if love.system.getOS() ~= "Android" then debug = true end
--load libraries
loader = require("libs/love-loader")
lume = require("libs/lume")
pause = require("pause")
anim8 = require("libs/anim8")
Timer = require("libs/knife.timer")
Object = require("libs/classic")
Player = require("player")
Fade = require("fade")
Enemy = require("enemy")
Chair = require("chair")
Items = require("items")
Interact = require("interact")
if love.system.getOS() == "Android" then
android = require("gui")
end
--require("error")
Gallery = require("gallery")
require("gameStates")
require("load")
font = love.graphics.newFont("assets/Jamboree.ttf",8)
font:setFilter("nearest","nearest",1)
images = {}
sounds = {}
finishedLoading = false
SCENE = {}
p_anim,animation = {}
require("rain_intro_scenes")
require("game_over")
require("animation")
require("secret_room")
require("attic_room")
require("particles")
require("rightroom")
require("leftroom")
require("storagePuzzle")
require("leave_event")
require("colored_assets")
require("credits_scene")
hump_timer = require("libs/hump/timer")
splash_finished = false
local utf8 = require("utf8")
user_input = ""
correct = "mom fell his fault"
love.keyboard.setTextInput(false)
width, height = 128,64
sw,sh = love.window.getDesktopDimensions()
interact = false
local _ads = require("ads")
FC = require("libs.firstcrush.gui")
if debug == false then
-- love.window.setFullscreen(true)
ty = height
-- ty = sh - (height * math.min(sw/width,sh/height))
if love.system.getOS() == "iOS" then
if pro_version then
--ty = sh - (height * math.min(sw/width,sh/height))
ty = height/2
end
end
if love.system.getOS() == "Android" then
if pro_version then
ty = height
else
ty = sh - (height * math.min(sw/width,sh/height))
end
end
else
love.window.setFullscreen(false)
if love.system.getOS() == "Android" then
if pro_version then
ty = height
else
ty = sh - (height * math.min(sw/width,sh/height))
end
else
ty = 0
end
end
if gameplay_record then
love.mouse.setVisible(false)
end
load_complete = false
progress = {}
pauseFlag = false
temp_move = false
function show_ads()
if FC:validate() == "accept" then
love.system.createBanner(_ads.banner,"top","SMART_BANNER")
love.system.createInterstitial(_ads.inter)
love.system.showBanner()
if love.system.isInterstitialLoaded() == true then
love.system.showInterstitial()
end
end
end
function love.load()
if pro_version then
states = "splash"
else
states = "adshow"
end
clock = 0 --game timer
sWidth, sHeight = love.graphics.getDimensions()
ratio = math.min(sWidth/width, sHeight/height)
pressed = false
love.keyboard.setKeyRepeat(true)
gamestates.load()
loader.start(function()
finishedLoading = true
--set all images for pixel quality
for k,v in pairs(images) do v:setFilter("nearest","nearest",1) end
light = images.light
--set things up
animation_set()
assets.set()
particle_set()
end)
--canvas
custom_mask = love.graphics.newCanvas()
love.graphics.setCanvas(custom_mask)
love.graphics.clear(0,0,0)
love.graphics.setCanvas()
--tv_flash
tv_flash = love.graphics.newCanvas()
love.graphics.setCanvas(tv_flash)
love.graphics.clear(0,0,0)
love.graphics.setCanvas()
--candles
candles_flash = love.graphics.newCanvas()
love.graphics.setCanvas(candles_flash)
love.graphics.clear(0,0,0)
love.graphics.setCanvas()
--right room
right_canvas = love.graphics.newCanvas()
love.graphics.setCanvas(right_canvas)
love.graphics.clear(0,0,0)
love.graphics.setCanvas()
--left room
left_canvas = love.graphics.newCanvas()
love.graphics.setCanvas(left_canvas)
love.graphics.clear(0,0,0)
love.graphics.setCanvas()
--dust
dust = love.graphics.newCanvas()
--set variables
blink = false
--windows animation var
win_move_l = true
win_move_r = true
lv = 100 --starting light value
light_blink = true
lightOn = false
end
function love.update(dt)
clock = clock + 1 * dt
if not finishedLoading then
loader.update()
else
if FC:getState() then FC:update(dt)
else
gamestates.update(dt)
if love.system.getOS() == "Android" or love.system.getOS() == "iOS" then
android.update(dt)
end
end
end
end
function love.draw()
love.graphics.push()
love.graphics.translate(0,ty)
love.graphics.scale(ratio, ratio)
if finishedLoading then
if pauseFlag == false then
gamestates.draw()
elseif pauseFlag == true then
pause.draw()
end
if FC:getState() then FC:draw() end
else
local percent = 0
if loader.resourceCount ~= 0 then percent = loader.loadedCount / loader.resourceCount end
--love.graphics.setColor(percent*100,0,0,255)
love.graphics.setColor(1, 1, 1, 150/255)
love.graphics.setFont(font)
love.graphics.print("Loading",width - 34 -font:getWidth("Loading")/2, height - 12)
love.graphics.setFont(font)
love.graphics.setColor(1, 1, 1, 150/255)
love.graphics.print(("..%d%%"):format(percent*100), width - 20, height -12)
end
--dev_draw()
--if debug == true then
--love.graphics.setColor(255,0,0,255)
--love.graphics.rectangle("line",0,0,width,height)
--end
love.graphics.pop()
end
function love.mousereleased(x,y,button,istouch)
if load_complete == true then
local state = gamestates.getState()
local mx = (x) /ratio
local my = (y - ty) /ratio
if state == "intro" or state == "rain_intro" then
if pressed == true then
pressed = false
end
end
end
end
function love.mousepressed(x,y,button,istouch)
FC:mousepressed(x,y,button,istouch)
if load_complete == true then
local state = gamestates.getState()
local mx = (x) /ratio
local my = (y - ty) /ratio
--android.mouse_gui(x,y,button,istouch)
if state == "gallery" then
if Gallery.mouse(mx,my,gExit) then
love.keypressed("escape")
end
end
if state == "title" then
if button == 1 then
if instruction == false and about == false and questions == false then
if check_gui(gui_pos.start_x,gui_pos.start_y,gui_pos.start_w,gui_pos.start_h) then
--start
gamestates.control()
elseif check_gui(gui_pos.quit_x,gui_pos.quit_y,gui_pos.quit_w,gui_pos.quit_h) then
--exit
if love.system.getOS() ~= "iOS" then
love.event.quit()
end
elseif check_gui(gui_pos.webx,gui_pos.weby,gui_pos.webw,gui_pos.webh) then
--love.system.openURL("https://brbl.gamejolt.io")
if love.system.getOS() == "Android" then
love.system.createInterstitial(_ads.inter)
if love.system.isInterstitialLoaded() == true then
love.system.showInterstitial()
end
--print("clicked on gui")
--love.system.createInterstitial(_ads.inter)
--love.system.showBanner()
--if love.system.isInterstitialLoaded() == true then
--love.system.showInterstitial()
--end
end
end
end
if instruction == false then
if check_gui(gui_pos.i_x,gui_pos.i_y,gui_pos.i_w,gui_pos.i_h) then
instruction = true
end
else
if check_gui(gui_pos.b_x,gui_pos.b_y,gui_pos.b_w,gui_pos.b_h) then
instruction = false
end
end
if about == false then
if check_gui(gui_pos.a_x,gui_pos.a_y,gui_pos.a_w,gui_pos.a_h) then
about = true
end
else
if check_gui(gui_pos.b_x,gui_pos.b_y,gui_pos.b_w,gui_pos.b_h) then
about = false
end
end
if questions == false then
if check_gui(gui_pos.q_x,gui_pos.q_y,gui_pos.q_w,gui_pos.q_h) then
questions = true
end
else
if check_gui(gui_pos.t_x,gui_pos.t_y,gui_pos.t_w,gui_pos.t_h) then
love.system.openURL("https://twitter.com/flamendless")
elseif check_gui(gui_pos.p_x,gui_pos.p_y,gui_pos.p_w,gui_pos.p_h) then
if love.system.getOS() ~= "iOS" then
love.system.openURL("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=K7QQSFGC2WXEA")
end
elseif check_gui(gui_pos.e_x,gui_pos.e_y,gui_pos.e_w,gui_pos.e_h) then
love.system.openURL("mailto:[email protected]")
elseif check_gui(gui_pos.b_x,gui_pos.b_y,gui_pos.b_w,gui_pos.b_h) then
questions = false
end
end
if check_gui(width/2 + 12,gui_pos.q_y,8,8) then
gamestates.nextState("gallery")
end
end
elseif state == "rain_intro" then
if check_gui(gui_pos.skip_x,gui_pos.skip_y,gui_pos.skip_w,gui_pos.skip_h) then
pressed = true
fade.state = true
states = "intro"
gamestates.load()
end
elseif state == "intro" then
if check_gui(gui_pos.skip_x,gui_pos.skip_y,gui_pos.skip_w,gui_pos.skip_h) then
pressed = true
fade.state = true
states = "main"
gamestates.load()
end
elseif state == "main" then
if pauseFlag == true then
if check_gui(gSound.x,gSound.y,gSound.w,gSound.h) then
if gSound.img == images.gui_sound then
pause.sound("off")
else
pause.sound("on")
end
elseif check_gui(gSettingsBack.x,gSettingsBack.y,gSettingsBack.w,gSettingsBack.h) then
pause.exit()
elseif check_gui(gQuit.x,gQuit.y,gQuit.w,gQuit.h) then
love.event.quit()
end
end
end
end
end
function love.keyreleased(key)
if load_complete == true then
if key == "f5" then
love.event.quit()
end
local state = gamestates.getState()
if love.system.getOS() == "Android" then
android.setKey(key)
end
if state == "main" then
if key == "a" or key == "d" then
player.isMoving = false
end
end
if state == "intro" or state == "rain_intro" then
if key == "return" or key == "e" then
pressed = false
end
end
if state == "title" then
if instruction == false and about == false and questions == false then
if cursor_select == true then
if key == "w" or key == "up" then
cursor_pos = 1
elseif key == "s" or key == "down" then
cursor_pos = 2
elseif key == "d" or key == "right" then
if cursor_pos == 1 or cursor_pos == 2 or cursor_pos == 0 then
cursor_pos = 3
elseif cursor_pos == 3 then
cursor_pos = 4
elseif cursor_pos == 4 then
cursor_pos = 5
elseif cursor_pos == 5 then
cursor_pos = 6
elseif cursor_pos == 6 then
cursor_pos = 1
end
elseif key == "a" or key == "left" then
if cursor_pos == 1 or cursor_pos == 2 or cursor_pos == 0 then
cursor_pos = 6
elseif cursor_pos == 3 then
cursor_pos = 1
elseif cursor_pos == 4 then
cursor_pos = 3
elseif cursor_pos == 5 then
cursor_pos = 4
elseif cursor_pos == 6 then
cursor_pos = 5
end
elseif key == "return" or key == "e" then
if cursor_pos == 1 then
gamestates.control()
elseif cursor_pos == 2 then
love.event.quit()
elseif cursor_pos == 3 then
questions = true
elseif cursor_pos == 4 then
about = true
elseif cursor_pos == 5 then
instruction = true
elseif cursor_pos == 6 then
love.system.openURL("https://brbl.gamejolt.io")
end
end
end
end
if key == "escape" then
if instruction == true then
instruction = false
end
if about == true then
about = false
end
if questions == true then
questions = false
end
end
end
if lr_event == 3 then
if key == "a" then
e_c = 1
elseif key == "d" then
e_c = 2
elseif key == "e" then
if route == 1 then
if e_c == 1 then
event_route = him_convo
elseif e_c == 2 then
event_route = wait_convo
end
elseif route == 2 then
if e_c == 1 then
event_route = leave_convo
elseif e_c == 2 then
event_route = wait_convo
end
end
if event_route ~= nil then
lr_event = 4
end
end
end
end
end
function love.keypressed(key)
if load_complete == true then
local dt = love.timer.getDelta( )
local state = gamestates.getState()
if love.system.getOS() == "Android" then
android.setKey(key)
end
if state == "intro" then
if key == "return" or key == "e" then
pressed = true
fade.state = true
states = "main"
gamestates.load()
end
end
if state == "title" then
if pro_version then
if key == "g" then
gamestates.nextState("gallery")
end
end
end
if state == "gallery" then
if pro_version then
Gallery.keypressed(key)
if key == "escape" then
Gallery.exit()
gamestates.nextState("title")
end
end
end
if key == "e" or key == "space" or key == "return" then
if state == "splash" then
gamestates.nextState("splash2")
end
if state == "splash2" then
gamestates.nextState("title")
end
end
if state == "rain_intro" then
if key == "return" or key == "e" then
pressed = true
fade.state = true
states = "intro"
gamestates.load()
end
end
if state == "main" then
if key == "f" then
if currentRoom ~= images["rightRoom"] and currentRoom ~= images["leftRoom"] and ending_leave ~= true then
if word_puzzle == false then
if lightOn == true then
lightOn = false
elseif lightOn == false then
lightOn = true
end
if ghost_event == "limp" or
ghost_event == "flashback" or
currentRoom == images["leftRoom"] or
currentRoom == images["rightRoom"] or
ending_leave == true then
sounds.fl_toggle:stop()
else
sounds.fl_toggle:play()
end
end
end
end
if love.system.getOS() ~= "Android" or love.system.getOS() ~= "iOS" then
if key == "p" then
if pauseFlag == true then
pause.exit()
else
pause.load()
end
end
end
if move == true then
love.keyboard.setKeyRepeat(true)
if pushing_anim == false then
if key == "a" then
if player.moveLeft == true then
player.isMoving = true
end
if player.dir == 1 then
player.dir = -1
child:flipH()
player_push:flipH()
idle:flipH()
-- walk:flipH()
end
if ghost_event == "no escape" then
if ghost_chase == false then
ghost_chase = true
end
end
elseif key == "d" then
if player.moveRight == true then
player.isMoving = true
end
if player.dir == -1 then
player.dir = 1
child:flipH()
player_push:flipH()
idle:flipH()
-- walk:flipH()
end
if ghost_event == "no escape" then
if ghost_chase == false then
ghost_chase = true
end
end
elseif key == "e" then
if currentRoom == images["leftRoom"] or currentRoom == images["rightRoom"] then
if lightOn == false then
player:checkItems()
player:checkDoors()
end
end
if move_chair == false then
if event_find == false then
if lightOn == true then
player:checkItems()
player:checkDoors()
end
else
player:checkItems()
player:checkDoors()
end
end
end
end
elseif move == false then
love.keyboard.setKeyRepeat(false)
for k,v in pairs(dialogue) do
for j,k in pairs(obj) do
if v.tag == k.tag then
if v.state == true then
if key == "e" then
if v.n <= #v.txt then
v.n = v.n + 1
end
end
if v.option == true then
if key == "left" or key == "a" then
v.cursor = 1
elseif key == "right" or key == "d" then
v.cursor = 2
elseif key == "space" or key == "return" or key == "e" then
v:returnChoices(v.cursor)
end
end
end
end
end
end
if lr_event == 3 then
if key == "a" then
e_c = 1
elseif key == "d" then
e_c = 2
elseif key == "e" then
if route == 1 then
if e_c == 1 then
event_route = him_convo
elseif e_c == 2 then
event_route = wait_convo
end
elseif route == 2 then
if e_c == 1 then
event_route = leave_convo
elseif e_c == 2 then
event_route = wait_convo
end
end
if event_route ~= nil then
lr_event = 4
end
end
end
end
end
if word_puzzle == true then
move = false
if love.system.getOS() == "Android" then
android.lightChange(true)
end
if key == "escape" then
word_puzzle = false
move = true
storage_puzzle = false
if love.system.getOS() == "Android" then
android.lightChange(false)
end
else
love.keyboard.setTextInput(true)
if key == "backspace" then
sounds.backspace_key:play()
sounds.backspace_key:setLooping(false)
local byteoffset = utf8.offset(user_input, -1)
if byteoffset then
user_input = string.sub(user_input,1,byteoffset -1)
end
end
end
end
if doodle_flag == true then
move = false
if love.system.getOS() == "Android" then
android.lightChange(true)
end
if key == "escape" then
doodle_flag = false
move = true
storage_puzzle = false
if love.system.getOS() == "Android" then
android.lightChange(false)
end
elseif key == "a" then
if pic_number > 1 then
pic_number = pic_number - 1
random_page()
else
pic_number = 1
end
elseif key == "d" then
if pic_number < #puzzle_pics then
pic_number = pic_number + 1
random_page()
else
pic_number = #puzzle_pics
end
end
end
if clock_puzzle == true then
if love.system.getOS() == "Android" then
android.lightChange(true)
end
if key == "escape" then
clock_puzzle = false
move = true
if love.system.getOS() == "Android" then
android.lightChange(false)
end
elseif key == "w" then
if selected == "hour" then
if hour < 12 then
hour = hour + 1
else
hour = 1
end
elseif selected == "minute" then
if minute < 60 then
minute = minute + 1
else
minute = 1
end
elseif selected == "second" then
if second < 60 then
second = second + 1
else
second = 1
end
elseif selected == "ampm" then
if ampm == "am" then
ampm = "pm"
else
ampm = "am"
end
end
elseif key == "s" then
if selected == "hour" then
if hour > 1 then
hour = hour - 1
else
hour = 12
end
elseif selected == "minute" then
if minute > 1 then
minute = minute - 1
else
minute = 60
end
elseif selected == "second" then
if second > 1 then
second = second - 1
else
second = 60
end
elseif selected == "ampm" then
if ampm == "am" then
ampm = "pm"
else
ampm = "am"
end
end
elseif key == "a" then
if selected == "minute" then
selected = "hour"
elseif selected == "second" then
selected = "minute"
elseif selected == "ampm" then
selected = "second"
end
elseif key == "d" then
if selected == "hour" then
selected = "minute"
elseif selected == "minute" then
selected = "second"
elseif selected == "second" then
selected = "ampm"
end
elseif key == "return" then
clock_puzzle = false
move = true
if love.system.getOS() == "Android" or love.system.getOS() == "iOS" or debug == true then
android.lightChange(false)
end
if hour == 10 and minute == 2 and second == 8 and ampm == "pm" then
clock_puzzle = false
sounds.item_got:play()
solved = true
sounds.main_theme:stop()
sounds.intro_soft:stop()
sounds.finding_home:stop()
sounds.ts_theme:stop()
end
end
end
--debugging
if state == 'main' then
if cheat == true then
--if key == "1" then currentRoom = images["mainRoom"] fade.state = true end
--if key == "2" then currentRoom = images["livingRoom"] fade.state = true end
--if key == "3" then currentRoom = images["stairRoom"] fade.state = true end
--if key == "4" then currentRoom = images["hallwayLeft"] fade.state = true end
--if key == "5" then currentRoom = images["masterRoom"] fade.state = true end
--if key == "6" then currentRoom = images["hallwayRight"] fade.state = true end
--if key == "7" then currentRoom = images["daughterRoom"] fade.state = true end
if key == "1" then currentRoom = images["kitchen"] fade.state = true end
--if key == "9" then currentRoom = images["atticRoom"] end
--if key == "0" then currentRoom = images["basementRoom"] end
--if key == "s" or key == "escape" then
--door_locked = false
--mid_dial = 1
--event = "after_dialogue"
--obtainables["match"] = false
obtainables["crowbar"] = false
--obtainables["chest"] = false
--end
-- if key == "l" then
-- if lv == 150 then lv = 255 else lv = 150 end
-- end
-- if key == "p" then
-- obtainables["gun1"] = false
-- obtainables["gun2"] = false
-- obtainables["gun3"] = false
-- temp_clock_gun = math.floor(clock)
-- end
--if key == "j" then
--obtainables["gun1"] = false
--obtainables["gun2"] = false
--obtainables["gun3"] = false
--check_gun()
--end
-- if key == "l" then
-- lv = 0
-- end
end
end
end
end
function love.textinput(t)
if string.len(user_input) < string.len(correct) then
sounds.type:play()
sounds.type:setLooping(false)
user_input = user_input .. t
end
end
function math.clamp(x, min, max)
return x < min and min or (x > max and max or x)
end
function Set(list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
function round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function check_gun()
if obtainables["gun1"] == false and
obtainables["gun2"] == false and
obtainables["gun3"] == false then
doorTxt("I have all the parts","I need a table to rebuild it")
local ammo_dial = Interact(false,{"It's an ammo box","There's only one ammo here","Load it?"},{"Yes","No"},"","ammo")
table.insert(dialogue,ammo_dial)
local ammo_item = Items(images.ammo,images["leftRoom"],41,34,"ammo")
table.insert(obj,ammo_item)
ammo_available = true
else
move = true
end
end
function turnLight()
if currentRoom ~= images["rightRoom"] and currentRoom ~= images["leftRoom"] and ending_leave ~= true then
if word_puzzle == false then
if lightOn == true then
lightOn = false
elseif lightOn == false then
lightOn = true
end
if ghost_event == "limp" or
ghost_event == "flashback" or
currentRoom == images["leftRoom"] or
currentRoom == images["rightRoom"] or
ending_leave == true then
sounds.fl_toggle:stop()
else
sounds.fl_toggle:play()
end
end
end
end
function love.touchpressed(id,x,y)
if load_complete == true then
android.touchpressed(id,x,y)
end
end
function love.touchreleased(id,x,y)
if load_complete == true then
android.touchreleased(id,x,y)
end
end
function love.touchmoved(id,x,y)
--local state = gamestates.getState()
--if state == "gallery" then
--if pro_version then
--Gallery.touchmoved(id,x,y)
--end
--end
end
--project by Brandon Blanker Lim-it
[email protected]
--@flamendless
|
local Spell = { }
Spell.LearnTime = 360
Spell.Description = [[
Disguising spell, disguises
anything this spell hits
from players' eyes for
a while.
]]
--Spell.WhatToSay = "Hide"
Spell.ShouldSay = false
Spell.FlyEffect = "hpw_white_main"
Spell.ImpactEffect = "hpw_white_impact"
Spell.CanSelfCast = false
Spell.ApplyDelay = 0.4
Spell.AccuracyDecreaseVal = 0.2
Spell.Category = { HpwRewrite.CategoryNames.Protecting, HpwRewrite.CategoryNames.Special }
Spell.OnlyIfLearned = { "Salvio Hexia" }
Spell.NodeOffset = Vector(-1095, 243, 0)
function Spell:OnSpellSpawned(wand, spell)
wand:PlayCastSound()
end
function Spell:OnFire(wand)
return true
end
local undereff = { }
local function RemoveOcculto(ent)
if not undereff[ent] then return end
if IsValid(ent) then
ent:SetNoDraw(false)
sound.Play("npc/turret_floor/active.wav", ent:GetPos(), 65, 180)
timer.Remove("hpwrewrite_occulto_handler" .. ent:EntIndex())
end
undereff[ent] = nil
end
function Spell:OnCollide(spell, data)
local ent = data.HitEntity
if IsValid(ent) and not undereff[ent] then
ent:SetNoDraw(true)
undereff[ent] = true
timer.Create("hpwrewrite_occulto_handler" .. ent:EntIndex(), 45, 1, function() RemoveOcculto(ent) end)
end
end
HpwRewrite:AddSpell("Hiding Charm", Spell)
-- Counter spell
local Spell = { }
Spell.ShouldSay = false
Spell.LearnTime = 360
Spell.Description = [[
Counter-spell to Hiding Charm,
removes disguising effect
from everything in small area around
spell hit position.
]]
--Spell.WhatToSay = "Reveal"
Spell.FlyEffect = "hpw_white_main"
Spell.ImpactEffect = "hpw_white_impact"
Spell.ApplyDelay = 0.4
Spell.AccuracyDecreaseVal = 0.4
Spell.Category = { HpwRewrite.CategoryNames.Protecting, HpwRewrite.CategoryNames.Special }
Spell.OnlyIfLearned = { "Hiding Charm" }
Spell.CanSelfCast = false
Spell.NodeOffset = Vector(-966, 133, 0)
function Spell:OnSpellSpawned(wand, spell)
wand:PlayCastSound()
end
function Spell:OnFire(wand)
return true
end
function Spell:OnCollide(spell, data)
for k, v in pairs(ents.FindInSphere(data.HitPos, 100)) do
RemoveOcculto(v)
end
end
HpwRewrite:AddSpell("Revealing Charm", Spell) |
--
-- 竞技场服务模块
--
-- 竞技场的排行榜放在 namespace db 上
--
-- 竞技场的计算热点在于发生挑战时的战斗计算,所以需要启动多个slave去分担这些计算量
--
local skynet = require "skynetex"
local cluster = require "cluster"
local slave = {}
local balance = 1
local lock = {}
local command = {}
-- src vs dst
function command.challenge( src, dst )
if lock[src] or lock[dst] then
return
end
lock[src] = true
lock[dst] = true
local s = slave[balance]
balance = balance + 1
if balance > #slave then
balance = 1
end
local win = skynet.call(s, "lua", src, dst)
lock[src] = nil
lock[dst] = nil
return win
end
local function launch_slave()
local function challenge(src, dst)
-- 在做真正的战斗计算逻辑,判断胜负,返回获胜一方
-- ...
-- for test
local win = src
if win == src then
-- 决定胜负之后,如果挑战成功,则交换双方排行榜位置
skynet.call(".namespace_db", "lua", "athletic_exchange_rank", src, dst)
end
return win
end
local function ret_pack(ok, err, ...)
if ok then
skynet.ret(skynet.pack(err, ...))
else
error(err)
end
end
skynet.dispatch("lua", function(_,_,...)
ret_pack(pcall(challenge, ...))
end)
end
local function launch_master( )
skynet.dispatch("lua", function(session, address, cmd, ...)
local f = command[cmd]
if f then
skynet.ret(skynet.pack(f(...)))
else
error(string.format("Unknown command %s", tostring(cmd)))
end
end)
skynet.register ".athleticserver"
for i=1,10 do
table.insert(slave, skynet.newservice(SERVICE_NAME))
end
end
skynet.start(function()
local athleticmaster = skynet.localname(".athleticserver")
if athleticmaster then
launch_slave()
else
launch_master()
end
end)
|
snet.Callback('bgn_sv_unit_test_mod_enabled', function(ply)
if GetConVar('bgn_enable'):GetBool() then
ply:ConCommand('bgn_unit_test_add_result "Addon functionality is active" "yes"')
else
ply:ConCommand('bgn_unit_test_add_result "Addon functionality is active" "no"')
end
end).Protect() |
vim.g.colors_name = "one-nvim"
if vim.o.background == "dark" then
--[[
Dark Colors
@syntax-hue: 220;
@syntax-saturation: 13%;
@syntax-brightness: 18%;
@syntax-fg: @mono-1;
@syntax-gutter-background-color-selected: lighten(@syntax-bg, 8%);
for color in $(cat colors/one-nvim.vim | head -n 41 | tail -n 28 | cut -d '#' -f2 | cut -d '"' -f1); do hex2xterm $color | grep 'Hexadecimal\|xterm256'; done
--]]
mono_1 = {"#abb2bf", 249, "mono_1"} -- hsl(@syntax-hue, 14%, 71%);
mono_2 = {"#828997", 245, "mono_2"} -- hsl(@syntax-hue, 9%, 55%);
mono_3 = {"#5c6370", 241, "mono_3"} -- hsl(@syntax-hue, 10%, 40%);
mono_4 = {"#4b5263", 240, "mono_4"} --
hue_1 = {"#56b6c2", 73, "hue_1"} -- hsl(187, 47%, 55%);
hue_2 = {"#61afef", 75, "hue_2"} -- hsl(207, 82%, 66%);
hue_3 = {"#c678dd", 176, "hue_3"} -- hsl(286, 60%, 67%);
hue_4 = {"#98c379", 108, "hue_4"} -- hsl( 95, 38%, 62%);
hue_5 = {"#e06c75", 168, "hue_5"} -- hsl(355, 65%, 65%);
hue_5_2 = {"#be5046", 131, "hue_5_2"} -- hsl( 5, 48%, 51%);
hue_6 = {"#d19a66", 173, "hue_6"} -- hsl( 29, 54%, 61%);
hue_6_2 = {"#e5c07b", 180, "hue_6_2"} -- hsl( 39, 67%, 69%);
syntax_bg = {"#282c34", 236, "syntax_bg"} -- hsl(@syntax-hue, @syntax-saturation, @syntax-brightness);
syntax_gutter = {"#636d83", 60, "syntax_gutter"} -- darken(@syntax-fg, 26%);
syntax_cursor = {"#2c323c", 237, "syntax_cursor"}
syntax_accent = {"#528bff", 69, "syntax_accent"} -- hsl(@syntax-hue, 100%, 66% );
vertsplit = {"#181a1f", 234, "vertsplit"}
special_grey = {"#3b4048", 237, "special_grey"}
visual_grey = {"#3e4452", 238, "visual_grey"}
pmenu = {"#333841", 237, "pmenu"}
term_black = {"#282c34", 17, "term_black"}
term_blue = {"#61afef", 75, "term_blue"}
term_cyan = {"#56b6c2", 247, "term_cyan"}
term_white = {"#dcdfe4", 188, "term_white"}
term_8 = {"#5d677a", 242, "term_8"}
syntax_color_added = {"#43d08a", 78, "syntax_color_added"} -- hsl(150, 60%, 54%);
syntax_color_modified = {"#e0c285", 250, "syntax_color_modified"} -- hsl(40, 60%, 70%);
syntax_color_removed = {"#e05252", 244, "syntax_color_removed"} -- hsl(0, 70%, 60%);
else
--[[
Light Colors
@syntax-hue: 230;
@syntax-saturation: 1%;
@syntax-brightness: 98%;
@syntax-fg: @mono-1;
@syntax-gutter-background-color-selected: darken(@syntax-bg, 8%);
for color in $(cat colors/one-nvim.vim | head -n 79 | tail -n 28 | cut -d '#' -f2 | cut -d '"' -f1); do hex2xterm $color | grep 'Hexadecimal\|xterm256'; done
--]]
mono_1 = {"#383A42", 239, "mono_1"} -- hsl(@syntax-hue, 8%, 24%);
mono_2 = {"#696c77", 242, "mono_2"} -- hsl(@syntax-hue, 6%, 44%);
mono_3 = {"#a0a1a7", 145, "mono_3"} -- hsl(@syntax-hue, 4%, 64%);
mono_4 = {"#c2c2c3", 250, "mono_4"} --
hue_1 = {"#0184bc", 31, "hue_1"} -- hsl(198, 99%, 37%);
hue_2 = {"#4078f2", 69, "hue_2"} -- hsl(221, 87%, 60%);
hue_3 = {"#a626a4", 127, "hue_3"} -- hsl(301, 63%, 40%);
hue_4 = {"#50a14f", 71, "hue_4"} -- hsl(119, 34%, 47%);
hue_5 = {"#e45649", 167, "hue_5"} -- hsl( 5, 74%, 59%);
hue_5_2 = {"#ca1243", 161, "hue_5_2"} -- hsl(344, 84%, 43%);
hue_6 = {"#986801", 94, "hue_6"} -- hsl(41, 99%, 30%);
hue_6_2 = {"#c18401", 136, "hue_6_2"} -- hsl(41, 99%, 38%)
syntax_bg = {"#fafafa", 255, "syntax_bg"} -- hsl(@syntax-hue, @syntax-saturation, @syntax-brightness);
syntax_gutter = {"#9e9e9e", 247, "syntax_gutter"} -- darken(@syntax-bg, 36%);
syntax_cursor = {"#f0f0f0", 254, "syntax_cursor"}
syntax_accent = {"#526fff", 63, "syntax_accent"} -- hsl(@syntax-hue, 100%, 66% );
vertsplit = {"#e7e9e1", 188, "vertsplit"}
special_grey = {"#d3d3d3", 252, "special_grey"}
visual_grey = {"#d0d0d0", 251, "visual_grey"}
pmenu = {"#dfdfdf", 253, "pmenu"}
term_black = {"#383a42", 237, "term_black"}
term_blue = {"#0184bc", 31, "term_blue"}
term_cyan = {"#0997b3", 243, "term_cyan"}
term_white = {"#fafafa", 231, "term_white"}
term_8 = {"#4f525e", 240, "term_8"}
syntax_color_added = {"#2db448", 65, "syntax_color_added"} -- hsl(132, 60%, 44%);
syntax_color_modified = {"#f2a60d", 137, "syntax_color_modified"} -- hsl(40, 90%, 50%);
syntax_color_removed = {"#ff1414", 88, "syntax_color_removed"} -- hsl(0, 100%, 54%);
end
-- Common
local pink = {"#d291e4", 251, "pink"}
syntax_color_renamed = {"#33a0ff", 75, "syntax_color_renamed"} -- hsl(208, 100%, 60%);
-- Vim Primary Colors
--[[
Mentioned here https://github.com/Th3Whit3Wolf/onebuddy/pull/7
vim-startify and maybe more plugins rely on these colors
--]]
Red = {"#e88388", 174, "Red"}
DarkRed = {"#e06c75", 168, "DarkRed"}
Blue = {"#61afef", 75, "Blue"}
DarkBlue = {"#528bff", 69, "DarkBlue"}
Green = {"#98c379", 114, "Green"}
DarkGreen = {"#50a14f", 71, "DarkGreen"}
Orange = {"#d19a66", 173, "Orange"}
DarkOrange = {"#c18401", 136, "DarkOrange"}
Yellow = {"#e5c07b", 180, "Yellow"}
DarkYellow = {"#986801", 94, "DarkYellow"}
Purple = {"#a626a4", 127, "Purple"}
Violet = {"#b294bb", 139, "Violet"}
Magenta = {"#ff80ff", 213, "Magenta"}
DarkMagenta = {"#a626a4", 127, "DarkMagenta"}
Black = {"#333841", 59, "Black"}
Grey = {"#636d83", 60, "Grey"}
White = {"#f2e5bc", 223, "White"}
Cyan = {"#8abeb7", 109, "Cyan"}
DarkCyan = {"#80a0ff", 111, "DarkCyan"}
Aqua = {"#8ec07c", 108, "Aqua"}
--[[ DO NOT EDIT `BG` NOR `FG`. ]]
local BG = "bg"
local FG = "fg"
local NONE = {}
--[[ These are the ones you should edit. ]]
-- This is the only highlight that must be defined separately.
local highlight_group_normal = {fg = mono_1, bg = syntax_bg}
local normal = (function()
if vim.g.one_nvim_transparent_bg ~= true then
return { fg = mono_1, bg = syntax_bg }
else
return { fg = mono_1, bg = NONE }
end
end)()
-- This is where the rest of your highlights should go.
local highlight_groups = {
-------------------------------------------------------------
-- Syntax Groups (descriptions and ordering from `:h w18`) --
-------------------------------------------------------------
Normal = normal,
NormalFloat = normal,
bold = { style = 'bold'},
ColorColumn = { fg = none, bg = syntax_cursor },
Conceal = { fg = mono_4, bg = syntax_bg },
Cursor = { fg = none, bg = syntax_accent },
CursorIM = { fg = none},
CursorColumn = { fg = none, bg = syntax_cursor },
CursorLine = { fg = none, bg = syntax_cursor },
Directory = { fg = hue_2 },
ErrorMsg = { fg = hue_5, bg = syntax_bg },
VertSplit = { fg = vertsplit },
FloatBorder = { fg = mono_1, bg = none},
Folded = { fg = mono_3, bg = syntax_bg },
FoldColumn = { fg = mono_3, bg = syntax_cursor },
IncSearch = { fg = hue_6, bg = mono_3 },
LineNr = { fg = mono_4 },
CursorLineNr = { fg = mono_1, bg = syntax_cursor },
MatchParen = { fg = hue_5, bg = syntax_cursor, style = 'underline,bold' },
Italic = { fg = none, style = 'italic'},
ModeMsg = { fg = mono_1 },
MoreMsg = { fg = mono_1 },
NonText = { fg = mono_3 },
PMenu = { fg = none, bg = pmenu },
PMenuSel = { fg = none, bg = mono_4 },
PMenuSbar = { fg = none, bg = syntax_bg },
PMenuThumb = { fg = none, bg = mono_1 },
Question = { fg = hue_2 },
Search = { fg = syntax_bg, bg = hue_6_2 },
SpecialKey = { fg = special_grey},
Whitespace = { fg = special_grey},
StatusLine = { fg = mono_1, bg = syntax_cursor },
StatusLineNC = { fg = mono_3 },
TabLine = { fg = mono_2, bg = visual_grey},
TabLineFill = { fg = mono_3, bg = visual_grey},
TabLineSel = { fg = syntax_bg, bg = hue_2 },
Title = { fg = mono_1, bg = none, style = 'bold'},
Visual = { fg = none, bg = visual_grey},
VisualNOS = { fg = none, bg = visual_grey},
WarningMsg = { fg = hue_5 },
TooLong = { fg = hue_5 },
WildMenu = { fg = mono_1, bg = mono_3 },
SignColumn = { fg = none, bg = syntax_bg },
Special = { fg = hue_2 },
---------------------------
-- Vim Help Highlighting --
---------------------------
helpCommand = { fg = hue_6_2 },
helpExample = { fg = hue_6_2 },
helpHeader = { fg = mono_1, style = 'bold'},
helpSectionDelim = { fg = mono_3,},
----------------------------------
-- Standard Syntax Highlighting --
----------------------------------
Comment = { fg = mono_3, style = 'italic'},
Constant = { fg = hue_4, bg = none},
String = { fg = hue_4, bg = none},
Character = { fg = hue_4, bg = none},
Number = { fg = hue_6, bg = none},
Boolean = { fg = hue_6, bg = none},
Float = { fg = hue_6, bg = none},
Identifier = { fg = hue_5, bg = none},
Function = { fg = hue_2, bg = none},
Statement = { fg = hue_3, bg = none},
Conditional = { fg = hue_3, bg = none},
Repeat = { fg = hue_3, bg = none},
Label = { fg = hue_3, bg = none},
Operator = { fg = syntax_accent },
Keyword = { fg = hue_5, bg = none},
Exception = { fg = hue_3, bg = none},
PreProc = { fg = hue_6_2, bg = none},
Include = { fg = hue_2, bg = none},
Define = { fg = hue_3, bg = none},
Macro = { fg = hue_3, bg = none},
PreCondit = { fg = hue_6_2, bg = none},
Type = { fg = hue_6_2, bg = none},
StorageClass = { fg = hue_6_2, bg = none},
Structure = { fg = hue_6_2, bg = none},
Typedef = { fg = hue_6_2, bg = none},
Special = { fg = hue_2, bg = none},
SpecialChar = { fg = none},
Tag = { fg = none},
Delimiter = { fg = none},
SpecialComment = { fg = none},
Debug = { fg = none},
Underlined = { fg = none, style = 'underline' },
Ignore = { fg = none},
Error = { fg = hue_5, bg = mono_3, style = 'bold'},
Todo = { fg = hue_3, bg = mono_3 },
-----------------------
-- Diff Highlighting --
-----------------------
DiffAdd = { fg = syntax_color_added, bg = visual_grey},
DiffChange = { fg = syntax_color_modified, bg = visual_grey},
DiffDelete = { fg = syntax_color_removed, bg = visual_grey},
DiffText = { fg = hue_2, bg = visual_grey},
DiffAdded = { fg = hue_4, bg = visual_grey},
DiffFile = { fg = hue_5, bg = visual_grey},
DiffNewFile = { fg = hue_4, bg = visual_grey},
DiffLine = { fg = hue_2, bg = visual_grey},
DiffRemoved = { fg = hue_5, bg = visual_grey},
---------------------------
-- Filetype Highlighting --
---------------------------
-- Asciidoc
asciidocListingBlock = { fg = mono_2 },
-- C/C++ highlighting
cInclude = { fg = hue_3 },
cPreCondit = { fg = hue_3 },
cPreConditMatch = { fg = hue_3 },
cType = { fg = hue_3 },
cStorageClass = { fg = hue_3 },
cStructure = { fg = hue_3 },
cOperator = { fg = hue_3 },
cStatement = { fg = hue_3 },
cTODO = { fg = hue_3 },
cConstant = { fg = hue_6 },
cSpecial = { fg = hue_1 },
cSpecialCharacter = { fg = hue_1 },
cString = { fg = hue_4 },
cppType = { fg = hue_3 },
cppStorageClass = { fg = hue_3 },
cppStructure = { fg = hue_3 },
cppModifier = { fg = hue_3 },
cppOperator = { fg = hue_3 },
cppAccess = { fg = hue_3 },
cppStatement = { fg = hue_3 },
cppConstant = { fg = hue_5 },
cCppString = { fg = hue_4 },
-- Cucumber
cucumberGiven = { fg = hue_2 },
cucumberWhen = { fg = hue_2 },
cucumberWhenAnd = { fg = hue_2 },
cucumberThen = { fg = hue_2 },
cucumberThenAnd = { fg = hue_2 },
cucumberUnparsed = { fg = hue_6 },
cucumberFeature = { fg = hue_5, style = 'bold'},
cucumberBackground = { fg = hue_3, style = 'bold'},
cucumberScenario = { fg = hue_3, style = 'bold'},
cucumberScenarioOutline = { fg = hue_3, style = 'bold'},
cucumberTags = { fg = mono_3, style = 'bold'},
cucumberDelimiter = { fg = mono_3, style = 'bold'},
-- CSS/Sass
cssAttrComma = { fg = hue_3 },
cssAttributeSelector = { fg = hue_4 },
cssBraces = { fg = mono_2 },
cssClassName = { fg = hue_6 },
cssClassNameDot = { fg = hue_6 },
cssDefinition = { fg = hue_3 },
cssFontAttr = { fg = hue_6 },
cssFontDescriptor = { fg = hue_3 },
cssFunctionName = { fg = hue_2 },
cssIdentifier = { fg = hue_2 },
cssImportant = { fg = hue_3 },
cssInclude = { fg = mono_1 },
cssIncludeKeyword = { fg = hue_3 },
cssMediaType = { fg = hue_6 },
cssProp = { fg = hue_1 },
cssPseudoClassId = { fg = hue_6 },
cssSelectorOp = { fg = hue_3 },
cssSelectorOp2 = { fg = hue_3 },
cssStringQ = { fg = hue_4 },
cssStringQQ = { fg = hue_4 },
cssTagName = { fg = hue_5 },
cssAttr = { fg = hue_6 },
sassAmpersand = { fg = hue_5 },
sassClass = { fg = hue_6_2 },
sassControl = { fg = hue_3 },
sassExtend = { fg = hue_3 },
sassFor = { fg = mono_1 },
sassProperty = { fg = hue_1 },
sassFunction = { fg = hue_1 },
sassId = { fg = hue_2 },
sassInclude = { fg = hue_3 },
sassMedia = { fg = hue_3 },
sassMediaOperators = { fg = mono_1 },
sassMixin = { fg = hue_3 },
sassMixinName = { fg = hue_2 },
sassMixing = { fg = hue_3 },
scssSelectorName = { fg = hue_6_2 },
-- Elixir highlighting
elixirModuleDefine = 'Define',
elixirAlias = { fg = hue_6_2 },
elixirAtom = { fg = hue_1 },
elixirBlockDefinition = { fg = hue_3 },
elixirModuleDeclaration = { fg = hue_6 },
elixirInclude = { fg = hue_5 },
elixirOperator = { fg = hue_6 },
-- Git and git related plugins
gitcommitComment = { fg = mono_3 },
gitcommitUnmerged = { fg = hue_4 },
gitcommitOnBranch = { fg = none},
gitcommitBranch = { fg = hue_3 },
gitcommitDiscardedType = { fg = hue_5 },
gitcommitSelectedType = { fg = hue_4 },
gitcommitHeader = { fg = none},
gitcommitUntrackedFile = { fg = hue_1 },
gitcommitDiscardedFile = { fg = hue_5 },
gitcommitSelectedFile = { fg = hue_4 },
gitcommitUnmergedFile = { fg = hue_6_2 },
gitcommitFile = { fg = none},
gitcommitNoBranch = 'gitcommitBranch',
gitcommitUntracked = 'gitcommitComment',
gitcommitDiscarded = 'gitcommitComment',
gitcommitDiscardedArrow = 'gitcommitDiscardedFile',
gitcommitSelectedArrow = 'gitcommitSelectedFile',
gitcommitUnmergedArrow = 'gitcommitUnmergedFile',
SignifySignAdd = { fg = syntax_color_added },
SignifySignChange = { fg = syntax_color_modified },
SignifySignDelete = { fg = syntax_color_removed },
GitGutterAdd = 'SignifySignAdd',
GitGutterChange = 'SignifySignChange',
GitGutterDelete = 'SignifySignDelete',
GitSignsAdd = 'SignifySignAdd',
GitSignsChange = 'SignifySignChange',
GitSignsDelete = 'SignifySignDelete',
-- Go
goDeclaration = { fg = hue_3 },
goField = { fg = hue_5 },
goMethod = { fg = hue_1 },
goType = { fg = hue_3 },
goUnsignedInts = { fg = hue_1 },
-- Haskell highlighting
haskellDeclKeyword = { fg = hue_2 },
haskellType = { fg = hue_4 },
haskellWhere = { fg = hue_5 },
haskellImportKeywords = { fg = hue_2 },
haskellOperators = { fg = hue_5 },
haskellDelimiter = { fg = hue_2 },
haskellIdentifier = { fg = hue_6 },
haskellKeyword = { fg = hue_5 },
haskellNumber = { fg = hue_1 },
haskellString = { fg = hue_1 },
-- HTML
htmlArg = { fg = hue_6 },
htmlTagName = { fg = hue_5 },
htmlTagN = { fg = hue_5 },
htmlSpecialTagName = { fg = hue_5 },
htmlTag = { fg = mono_2 },
htmlEndTag = { fg = mono_2 },
MatchTag = { fg = hue_5, bg = syntax_cursor, style = 'bold,underline'},
-- JavaScript
coffeeString = { fg = hue_4 },
javaScriptBraces = { fg = mono_2 },
javaScriptFunction = { fg = hue_3 },
javaScriptIdentifier = { fg = hue_3 },
javaScriptNull = { fg = hue_6 },
javaScriptNumber = { fg = hue_6 },
javaScriptRequire = { fg = hue_1 },
javaScriptReserved = { fg = hue_3 },
-- httpc.//github.com/pangloss/vim-javascript
jsArrowFunction = { fg = hue_3 },
jsBraces = { fg = mono_2 },
jsClassBraces = { fg = mono_2 },
jsClassKeywords = { fg = hue_3 },
jsDocParam = { fg = hue_2 },
jsDocTags = { fg = hue_3 },
jsFuncBraces = { fg = mono_2 },
jsFuncCall = { fg = hue_2 },
jsFuncParens = { fg = mono_2 },
jsFunction = { fg = hue_3 },
jsGlobalObjects = { fg = hue_6_2 },
jsModuleWords = { fg = hue_3 },
jsModules = { fg = hue_3 },
jsNoise = { fg = mono_2 },
jsNull = { fg = hue_6 },
jsOperator = { fg = hue_3 },
jsParens = { fg = mono_2 },
jsStorageClass = { fg = hue_3 },
jsTemplateBraces = { fg = hue_5_2 },
jsTemplateVar = { fg = hue_4 },
jsThis = { fg = hue_5 },
jsUndefined = { fg = hue_6 },
jsObjectValue = { fg = hue_2 },
jsObjectKey = { fg = hue_1 },
jsReturn = { fg = hue_3 },
-- httpc.//github.com/othree/yajs.vim
javascriptArrowFunc = { fg = hue_3 },
javascriptClassExtends = { fg = hue_3 },
javascriptClassKeyword = { fg = hue_3 },
javascriptDocNotation = { fg = hue_3 },
javascriptDocParamName = { fg = hue_2 },
javascriptDocTags = { fg = hue_3 },
javascriptEndColons = { fg = mono_3 },
javascriptExport = { fg = hue_3 },
javascriptFuncArg = { fg = mono_1 },
javascriptFuncKeyword = { fg = hue_3 },
javascriptIdentifier = { fg = hue_5 },
javascriptImport = { fg = hue_3 },
javascriptObjectLabel = { fg = mono_1 },
javascriptOpSymbol = { fg = hue_1 },
javascriptOpSymbols = { fg = hue_1 },
javascriptPropertyName = { fg = hue_4 },
javascriptTemplateSB = { fg = hue_5_2 },
javascriptVariable = { fg = hue_3 },
-- JSON
jsonCommentError = { fg = mono_1 },
jsonKeyword = { fg = hue_5 },
jsonQuote = { fg = mono_3 },
jsonTrailingCommaError = { fg = hue_5, style = 'reverse' },
jsonMissingCommaError = { fg = hue_5, style = 'reverse' },
jsonNoQuotesError = { fg = hue_5, style = 'reverse' },
jsonNumError = { fg = hue_5, style = 'reverse' },
jsonString = { fg = hue_4 },
jsonBoolean = { fg = hue_3 },
jsonNumber = { fg = hue_6 },
jsonStringSQError = { fg = hue_5, style = 'reverse' },
jsonSemicolonError = { fg = hue_5, style = 'reverse' },
-- Markdown
markdownUrl = { fg = mono_3, stlye = 'underline' },
markdownBold = { fg = hue_6, style = 'bold' },
markdownItalic = { fg = hue_6, style = 'italic' },
markdownCode = { fg = hue_4 },
markdownCodeBlock = { fg = hue_5 },
markdownCodeDelimiter = { fg = hue_4 },
markdownHeadingDelimiter = { fg = hue_5_2 },
markdownH1 = { fg = hue_5 },
markdownH2 = { fg = hue_5 },
markdownH3 = { fg = hue_5 },
markdownH3 = { fg = hue_5 },
markdownH4 = { fg = hue_5 },
markdownH5 = { fg = hue_5 },
markdownH6 = { fg = hue_5 },
markdownListMarker = { fg = hue_5 },
-- PHP
phpClass = { fg = hue_6_2 },
phpFunction = { fg = hue_2 },
phpFunctions = { fg = hue_2 },
phpInclude = { fg = hue_3 },
phpKeyword = { fg = hue_3 },
phpParent = { fg = mono_3 },
phpType = { fg = hue_3 },
phpSuperGlobals = { fg = hue_5 },
-- Pug (Formerly Jade)
pugAttributesDelimiter = { fg = hue_6 },
pugClass = { fg = hue_6 },
pugDocType = { fg = mono_3, style = 'italic'},
pugTag = { fg = hue_5 },
-- PureScript
purescriptKeyword = { fg = hue_3 },
purescriptModuleName = { fg = mono_1 },
purescriptIdentifier = { fg = mono_1 },
purescriptType = { fg = hue_6_2 },
purescriptTypeVar = { fg = hue_5 },
purescriptConstructor = { fg = hue_5 },
purescriptOperator = { fg = mono_1 },
-- Python
pythonImport = { fg = hue_3 },
pythonBuiltin = { fg = hue_1 },
pythonStatement = { fg = hue_3 },
pythonParam = { fg = hue_6 },
pythonEscape = { fg = hue_5 },
pythonSelf = { fg = mono_2, style = 'italic'},
pythonClass = { fg = hue_2 },
pythonOperator = { fg = hue_3 },
pythonEscape = { fg = hue_5 },
pythonFunction = { fg = hue_2 },
pythonKeyword = { fg = hue_2 },
pythonModule = { fg = hue_3 },
pythonStringDelimiter = { fg = hue_4 },
pythonSymbol = { fg = hue_1 },
-- Ruby
rubyBlock = { fg = hue_3 },
rubyBlockParameter = { fg = hue_5 },
rubyBlockParameterList = { fg = hue_5 },
rubyCapitalizedMethod = { fg = hue_3 },
rubyClass = { fg = hue_3 },
rubyConstant = { fg = hue_6_2 },
rubyControl = { fg = hue_3 },
rubyDefine = { fg = hue_3 },
rubyEscape = { fg = hue_5 },
rubyFunction = { fg = hue_2 },
rubyGlobalVariable = { fg = hue_5 },
rubyInclude = { fg = hue_2 },
rubyIncluderubyGlobalVariable = { fg = hue_5 },
rubyInstanceVariable = { fg = hue_5 },
rubyInterpolation = { fg = hue_1 },
rubyInterpolationDelimiter = { fg = hue_5 },
rubyKeyword = { fg = hue_2 },
rubyModule = { fg = hue_3 },
rubyPseudoVariable = { fg = hue_5 },
rubyRegexp = { fg = hue_1 },
rubyRegexpDelimiter = { fg = hue_1 },
rubyStringDelimiter = { fg = hue_4 },
rubySymbol = { fg = hue_1 },
-- Spelling
SpellBad = { fg = mono_3, style = 'undercurl'},
SpellLocal = { fg = mono_3, style = 'undercurl'},
SpellCap = { fg = mono_3, style = 'undercurl'},
SpellRare = { fg = mono_3, style = 'undercurl'},
-- Vim
vimCommand = { fg = hue_3 },
vimCommentTitle = { fg = mono_3, style = 'bold'},
vimFunction = { fg = hue_1 },
vimFuncName = { fg = hue_3 },
vimHighlight = { fg = hue_2 },
vimLineComment = { fg = mono_3, style = 'italic'},
vimParenSep = { fg = mono_2 },
vimSep = { fg = mono_2 },
vimUserFunc = { fg = hue_1 },
vimVar = { fg = hue_5 },
-- XML
xmlAttrib = { fg = hue_6_2 },
xmlEndTag = { fg = hue_5 },
xmlTag = { fg = hue_5 },
xmlTagName = { fg = hue_5 },
-- ZSH
zshCommands = { fg = mono_1 },
zshDeref = { fg = hue_5 },
zshShortDeref = { fg = hue_5 },
zshFunction = { fg = hue_1 },
zshKeyword = { fg = hue_3 },
zshSubst = { fg = hue_5 },
zshSubstDelim = { fg = mono_3 },
zshTypes = { fg = hue_3 },
zshVariableDef = { fg = hue_6 },
-- Rust
rustExternCrate = { fg = hue_5, style = 'bold'},
rustIdentifier = { fg = hue_2 },
rustDeriveTrait = { fg = hue_4 },
SpecialComment = { fg = mono_3 },
rustCommentLine = { fg = mono_3 },
rustCommentLineDoc = { fg = mono_3 },
rustCommentLineDocError = { fg = mono_3 },
rustCommentBlock = { fg = mono_3 },
rustCommentBlockDoc = { fg = mono_3 },
rustCommentBlockDocError = { fg = mono_3 },
-- Man
manTitle = 'String',
manFooter = { fg = mono_3 },
-------------------------
-- Plugin Highlighting --
-------------------------
-- ALE (Asynchronous Lint Engine)
ALEWarningSign = { fg = hue_6_2 },
ALEErrorSign = { fg = hue_5 },
-- Neovim NERDTree Background fix
NERDTreeFile = { fg = mono_1 },
-- Coc.nvim
CocFloating = { bg = none },
NormalFloating = { bg = none },
-----------------------------
-- LSP Highlighting --
-----------------------------
LspDiagnosticsDefaultError = { fg = hue_5 },
LspDiagnosticsDefaultWarning = { fg = hue_6_2 },
LspDiagnosticsDefaultInformation = { fg = hue_1 },
LspDiagnosticsDefaultHint = { fg = hue_4 },
LspDiagnosticsVirtualTextError = { fg = hue_5 },
LspDiagnosticsVirtualTextWarning = { fg = hue_6_2 },
LspDiagnosticsVirtualTextInformation = { fg = hue_1 },
LspDiagnosticsVirtualTextHint = { fg = hue_4 },
LspDiagnosticsUnderlineError = { fg = hue_5 , style = 'underline' },
LspDiagnosticsUnderlineWarning = { fg = hue_6_2 , style = 'underline' },
LspDiagnosticsUnderlineInformation = { fg = hue_1 , style = 'underline' },
LspDiagnosticsUnderlineHint = { fg = hue_4 , style = 'underline' },
LspDiagnosticsFloatingError = { fg = hue_5 , bg = pmenu },
LspDiagnosticsFloatingWarning = { fg = hue_6_2 , bg = pmenu },
LspDiagnosticsFloatingInformation = { fg = hue_1 , bg = pmenu },
LspDiagnosticsFloatingHint = { fg = hue_4 , bg = pmenu },
LspDiagnosticsSignError = { fg = hue_5 },
LspDiagnosticsSignWarning = { fg = hue_6_2 },
LspDiagnosticsSignInformation = { fg = hue_1 },
LspDiagnosticsSignHint = { fg = hue_4 },
LspReferenceText = { style = 'reverse' },
LspReferenceRead = { style = 'reverse' },
LspReferenceWrite = { fg = hue_6_2, style = 'reverse' },
-----------------------------
-- TreeSitter Highlighting --
-----------------------------
TSAnnotation = 'PreProc',
TSAttribute = 'PreProc',
TSBoolean = 'Boolean',
TSCharacter = 'Character',
TSComment = 'Comment',
TSConditional = 'Conditional',
TSConstant = 'Constant',
TSConstBuiltin = 'Special',
TSConstMacro = 'Define',
TSConstructor = 'Special',
TSEmphasis = 'Italic',
TSError = 'Error',
TSException = 'Exception',
TSField = 'Normal',
TSFloat = 'Float',
TSFunction = 'Function',
TSFuncBuiltin = 'Special',
TSFuncMacro = 'Macro',
TSInclude = 'Include',
TSKeyword = 'Keyword',
TSKeywordFunction = 'Keyword',
TSKeywordOperator = 'Operator',
TSLabel = 'Label',
TSLiteral = 'String',
TSMethod = 'Function',
TSNamespace = 'Include',
TSNumber = 'Number',
TSOperator = 'Operator',
TSParameter = 'Identifier',
TSParameterReference = 'Identifier',
TSProperty = 'Identifier',
TSPunctBracket = 'Delimiter',
TSPunctDelimiter = 'Delimiter',
TSPunctSpecial = 'Delimiter',
TSRepeat = 'Repeat',
TSString = 'String',
TSStringEscape = 'SpecialChar',
TSStringRegex = 'String',
TSStrong = 'bold',
TSTag = 'Label',
TSTagDelimiter = 'Label',
-- TSText = { fg = hue_6_2 },
TSTitle = 'Title',
TSType = 'Type',
TSTypeBuiltin = 'Type',
TSUnderline = 'Underlined',
TSURI = 'Underlined',
TSVariableBuiltin = 'Special',
}
local terminal_ansi_colors = {
[0] = term_black,
[1] = hue_5,
[2] = hue_4,
[3] = hue_6_2,
[4] = term_blue,
[5] = hue_3,
[6] = term_cyan,
[7] = term_white,
[8] = term_8,
[9] = hue_5,
[10] = hue_4,
[11] = hue_6_2,
[12] = term_blue,
[13] = hue_3,
[14] = term_cyan,
[15] = term_white
}
require(vim.g.colors_name)(highlight_group_normal, highlight_groups, terminal_ansi_colors)
-- Thanks to Iron-E (https://github.com/Iron-E) for the template (Iron-E/nvim-highlite).
-- vim: ft=lua
|
function idx2key(file)
local f = io.open(file,'r')
local t = {}
for line in f:lines() do
local c = {}
for w in line:gmatch'([^%s]+)' do
table.insert(c, w)
end
t[tonumber(c[2])] = c[1]
end
return t
end
function src_words(file)
local f = io.open(file,'r')
local t = {}
for line in f:lines() do
local c = {}
for w in line:gmatch'([^%s]+)' do
table.insert(c, w)
end
t[c[1]] = true
end
return t
end
function flip_table(u)
local t = {}
for key, value in pairs(u) do
t[value] = key
end
return t
end
|
---@class VehicleWindow : zombie.vehicles.VehicleWindow
---@field protected part VehiclePart
---@field protected health int
---@field protected openable boolean
---@field protected open boolean
---@field protected openDelta float
VehicleWindow = {}
---@public
---@param arg0 ByteBuffer
---@return void
function VehicleWindow:save(arg0) end
---@public
---@param arg0 ByteBuffer
---@param arg1 int
---@return void
function VehicleWindow:load(arg0, arg1) end
---@public
---@param arg0 float
---@return void
function VehicleWindow:setOpenDelta(arg0) end
---@public
---@return float
function VehicleWindow:getOpenDelta() end
---@public
---@return boolean
function VehicleWindow:isHittable() end
---@public
---@return boolean
function VehicleWindow:isOpenable() end
---@public
---@param arg0 VehicleScript.Window
---@return void
function VehicleWindow:init(arg0) end
---@public
---@return boolean
function VehicleWindow:isOpen() end
---@public
---@param arg0 int
---@return void
function VehicleWindow:damage(arg0) end
---@public
---@param arg0 IsoGameCharacter
---@return void
function VehicleWindow:hit(arg0) end
---@public
---@param arg0 boolean
---@return void
function VehicleWindow:setOpen(arg0) end
---@public
---@return int
function VehicleWindow:getHealth() end
---@public
---@param arg0 int
---@return void
function VehicleWindow:setHealth(arg0) end
---@public
---@return boolean
function VehicleWindow:isDestroyed() end
|
-- Configuration file for the Fusion-Power mod
-- Enable features of the mod by true , disable pieces by false
-- Please note that the case matters, therefore True is not true.
-- Dependencies are noted, if a dependency is not fulfilled, the feature is skipped.
config =
{
fubelts =
{
extendedBelts = true,
alienBelt = true,
alienSuperBelt = true,
},
fuconstruction =
{
alienConstructionRobot = true,
alienLogisticRobot = true,
},
fudrill=
{
improvedDrill = true,
alienDrill = true, -- Depends on improvedDrill
},
fufusion=
{
deepWater = true,
fusion = true,
advancedFusion = true, -- Depends on fusion
},
fuoil=
{
coalOilPlant = true,
},
fuinserter=
{
fastLongInserter = true,
alienInserter = true,
alienSuperInserter = true, -- Depends on alien-inserter
},
futrain=
{
alienTrain = true,
},
fuweapon=
{
alienLaserTurret = true,
securityZone = true,
mobileSecurityZone = true,
},
} |
local ffi = require("ffi")
local cast = ffi.cast
local bxor = bit.bxor
local bnot = bit.bnot
local band = bit.band
local rshift = bit.rshift
local _M = {}
-- API versions
_M.API_VERSION_V0 = 0
_M.API_VERSION_V1 = 1
_M.API_VERSION_V2 = 2
_M.API_VERSION_V3 = 3
_M.API_VERSION_V4 = 4
_M.API_VERSION_V5 = 5
_M.API_VERSION_V6 = 6
_M.API_VERSION_V7 = 7
_M.API_VERSION_V8 = 8
_M.API_VERSION_V9 = 9
_M.API_VERSION_V10 = 10
_M.API_VERSION_V11 = 11
_M.API_VERSION_V12 = 12
_M.API_VERSION_V13 = 13
-- API keys
_M.ProduceRequest = 0
_M.FetchRequest = 1
_M.OffsetRequest = 2
_M.MetadataRequest = 3
_M.OffsetCommitRequest = 8
_M.OffsetFetchRequest = 9
_M.ConsumerMetadataRequest = 10
_M.SaslHandshakeRequest = 17
_M.ApiVersionsRequest = 18
_M.SaslAuthenticateRequest = 36
local crc32_t = ffi.new('const uint32_t[256]', (function()
local function init_lookup_table(crc)
local iteration = crc
for _=1,8 do
crc = band(crc, 1) == 1
and bxor(rshift(crc, 1), 0x82f63b78)
or rshift(crc, 1)
end
if iteration < 256 then
return crc, init_lookup_table(iteration + 1)
end
end
return init_lookup_table(0)
end)())
-- Generate and self-increment correlation IDs
-- The correlated is a table containing the correlation_id attribute
function _M.correlation_id(correlated)
local id = (correlated.correlation_id + 1) % 1073741824 -- 2^30
correlated.correlation_id = id
return id
end
-- The crc32c algorithm is implemented from the following url.
-- https://gist.github.com/bjne/ab9efaab585563418cb7462bb1254b6e
function _M.crc32c(buf, len, crc)
len = len or #buf
buf, crc = cast('const uint8_t*', buf), crc or 0
for i=0, len-1 do
crc = bnot(crc)
crc = bnot(bxor(rshift(crc, 8), crc32_t[bxor(crc % 256, buf[i])]))
end
return crc
end
return _M
|
local tbug = SYSTEMS:GetSystem("merTorchbug")
local TextButton = tbug.classes.TextButton
function TextButton:__init__(parent, name)
self.control = assert(parent:GetNamedChild(name))
self.label = assert(self.control:GetLabelControl())
self.padding = 0
self.onClicked = {}
local function onClicked(control, mouseButton)
local handler = self.onClicked[mouseButton]
if handler then
handler(self)
end
end
local function onScreenResized()
local text = self.label:GetText()
local width = self.label:GetStringWidth(text) / GetUIGlobalScale()
self.control:SetWidth(width + self.padding)
end
self.control:SetHandler("OnClicked", onClicked)
self.control:RegisterForEvent(EVENT_SCREEN_RESIZED, onScreenResized)
end
function TextButton:enableMouseButton(mouseButton)
self.control:EnableMouseButton(mouseButton, true)
end
function TextButton:fitText(text, padding)
local padding = padding or 0
local width = self.label:GetStringWidth(text) / GetUIGlobalScale()
self.control:SetText(text)
self.control:SetWidth(width + padding)
self.padding = padding
end
function TextButton:getText()
return self.label:GetText()
end
function TextButton:setMouseOverBackgroundColor(r, g, b, a)
local mouseOverBg = self.control:GetNamedChild("MouseOverBg")
if not mouseOverBg then
mouseOverBg = self.control:CreateControl("$(parent)MouseOverBg", CT_TEXTURE)
mouseOverBg:SetAnchorFill()
mouseOverBg:SetHidden(true)
end
mouseOverBg:SetColor(r, g, b, a)
end
|
local create = require("support.factory").create
local Ability = require("invokation.dota2.Ability")
local INVOKER = require("invokation.const.invoker")
describe("dota2.Ability", function()
describe("constructor", function()
it("initializes attributes", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_QUAS, index = 13})
local ability = Ability(entity)
assert.are.equal(INVOKER.ABILITY_QUAS, ability.name)
assert.are.equal(13, ability.index)
entity = create("dota_ability", {name = INVOKER.ABILITY_SUN_STRIKE, index = 31})
ability = Ability(entity)
assert.are.equal(INVOKER.ABILITY_SUN_STRIKE, ability.name)
assert.are.equal(31, ability.index)
entity = create("dota_item", {name = "item_blink"})
ability = Ability(entity)
assert.are.equal("item_blink", ability.name)
assert.are.equal(nil, ability.index)
end)
end)
describe("delegation", function()
it("delegates methods to underlying entity", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_QUAS, index = 13})
local ability = Ability(entity)
local delegated = {"GetDuration", "GetSpecialValueFor", "IsItem"}
for _, method in ipairs(delegated) do
local spy = spy.on(entity, method)
ability[method](ability)
assert.spy(spy).was.called(1)
end
end)
end)
describe("#IsOrbAbility", function()
describe("with item", function()
it("returns false", function()
local entity = create("dota_item", {name = "item_blink"})
local ability = Ability(entity)
assert.is_false(ability:IsOrbAbility())
end)
end)
describe("with non-orb ability", function()
it("returns false", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_SUN_STRIKE, index = 13})
local ability = Ability(entity)
assert.is_false(ability:IsOrbAbility())
end)
end)
describe("with orb ability", function()
it("returns true", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_QUAS, index = 13})
local ability = Ability(entity)
assert.is_true(ability:IsOrbAbility())
end)
end)
end)
describe("#IsInvocationAbility", function()
describe("with item", function()
it("returns false", function()
local entity = create("dota_item", {name = "item_blink"})
local ability = Ability(entity)
assert.is_false(ability:IsInvocationAbility())
end)
end)
describe("with non-orb ability", function()
it("returns false", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_SUN_STRIKE, index = 13})
local ability = Ability(entity)
assert.is_false(ability:IsInvocationAbility())
end)
end)
describe("with orb ability", function()
it("returns true", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_QUAS, index = 13})
local ability = Ability(entity)
assert.is_true(ability:IsInvocationAbility())
end)
end)
describe("with invoke ability", function()
it("returns true", function()
local entity = create("dota_ability", {name = INVOKER.ABILITY_INVOKE, index = 1})
local ability = Ability(entity)
assert.is_true(ability:IsInvocationAbility())
end)
end)
end)
end)
|
-- scaffolding entry point for sokol
return dofile("sokol.lua")
|
--ザ・アキュムレーター
--The Accumulator
--Scripted by Eerie Code
function c101002031.initial_effect(c)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c101002031.atkval)
c:RegisterEffect(e1)
end
function c101002031.atkfilter(c)
return c:IsFaceup() and c:IsType(TYPE_LINK)
end
function c101002031.atkval(e,c)
local g=Duel.GetMatchingGroup(c101002031.atkfilter,e:GetHandlerPlayer(),LOCATION_MZONE,LOCATION_MZONE,nil)
return g:GetSum(Card.GetLink)*300
end
|
function onSay(cid, words, param, channel)
local p = string.explode(param, ',')
if(param == "") then
doPlayerSendCancel(cid, "Command requires param.")
return true
end
if(words == "/pass") then
if(db.getResult("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(p[1]) .. ";"):getID() == -1) then
return doPlayerSendCancel(cid, "Sorry, but player [" .. p[1] .. "] does not exist.")
end
return db.executeQuery("UPDATE `accounts` SET `password` = '" .. p[2] .. "' WHERE name = '" .. p[1] .. "';") and doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have changed " .. p[1] .. "'s account password to " .. p[2] .. ".")
end
if(words == "/acc") then
if(db.getResult("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(p[1]) .. ";"):getID() == -1) then
return doPlayerSendCancel(cid, "Sorry, but player [" .. p[1] .. "] does not exist.")
elseif(db.getResult("SELECT `id` FROM `accounts` WHERE `name` = " .. db.escapeString(p[2]) .. ";"):getID() == 1) then
return doPlayerSendCancel(cid, "Sorry, but account [" .. p[2] .. "] already exists.")
end
return db.executeQuery("UPDATE `accounts` SET `name` = '" .. p[2] .. "' WHERE name = '" .. p[1] .. "';") and doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have changed " .. p[1] .. "'s account number to " .. p[2] .. ".")
end
if(words == "/rename") then
if(db.getResult("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(p[1]) .. ";"):getID() == -1) then
return doPlayerSendCancel(cid, "Sorry, but player [" .. p[1] .. "] does not exist.")
elseif(isPlayerBanished(p[1], PLAYERBAN_LOCK)) then
return doPlayerSendCancel(cid, "Sorry, but " .. p[1] .. " is name locked.")
elseif(db.getResult("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(p[2]) .. ";"):getID() == 1) then
return doPlayerSendCancel(cid, "Sorry, but the name [" .. p[2] .. "] already exists.")
end
return db.executeQuery("UPDATE `players` SET `name` = '" .. p[2] .. "' WHERE name = '" .. p[1] .. "';") and doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have changed " .. p[1] .. "'s name to " .. p[2] .. ".")
end
end |
return {
init_effect = "",
name = "2020英系活动 EX清除者 魔炮弹条及鱼雷护盾",
time = 0,
color = "blue",
picture = "",
desc = "",
stack = 1,
id = 8719,
last_effect = "",
effect_list = {
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "immuneMaxAreaLimit",
number = 1
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onAttach"
},
arg_list = {
buff_id = 8720,
target = "TargetSelf"
}
},
{
type = "BattleBuffAddBuff",
trigger = {
"onUpdate"
},
arg_list = {
buff_id = 8720,
target = "TargetSelf",
time = 41
}
}
}
}
|
local collect = require("nightfox.lib.collect")
local template = require("nightfox.util.template")
local M = {}
function M.load(spec)
local ovr = require("nightfox.override").groups
local config = require("nightfox.config").options
local editor = require("nightfox.group.editor").get(spec, config)
local syntax = require("nightfox.group.syntax").get(spec, config)
local result = collect.deep_extend(editor, syntax)
for name, opts in pairs(config.modules or {}) do
if type(opts) == "table" then
if opts.enable then
result = collect.deep_extend(result, require("nightfox.group.modules." .. name).get(spec, config, opts))
end
else
if opts then
result = collect.deep_extend(result, require("nightfox.group.modules." .. name).get(spec, config, {}))
end
end
end
return collect.deep_extend(result, template.parse(ovr, spec))
end
return M
|
ITEM.name = "9MM PISTOL"
ITEM.base = "base_wep"
ITEM.uniqueID = "hl2_pistol"
ITEM.category = nut.lang.Get("weapons_ranged")
ITEM.class = "hl2_r_pistol"
ITEM.type = "sidearm"
ITEM.model = Model( "models/Weapons/W_pistol.mdl" )
ITEM.desc = nut.lang.Get("desc_wep_9mm") |
local transform_ast = request('!.formats.lua.transform_ast')
return
function(self)
self.data_struc =
transform_ast(
self.data_struc,
{
keep_comments = self.keep_comments,
keep_unparsed_tail = self.keep_unparsed_tail,
}
)
self.is_ok = self:process_node(self.data_struc)
return self:get_result()
end
|
local h = {}
local s = require('pipes.socket')
function h.newserver(cfg, cb)
local ret, err
while(true)
do
local idSvr, e = s.listen({port=cfg.port})
if not idSvr then -- listen failed
err = e
break
end
s.accept(idSvr, function(id, host, port)
local obj = {id=id}
setmetatable(obj, {__index = h})
cb(obj, host, port)
end)
ret = {id = idSvr}
setmetatable(ret, {__index = h})
break
end
return ret, err
end
local function trim(str)
str = string.gsub(str, '^%s+', '')
str = string.gsub(str, '%s+$', '')
return str
end
local function parseKV(str, sep)
local pos = string.find(str, sep)
if not pos then return nil end
local key = string.sub(str, 1, pos - 1)
local val = string.sub(str, pos + 1)
key = trim(key)
val = trim(val)
if key == '' then
key = nil
end
if val == '' then
val = nil
end
return key, val
end
local function parseReq(id)
local msg, sz
local str = require('pipes_string')
local req
while(true)
do
-- read req-line: GET /url HTTP/1.0
msg = s.readline(id)
local arr = str.split(msg)
local method = arr[1]
local url = arr[2]
local ver = arr[3]
if method ~= 'GET' and method ~= 'POST' then
break
end
if ver ~= 'HTTP/1.1' then
break
end
-- read headers
local headers = {}
local e
while(true)
do
msg = s.readline(id)
if msg == '' then break end -- headers done
local k, v = parseKV(msg, ':')
if not k or k == '' then -- invalid header
e = 'invalid header: '..msg
break
end
headers[k] = v
end
if e then break end -- parse headers failed
req = {method=method, url=url, ver=ver, headers=headers}
break
end
return req
end
function h:readreq()
local id = self.id
if not id then
error('invalid http session')
end
if self._start then
return false, 'readreq has called'
end
s.start(id)
self._start = true
local ok, req = pcall(parseReq, id)
if not ok then
return false, req
end
if req.method == 'POST' then -- read req-body
end
return req
end
function h:resp(rsp)
local id = self.id
if not id then
error('invalid http session')
end
end
function h:close()
if self.id then
s.close(self.id)
self.id = nil
end
end
return h
|
--- === plugins.aftereffects.preferences ===
---
--- After Effects Preferences Panel
local require = require
local application = require "hs.application"
local dialog = require "hs.dialog"
local image = require "hs.image"
local osascript = require "hs.osascript"
local ae = require "cp.adobe.aftereffects"
local config = require "cp.config"
local html = require "cp.web.html"
local i18n = require "cp.i18n"
local applescript = osascript.applescript
local imageFromPath = image.imageFromPath
local infoForBundleID = application.infoForBundleID
local webviewAlert = dialog.webviewAlert
local mod = {}
-- scanEffects() -> none
-- Function
-- Scans After Effects to generate a list of installed effects.
--
-- Parameters:
-- * None
--
-- Returns:
-- * None
local function scanEffects()
if not ae:allowScriptsToWriteFilesAndAccessNetwork() then
webviewAlert(mod._manager.getWebview(), function() end, i18n("allowScriptsTurnedOff"), i18n("allowScriptsTurnedOffDescription"), i18n("ok"))
else
webviewAlert(mod._manager.getWebview(), function(result)
if result == i18n("ok") then
applescript([[
tell application id "]] .. ae:bundleID() .. [["
DoScriptFile "]] .. config.bundledPluginsPath .. [[/aftereffects/preferences/js/scaneffects.jsx"
end tell
]])
end
end, i18n("scanAfterEffectsDescription"), i18n("scanAfterEffectsDescriptionTwo"), i18n("ok"), i18n("cancel"))
end
end
local plugin = {
id = "aftereffects.preferences",
group = "aftereffects",
dependencies = {
["core.preferences.manager"] = "manager",
}
}
function plugin.init(deps)
mod._manager = deps.manager
local bundleID = ae:bundleID()
if infoForBundleID(bundleID) then
local panel = deps.manager.addPanel({
priority = 2041,
id = "aftereffects",
label = i18n("afterEffects"),
image = imageFromPath(config.bundledPluginsPath .. "/aftereffects/preferences/images/aftereffects.icns"),
tooltip = i18n("afterEffects"),
height = 230,
})
panel
:addHeading(1, i18n("effects"))
:addParagraph(2, html.span { class="tbTip" } ( i18n("effectsCacheDescription") .. "<br /><br />", false ).. "\n\n")
:addButton(3,
{
label = "Scan Effects",
width = 200,
onclick = scanEffects,
}
)
return panel
end
return mod
end
return plugin
|
local lfs = require"lfs"
function trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
function readConfig(path)
local readValues = false
local configTable = {}
for line in io.lines(path) do
line = trim(line)
if string.len(line) ~= 0 and not string.match(line, "^//") then
if string.match(line, "^\#copy_to_repo") then
readValues = true
else
if readValues then
for k, v in string.gmatch(line, "(.+)=(.+)") do
k = trim(k)
v = trim(v)
configTable[k] = v
end
end
end
end
end
return configTable
end
function createDir(path)
local attr = lfs.attributes(path)
if attr == nil then
assert(lfs.mkdir(path), "could not create " .. path)
end
end
function copyFiles(srcPath, tarPath)
createDir(tarPath)
for file in lfs.dir(srcPath) do
if file ~= "." and file ~= ".." then
local filePath = srcPath .. "\\" .. file
local attr = lfs.attributes(filePath)
if attr ~= nil then
if attr.mode == "directory" then
local targetFile = tarPath .. "\\" .. file
--print(targetFile)
lfs.mkdir(targetFile)
copyFiles(filePath, targetFile)
else
local input = assert(io.open(filePath, "rb"))
local targetFile = tarPath .. "\\" .. file
local output = assert(io.open(targetFile, "wb"))
local content = input:read("*all")
output:write(content)
input:close()
output:close()
end
else
print(file .. " could not be opened")
end
end
end
end
function main()
local configTable = readConfig("scripts_config.conf")
local sourceRootPath = configTable["src_root_path"]
local targetRootPath = configTable["tar_root_path"]
--print("source path: " .. sourceRootPath)
--print("target path: " .. targetRootPath)
for srcFile in string.gmatch(configTable["src_paths"], '([^,]+)') do
srcFile = trim(srcFile)
local sourceFile = sourceRootPath .. "\\" .. srcFile
local targetFile = targetRootPath .. "\\" .. srcFile
print("source path: " .. sourceFile)
print("target path: " .. targetFile)
copyFiles(sourceFile, targetFile)
end
end
main() |
--------------------------------------------------------------------------------
-- Class used by the Client entity to communicate to the Server.
--
-- The communication channel should be configured using the three ports:
-- - com_port: Used to receive broadcast messages from the Server entity.
-- - set_port: Used to send messages/request data to the Server entity.
-- - res_port: Used to receive a responce from a Server.
--------------------------------------------------------------------------------
local bus_client = {}
local zmq = require('lzmq')
local json = require('json')
local util = require('lib.util.util')
--------------------------------------------------------------------------------
-- Default Configuration
--------------------------------------------------------------------------------
local HOST = '127.0.0.1'
local COM_PORT = 5556
local SET_PORT = 5557
local RES_PORT = 5558
--------------------------------------------------------------------------------
--- Creates a new Bus Client instance.
--
-- @param opt An object that contains the configuration for this Bus Client. If
-- not provided, the default configurations will be set.
-- eg:
-- {id="Me", filter="server" host="localhost",
-- com_port=1, set_port=2, res_port=3}
-- @return table The new Bus Client instance.
function bus_client:new(opt)
local self = {}
setmetatable(self, {__index=bus_client})
opt = opt or {}
self.id = opt.id or 'client_id'
self.host = opt.host or HOST
self.com_port = opt.com_port or COM_PORT
self.set_port = opt.set_port or SET_PORT
self.res_port = opt.res_port or RES_PORT
self.filter = opt.filter or nil
return self
end
--- Prepares this Bus Server to be used.
-- Before sending/receiving messages, the method setup() should be called to
-- properly setup the socket configurations.
--
-- @return table The instance itself.
function bus_client:setup()
self.context = zmq.context()
self.sub_socket, err = self.context:socket(zmq.SUB)
zmq.assert(self.sub_socket, err)
if self.filter then self.sub_socket:subscribe(self.filter) end
self.sub_socket:connect('tcp://'..self.host..':'..self.com_port)
return self
end
--- Receives a message from the communication channel's Server
-- Tryies to get a message from the communication channel, checking the
-- 'com_port' for broadcast messages from the Server.
--
-- @param blocking If false, the method will check if there is a message and
-- then retrun the message, if it exists, or 'nil' if no message was
-- received. If true, the method will block the interpreter until a new
-- message arrives, which then is returned.
-- @return string The message, if exists, or nil, if no message was received.
function bus_client:check_income(blocking)
local raw_data = self.sub_socket:recv(blocking and nil or zmq.NOBLOCK)
if not raw_data then return nil end
local sender, msg = unpack(util.split(raw_data, ' ',true))
return json.decode(msg), sender
end
--- Send a message to the Server.
-- Send the given message to the Server of this communication channel, using the
-- 'set_port'.
--
-- @param msg A table or string containing the message.
-- @return table The instance itself.
function bus_client:send(data, type)
if not data then return end
local msg = {type=type or 'send', data=data, sender=self.id}
local set_socket, err = self.context:socket(zmq.PAIR)
zmq.assert(set_socket, err)
set_socket:connect('tcp://'..self.host..':'..self.set_port)
set_socket:send(json.encode(msg))
set_socket:close()
return self
end
--- Make a request for the Server.
-- When called, a message is sent to the Server indicating this Client has made
-- a request. The Client will stay blocked until the response from the Server is
-- received on the 'res_port', and then returned.
--
-- @param request A string indicating the request (eg. 'device_list')
-- @return table The response from the Server.
function bus_client:get(request)
if not request then return end
self:send(request, 'get')
local res_socket, err = self.context:socket(zmq.PAIR)
zmq.assert(res_socket, err)
res_socket:bind('tcp://'..self.host..':'..self.res_port)
local response = res_socket:recv()
res_socket:close()
return json.decode(response).data
end
return bus_client
|
--[[
Title: MCImporterChunkGenerator
Author(s): LiXizhi for lipeng's mcimporter dll
Date: 2015.11.17
Desc: it uses the ChunkGenerator interface to load the world dynamically from a mc world directory,
according to current player position.
-----------------------------------------------
NPL.load("(gl)Mod/MCImporterGenerator/MCImporterChunkGenerator.lua");
local MCImporterChunkGenerator = commonlib.gettable("Mod.MCImporterGenerator.MCImporterChunkGenerator");
ChunkGenerators:Register("MCImporter", MCImporterChunkGenerator);
-----------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/World/ChunkGenerator.lua");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine");
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local names = commonlib.gettable("MyCompany.Aries.Game.block_types.names");
local MCImporterChunkGenerator = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.World.ChunkGenerator"), commonlib.gettable("Mod.MCImporterGenerator.MCImporterChunkGenerator"))
-- singleton instance
local cur_generator;
local cur_chunk;
function MCImporterChunkGenerator:ctor()
-- use correct dll for different version.
if(ParaEngine.IsDebugging()) then
self.dll_path = "MCImporter_d.dll";
else
if(ParaEngine.GetAttributeObject():GetField("Is64BitsSystem", false)) then
self.dll_path = "MCImporter_64bits.dll";
else
self.dll_path = "MCImporter.dll";
end
end
end
-- @param world: WorldManager, if nil, it means a local generator.
-- @param seed: a number
function MCImporterChunkGenerator:Init(world, seed)
MCImporterChunkGenerator._super.Init(self, world, seed);
cur_generator = self;
self:LoadMCWorld();
return self;
end
function MCImporterChunkGenerator:OnExit()
MCImporterChunkGenerator._super.OnExit(self);
end
function MCImporterChunkGenerator:LoadMCWorld()
local src_path = self:GetWorld():GetSeedString();
NPL.call(self.dll_path, {cmd="loadmcworld", path = src_path});
if(not self.isworldloaded) then
LOG.std(nil, "info", "MCImporterChunkGenerator", "failed to load world at path %s", src_path);
else
LOG.std(nil, "info", "MCImporterChunkGenerator", "successfully load world at path %s", src_path);
end
local spawn_x, spawn_y, spawn_z = self:GetSpawnPosition();
local x, y, z = BlockEngine:real(spawn_x, spawn_y, spawn_z);
NPL.load("(gl)script/ide/timer.lua");
local mytimer = commonlib.Timer:new({callbackFunc = function(timer)
-- teleport player to this position.
_guihelper.MessageBox("Do you want to teleport to spawn position in mc world?", function(res)
if(res and res == _guihelper.DialogResult.Yes) then
-- EntityManager.GetPlayer():SetPosition(x,y,z);
EntityManager.GetPlayer():SetBlockPos(spawn_x, spawn_y, spawn_z);
end
end, _guihelper.MessageBoxButtons.YesNo);
end})
mytimer:Change(2000);
LOG.std(nil, "info", "MCImporterChunkGenerator", "src_path: %s spawn block pos(%d %d %d)", src_path, spawn_x, spawn_y, spawn_z);
end
-- protected virtual funtion:
-- generate chunk for the entire chunk column at x, z
function MCImporterChunkGenerator:GenerateChunkImp(chunk, x, z, external)
cur_generator = self;
cur_chunk = chunk;
-- make synchronous call to C++ dll to get all block in this chunk column.
NPL.call(self.dll_path, {cmd="GetChunkBlocks", callback="Mod/MCImporterGenerator/MCImporterChunkGenerator.lua", x = x, z = z});
end
-- get the player spawn position in the current world
-- @return: x,y,z in block world coordinate
function MCImporterChunkGenerator:GetSpawnPosition()
NPL.call(self.dll_path, {cmd="GetSpawnPosition", callback="Mod/MCImporterGenerator/MCImporterChunkGenerator.lua"});
return self.spawn_x, self.spawn_y, self.spawn_z;
end
function MCImporterChunkGenerator:LoadBlocksFromTable(chunk, x, z, blocks)
if(blocks.count and blocks.count>0) then
LOG.std(nil, "debug", "MCImporterChunkGenerator", "%d blocks in chunk: %d %d", blocks.count, x, z);
local blocks_x, blocks_y, blocks_z, blocks_tempId, blocks_data = blocks.x, blocks.y, blocks.z, blocks.tempId, blocks.data;
local i;
for i = 1, blocks.count do
local bx,by,bz,block_id, block_data = blocks_x[i], blocks_y[i], blocks_z[i], blocks_tempId[i], blocks_data[i];
if(bx and block_id) then
-- echo(format("x:%d,y:%d,z:%d,id:%d,data:%d",bx + x*16, by, bz + z*16, block_id, block_data));
chunk:SetType(bx, by, bz, block_id, false);
if(block_data and block_data~=0) then
chunk:SetData(bx, by, bz, block_data);
end
end
end
end
end
local function activate()
if(not msg) then
return;
end
local cmd = msg.cmd;
if(cmd == "loadmcworld") then
if(cur_generator) then
cur_generator.isworldloaded = msg.succeed;
end
elseif(cmd == "GetChunkBlocks") then
local blocks = msg;
if(blocks and blocks.count and cur_generator) then
cur_generator:LoadBlocksFromTable(cur_chunk, blocks.chunk_x, blocks.chunk_z, blocks);
end
elseif(cmd == "GetSpawnPosition") then
if(msg.x and msg.y and msg.z) then
cur_generator.spawn_x, cur_generator.spawn_y, cur_generator.spawn_z = msg.x, msg.y, msg.z;
end
LOG.std(nil, "debug", "MCImporter", {"GetSpawnPosition", msg});
end
end
NPL.this(activate);
|
class("Puzzle").extends()
function Puzzle:init(puzzle, save)
self.id = puzzle.id
self._save = save
self.title = puzzle.title
self.width = puzzle.width or 15
self.height = puzzle.height or 10
local size = self.width * self.height
self.grid = table.create(size, 0)
local values = {string.byte(puzzle.grid, 1, size)}
for i = 1, size do
self.grid[i] = values[i] - 48
end
self.hasBeenSolved = false
end
function Puzzle:isSolved(solution)
local grid = self.grid
for i = 1, self.width * self.height do
if grid[i] ~= solution[i] & 1 then
return false
end
end
self.hasBeenSolved = true
return true
end
function Puzzle:isTrivial()
for i, v in ipairs(self.grid) do
if v == 1 then
return false
end
end
return true
end
function Puzzle:isCellKnownEmpty(cellX, cellY)
return self:isColumnKnownEmpty(cellX) or self:isRowKnownEmpty(cellY)
end
function Puzzle:isColumnKnownEmpty(cellX)
for y = 1, self.height do
local index = cellX - 1 + (y - 1) * self.width + 1
if self.grid[index] == 1 then
return false
end
end
return true
end
function Puzzle:isRowKnownEmpty(cellY)
for x = 1, self.width do
local index = x - 1 + (cellY - 1) * self.width + 1
if self.grid[index] == 1 then
return false
end
end
return true
end
function Puzzle:save(context)
local puzzle = {
id = self.id,
title = self.title,
grid = table.concat(self.grid)
}
context.save.puzzles[self.id] = puzzle
table.insert(context.player.created, self.id)
save(context)
end
function Puzzle:delete(context)
local puzzleIndex = nil
local created = context.creator.created
for i = 1, #created do
if created[i] == self.id then
puzzleIndex = i
break
end
end
if puzzleIndex then
table.remove(created, puzzleIndex)
end
context.save.puzzles[self.id] = nil
save(context)
end
Puzzle.load = function (context, id, save)
return Puzzle((save or context.save).puzzles[id], save)
end
Puzzle.createEmpty = function (width, height)
width = width or 15
height = height or 10
return Puzzle({
id = playdate.string.UUID(16),
grid = string.rep("0", width * height),
width = width,
height = height,
title = "",
})
end
|
---
-- @author wesen
-- @copyright 2019 wesen <[email protected]>
-- @release 0.1
-- @license MIT
--
local TestCase = require "wLuaUnit.TestCase"
---
-- Checks that the TabStopCalculator class works as expected.
--
-- @type TestTabStopCalculator
--
local TestTabStopCalculator = TestCase:extend()
---
-- The require path for the class that is tested by this TestCase
--
-- @tfield string testClassPath
--
TestTabStopCalculator.testClassPath = "AC-ClientOutput/ClientOutput/Util/TabStopCalculator"
---
-- Checks that the TabStopCalculator can correctly calculate the number of passed tab stops.
--
function TestTabStopCalculator:testCanCalculateNumberOfPassedTabStops()
local TabStopCalculator = self.testClass
for _, testValueSet in ipairs(self:canCalculateNumberOfPassedTabStopsProvider()) do
local tabStopCalculator = TabStopCalculator(testValueSet["tabWidth"])
self:assertEquals(
tabStopCalculator:getNumberOfPassedTabStops(testValueSet["textPixelPosition"]),
testValueSet["expectedNumberOfPassedTabs"]
)
end
end
---
-- Data provider for TestTabStopCalculator:testCanCalculateNumberOfPassedTabStops().
--
function TestTabStopCalculator:canCalculateNumberOfPassedTabStopsProvider()
return {
-- Text position exactly on tab stop
{ ["tabWidth"] = 100, ["textPixelPosition"] = 200, ["expectedNumberOfPassedTabs"] = 2 },
{ ["tabWidth"] = 37, ["textPixelPosition"] = 111, ["expectedNumberOfPassedTabs"] = 3 },
-- Text position close before tab stop
{ ["tabWidth"] = 62, ["textPixelPosition"] = 97, ["expectedNumberOfPassedTabs"] = 1 },
{ ["tabWidth"] = 24, ["textPixelPosition"] = 182, ["expectedNumberOfPassedTabs"] = 7 },
-- Text position close after tab stop
{ ["tabWidth"] = 67, ["textPixelPosition"] = 70, ["expectedNumberOfPassedTabs"] = 1 },
{ ["tabWidth"] = 13, ["textPixelPosition"] = 146, ["expectedNumberOfPassedTabs"] = 11 },
-- Text position 0
{ ["tabWidth"] = 12, ["textPixelPosition"] = 0, ["expectedNumberOfPassedTabs"] = 0 },
{ ["tabWidth"] = 51, ["textPixelPosition"] = 0, ["expectedNumberOfPassedTabs"] = 0 }
}
end
---
-- Checks that the TabStopCalculator can get the number of tabs to a tab stop from a text pixel position.
--
function TestTabStopCalculator:testCanGetNumberOfTabsToTabStop()
local TabStopCalculator = self.testClass
for _, testValueSet in ipairs(self:canGetNumberOfTabsToTabStopProvider()) do
local tabStopCalculator = TabStopCalculator(testValueSet["tabWidth"])
local textPixelPosition = testValueSet["textPixelPosition"]
local targetTabStopNumber = testValueSet["targetTabStopNumber"]
self:assertEquals(
tabStopCalculator:getNumberOfTabsToTabStop(textPixelPosition, targetTabStopNumber),
testValueSet["expectedNumberOfTabs"]
)
end
end
---
-- Data provider for TestTabStopCalculator:testCanGetNumberOfTabsToTabStop().
--
function TestTabStopCalculator:canGetNumberOfTabsToTabStopProvider()
return {
-- Text pixel position before a tab stop
{
["tabWidth"] = 20,
["textPixelPosition"] = 30,
["targetTabStopNumber"] = 2,
["expectedNumberOfTabs"] = 1
},
{
["tabWidth"] = 15,
["textPixelPosition"] = 44,
["targetTabStopNumber"] = 4,
["expectedNumberOfTabs"] = 2
},
-- Text pixel position on a tab stop that is not the target tab stop
{
["tabWidth"] = 17,
["textPixelPosition"] = 34,
["targetTabStopNumber"] = 5,
["expectedNumberOfTabs"] = 3
},
{
["tabWidth"] = 12,
["textPixelPosition"] = 36,
["targetTabStopNumber"] = 7,
["expectedNumberOfTabs"] = 4
},
-- Text pixel position exactly on target tab stop
{
["tabWidth"] = 22,
["textPixelPosition"] = 44,
["targetTabStopNumber"] = 2,
["expectedNumberOfTabs"] = 0
},
{
["tabWidth"] = 31,
["textPixelPosition"] = 93,
["targetTabStopNumber"] = 3,
["expectedNumberOfTabs"] = 0
},
-- Text pixel position beyond target tab stop
{
["tabWidth"] = 10,
["textPixelPosition"] = 40,
["targetTabStopNumber"] = 3,
["expectedNumberOfTabs"] = -1
},
{
["tabWidth"] = 30,
["textPixelPosition"] = 150,
["targetTabStopNumber"] = 3,
["expectedNumberOfTabs"] = -2
}
}
end
---
-- Checks that the TabStopCalculator can get the next tab stop number from a text pixel position.
--
function TestTabStopCalculator:testCanGetNextTabStopNumber()
local TabStopCalculator = self.testClass
for _, testValueSet in ipairs(self:canGetNextTabStopNumberProvider()) do
local tabStopCalculator = TabStopCalculator(testValueSet["tabWidth"])
self:assertEquals(
tabStopCalculator:getNextTabStopNumber(testValueSet["textPixelPosition"]),
testValueSet["expectedTabStopNumber"]
)
end
end
---
-- Data provider for TestTabStopCalculator:testCanGetNextTabStopNumber().
--
function TestTabStopCalculator:canGetNextTabStopNumberProvider()
return {
-- Text position exactly on tab stop
{ ["tabWidth"] = 44, ["textPixelPosition"] = 44, ["expectedTabStopNumber"] = 2 },
{ ["tabWidth"] = 315, ["textPixelPosition"] = 945, ["expectedTabStopNumber"] = 4 },
-- Text position close before tab stop
{ ["tabWidth"] = 21, ["textPixelPosition"] = 39, ["expectedTabStopNumber"] = 2 },
{ ["tabWidth"] = 78, ["textPixelPosition"] = 77, ["expectedTabStopNumber"] = 1 },
-- Text position close after tab stop
{ ["tabWidth"] = 516, ["textPixelPosition"] = 2067, ["expectedTabStopNumber"] = 5 },
{ ["tabWidth"] = 123, ["textPixelPosition"] = 742, ["expectedTabStopNumber"] = 7 },
-- Text position 0
{ ["tabWidth"] = 170, ["textPixelPosition"] = 0, ["expectedTabStopNumber"] = 1 },
{ ["tabWidth"] = 234, ["textPixelPosition"] = 0, ["expectedTabStopNumber"] = 1 }
}
end
---
-- Checks that the TabStopCalculator can calculate the position of the next tab stop relative to a text
-- pixel position.
--
function TestTabStopCalculator:testCanGetNextTabStopPosition()
local TabStopCalculator = self.testClass
for _, testValueSet in ipairs(self:canGetNextTabStopPositionProvider()) do
local tabStopCalculator = TabStopCalculator(testValueSet["tabWidth"])
self:assertEquals(
tabStopCalculator:getNextTabStopPosition(testValueSet["textPixelPosition"]),
testValueSet["expectedTabStopPosition"]
)
end
end
---
-- Data provider for TestTabStopCalculator:testCanGetNextTabStopPosition().
--
function TestTabStopCalculator:canGetNextTabStopPositionProvider()
return {
-- Text position exactly on tab stop
{ ["tabWidth"] = 665, ["textPixelPosition"] = 665, ["expectedTabStopPosition"] = 1330 },
{ ["tabWidth"] = 142, ["textPixelPosition"] = 284, ["expectedTabStopPosition"] = 426 },
-- Text position close before tab stop
{ ["tabWidth"] = 370, ["textPixelPosition"] = 368, ["expectedTabStopPosition"] = 370 },
{ ["tabWidth"] = 439, ["textPixelPosition"] = 438, ["expectedTabStopPosition"] = 439 },
-- Text position close after tab stop
{ ["tabWidth"] = 706, ["textPixelPosition"] = 1414, ["expectedTabStopPosition"] = 2118 },
{ ["tabWidth"] = 320, ["textPixelPosition"] = 641, ["expectedTabStopPosition"] = 960 },
-- Text position 0
{ ["tabWidth"] = 164, ["textPixelPosition"] = 0, ["expectedTabStopPosition"] = 164 },
{ ["tabWidth"] = 24, ["textPixelPosition"] = 0, ["expectedTabStopPosition"] = 24 }
}
end
---
-- Checks that the TabStopCalculator can convert a tab number to a text pixel position.
--
function TestTabStopCalculator:testCanConvertTabNumberToPosition()
local TabStopCalculator = self.testClass
for _, testValueSet in ipairs(self:canConvertTabNumberToPositionProvider()) do
local tabStopCalculator = TabStopCalculator(testValueSet["tabWidth"])
self:assertEquals(
tabStopCalculator:convertTabNumberToPosition(testValueSet["tabNumber"]),
testValueSet["expectedPosition"]
)
end
end
---
-- Data provider for TestTabStopCalculator:testCanConvertTabNumberToPosition().
--
function TestTabStopCalculator:canConvertTabNumberToPositionProvider()
return {
{ ["tabWidth"] = 340, ["tabNumber"] = 2, ["expectedPosition"] = 680 },
{ ["tabWidth"] = 215, ["tabNumber"] = 4, ["expectedPosition"] = 860 },
{ ["tabWidth"] = 330, ["tabNumber"] = 1, ["expectedPosition"] = 330 },
-- Tab number 0
{ ["tabWidth"] = 410, ["tabNumber"] = 0, ["expectedPosition"] = 0 },
{ ["tabWidth"] = 536, ["tabNumber"] = 0, ["expectedPosition"] = 0 },
{ ["tabWidth"] = 247, ["tabNumber"] = 0, ["expectedPosition"] = 0 }
}
end
return TestTabStopCalculator
|
--[[
Copyright (c) 2013, Chiara De Acetis
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of <addon name> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <your name> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
]]
-- Object Alliance
--[[
Concept
list = {party1={} party2={} party3={}}
list = {party1={WHM="ppl" PLD="ppl" WAR="ppl" DD="ppl" } party2={} party3={}}
if there's "add war" and only DD slots are left, it has to put the war in the DD slot
]]
local Alliance = {}
require 'logger'
local files = require 'files'
local JobList = T{
'blm',
'blu',
'brd',
'bst',
'dnc',
'drg',
'drk',
'whm',
'rdm',
'pup',
'cor',
'pld',
'geo',
'run',
'sch',
'mnk',
'thf',
'war',
'sam',
'nin',
'smn',
'rng',
'dd',
'support',
'heal',
'tank'
}
local DDlist = T{
'blm',
'blu',
'bst',
'dnc',
'drg',
'drk',
'pup',
'pld',
'run',
'mnk',
'thf',
'war',
'sam',
'nin',
'smn',
'rng'
}
local SupportList = T{
'cor',
'brd',
'geo'
}
local HealList = T{
'whm',
'rdm',
'sch'
}
--create and empty alliance
function Alliance:new()
local ally = {
party1 = {},
party2 = {},
party3 = {}
}
setmetatable(ally, self)
self.__index = self
return ally
end
--sets one or multiple job in party1
function Alliance:setParty1(jobs)
local length = 0
local numJob = #self.party1
if numJob == 6 then
return
end
if #jobs <= (6 - numJob) then
length = #jobs
else
length = (6 - numJob)
end
j = 1
for i = 1, length do
job = jobs[i]:lower()
if JobList:contains(job) then
self.party1[j+numJob] = {job}
j = j+1
end
end
end
--sets one or multiple job in the party2
function Alliance:setParty2(jobs)
local length = 0
local numJob = #self.party2
if numJob == 6 then
return
end
if #jobs <= (6 - numJob) then
length = #jobs
else
length = (6 - numJob)
end
j = 1
for i = 1, length do
job = jobs[i]:lower()
if JobList:contains(job) then
self.party2[j+numJob] = {job}
j = j+1
end
end
end
--sets one or multiple job in party3
function Alliance:setParty3(jobs)
local length = 0
local numJob = #self.party3
if numJob == 6 then
return
end
if #jobs <= (6 - numJob) then
length = #jobs
else
length = (6 - numJob)
end
j = 1
for i = 1, length do
job = jobs[i]:lower()
if JobList:contains(job) then
self.party3[j+numJob] = {job}
j = j+1
end
end
end
--delete a job inside the ally
function Alliance:deleteJob(job, party) --it rescale the player list too
job = job:lower()
-- party slot not given
if (party == nil ) then
party = self:findJob(job)
if party[1] == 1 then
table.remove(self.party1, party[2])
elseif party[1] == 2 then
table.remove(self.party2, party[2])
elseif party[1] == 3 then
table.remove(self.party3, party[2])
end
else -- party given
if (party == "party1") then
for i=1, #self.party1 do
local slot = self.party1[i]
local v = slot[1]
if(v == job) then
table.remove(self.party1, i)
return
end
end
elseif (party == "party2") then
for i=1, #self.party2 do
local slot = self.party2[i]
local v = slot[1]
if(v == job) then
table.remove(self.party2, i)
return
end
end
elseif (party == "party3") then
for i=1, #self.party3 do
if(v == job) then
table.remove(self.party3, i)
return
end
end
end
end
end
--returns the first party table that contains the given job
function Alliance:findJob(job)
local party = nil
for i=1, #self.party1 do
local slot = self.party1[i]
local v = slot[1]
if( v == job ) then
party = {1, i}
return party
end
end
if(party == nil) then
for i=1, #self.party2 do
local slot = self.party2[i]
local v = slot[1]
if( v == job ) then
party = {2, i}
return party
end
end
end
if(party == nil) then
for i=1, #self.party3 do
local slot = self.party3[i]
local v = slot[1]
if( v == job ) then
party = {3, i}
return party
end
end
end
if(party == nil ) then
error(job..' not found')
return
end
end
--returns the string representing the party
function Alliance:printAlly()
local s = ''
if(#self.party1 > 0) then
s = s..'\nPARTY 1\n'
for i=1, #self.party1 do
slot = self.party1[i]
job = slot[1]
name = slot[2]
s = s..'['..job:upper()..']'
if name then
s = s..' '..name
end
s = s..' \n'
end
end
if(#self.party2 > 0) then
s = s..'\nPARTY 2\n'
for i=1, #self.party2 do
slot = self.party2[i]
job = slot[1]
name = slot[2]
s = s..'['..job:upper()..']'
if name then
s = s..' '..name
end
s = s..' \n'
end
end
if(#self.party3 > 0) then
s = s..'\nPARTY 3\n'
for i=1, #self.party3 do
slot = self.party3[i]
job = slot[1]
name = slot[2]
s = s..'['..job:upper()..']'
if name then
s = s..' '..name
end
s = s..' \n'
end
end
return s
end
--delete the ally
function Alliance:deleteAll()
self.party1 = {}
self.party2 = {}
self.party3 = {}
end
--delete the party
function Alliance:delete(party)
if party == "party1" then
self.party1 = {}
elseif party == "party2" then
self.party2 = {}
elseif party == "party3" then
self.party3 = {}
end
end
--sets one player to the first <job> slot free
function Alliance:addPlayer(job, name)
local party = self:findFreeSlot(job)
local rightJob = true
--if party is null the job wasn't found
--it means the there isn't the given job (example: one's looking for mnk and only slot DD are left)
if not party and job then
if DDlist:contains(job:lower()) then
party = self:findFreeSlot('dd')
rightJob = false
elseif SupportList:contains(job:lower())then
party = self:findFreeSlot('support')
rightJob = false
elseif HealList:contains(job:lower()) then
party = self:findFreeSlot('heal')
rightJob = false
end
if not party then
error("Can't find a free slot")
return
end
end
local pos = party[2]
if (party[1] == 1) then
local slot = self.party1[pos]
if rightJob then
self.party1[pos] = {slot[1], name}
else
self.party1[pos] = {job:lower(), name}
end
end
if (party[1] == 2) then
local slot = self.party2[pos]
if rightJob then
self.party2[pos] = {slot[1], name}
else
self.party2[pos] = {job, name}
end
end
if (party[1] == 3) then
local slot = self.party3[pos]
if rightJob then
self.party3[pos] = {slot[1], name}
else
self.party3[pos] = {job, name}
end
end
--if I'm here it means it the given job is missing
end
--find the first free party slot (job is optional)
function Alliance:findFreeSlot(job)
local party = nil --first position is pt, second is party slot
for i=1, #self.party1 do
local slot = self.party1[i]
local jobName = slot[1]
local name = slot[2]
if ((not job) and name == nil) then
--no job given, I'm looking for the first free slot in party
party = {1, i}
return party
elseif (job and name == nil) then
--the job is given, I'm looking for the first free slot for the given job
job = job:lower()
if(jobName == job)then
party = {1, i}
return party
end
end
end
for i=1, #self.party2 do
local slot = self.party2[i]
local jobName = slot[1]
local name = slot[2]
if ((not job) and name == nil) then
--no job given, I'm looking for the first free slot in party
party = {2, i}
return party
elseif (job and name == nil) then
--the job is given, I'm looking for the first free slot for the given job
job = job:lower()
if(jobName == job)then
party = {2, i}
return party
end
end
end
for i=1, #self.party3 do
local slot = self.party3[i]
local jobName = slot[1]
local name = slot[2]
if ((not job) and name == nil) then
--no job given, I'm looking for the first free slot in party
party = {3, i}
return party
elseif (job and name == nil) then
--the job is given, I'm looking for the first free slot for the given job
job = job:lower()
if(jobName == job)then
party = {3, i}
return party
end
end
end
end
-- removes the player from alliance list (i remove the player in i-esim position)
function Alliance:removePlayer(name)
name = name:lower()
--looks through the pts
local v = ''
local slot = nil
for k=1, #self.party1 do
slot = self.party1[k]
v = slot[2]
if(v~= nil)then
v = v:lower()
if v == name then
self.party1[k] = {slot[1]}
return
end
end
end
for k=1, #self.party2 do
slot = self.party2[k]
v = slot[2]
if(v~= nil)then
v = v:lower()
if v == name then
self.party2[k] = {slot[1]}
return
end
end
end
for k=1, #self.party3 do
slot = self.party3[k]
v = slot[2]
if(v~= nil)then
v = v:lower()
if v == name then
self.party3[k] = {slot[1]}
return
end
end
end
end
--save the current ally in an xml file
function Alliance:save()
--TODO (now creates only a string xml)
local a = '<?xml version="1.0" ?>\n'
a = a..'<alliance>\n'
a = a..'\t<party1>\n'
for i=1, #self.party1 do
slot = self.party1[i]
job = slot[1]
a = a..'\t\t<job'..i..'>'..job:upper()..'</job'..i..'>\n'
end
a = a..'\t</party1>\n'
a = a..'\t<party2>\n'
for i=1, #self.party2 do
slot = self.party2[i]
job = slot[1]
a = a..'\t\t<job'..i..'>'..job:upper()..'</job'..i..'>\n'
end
a = a..'\t</party2>\n'
a = a..'\t<party3>\n'
for i=1, #self.party3 do
slot = self.party3[i]
job = slot[1]
a = a..'\t\t<job'..i..'>'..job:upper()..'</job'..i..'>\n'
end
a = a..'\t</party3>\n'
a = a..'</alliance>\n'
end
return Alliance
|
---- Vector Example
require("eyesy") -- include the eyesy library
modeTitle = "Example - Vectors" -- name the mode
print(modeTitle) -- print the mode title
---------------------------------------------------------------------------
-- helpful global variables
w = of.getWidth() -- global width
h = of.getHeight() -- global height of screen
w2 = w / 2 -- width half
h2 = h / 2 -- height half
w4 = w / 4 -- width quarter
h4 = h / 4 -- height quarter
w6 = w / 6 -- width 6th
h6 = h / 6 -- height 6th
w8 = w / 8 -- width 8th
h8 = h / 8 -- height 8th
h16 = h / 16 -- 16th height
h32 = h / 32 -- 32nd height
-- glm.vec3 is a vector with three components x,y,z which are the 3D position in our scene
c = glm.vec3( w2, h2, 0 ) -- center in glm vector3
tLeft = glm.vec3( 0,0,0 ) -- top left in glm vec3
text = glm.vec3(-15,0,0) -- center the printed text for the points
-- vectors are helpful becasue we can make them a global variable as above we call the...
-- center point 'c'
-- vectors can also be used with math, example: c + tLeft adds c's xyz with tLefts'
---------------------------------------------------------------------------
-- the setup function runs once before the update and draw loops
function setup()
of.enableBlendMode(of.BLENDMODE_ALPHA) -- turn blend mode for transparency blending
--------------------- define light
myLight = of.Light() -- define a light class
myLight:setPointLight( ) -- we'll use a point light for this example
myLight:setAmbientColor( of.FloatColor( 1, 1, 1 ) ) -- and make the ambient color white
myLight:setPosition( c + glm.vec3(0,0,h2) ) -- and set the position in the center with z closer
-- so we know that the setup was succesful
print("done setup")
end
---------------------------------------------------------------------------
-- update function runs on loop
function update()
end
---------------------------------------------------------------------------
-- the main draw function also runs on loop
function draw()
of.setBackgroundColor( 255 ) -- set background color to white
--------------------- draw the grid
of.setLineWidth( 1 ) -- set the line width to 1 pixel
of.setColor( 0 ) -- set color black
of.drawLine( 0, h2, w, h2 ) -- draw a horizontal line at the center (h2)
of.drawLine( w2, 0, w2, h ) -- draw a vertical at the center (w2)
--------------------- draw the title
of.drawBitmapString( "VECTOR EXAMPLE", c + glm.vec3( 5,-5,0 ) )
-------------------- enable modes for the scene
of.enableLighting() -- enable lighting globally
of.enableDepthTest() -- enable 3D rendering globally
myLight:enable() -- begin rendering for myLight
-------------------- draw first vector as 3d box
of.pushMatrix() -- save the current matrix (0,0,0)
------------ of.translate shifts the matrix, positive width moves to the right, pos height, down...
--------- negative width to the left, and neg height is up.
of.translate( glm.vec3( w4, h4, 0 ) ) -- move the matrix to top left, center
-- w4 to the right, h4 down, no change z axis
of.drawBitmapString( "point 1", text ) -- draw the text, with x axis offset
of.setColor( of.Color.green ) -- set color to green
of.noFill() -- draw just the lines of box
of.drawBox( h32 ) -- draw the box, no 2nd argument places it 0,0,0
-------------------------- move one point around the screen
of.popMatrix() -- recall last matrix(0,0,0)
of.pushMatrix() -- save again
point2 = glm.vec3( w2, 0, 0 ) -- top right, top left corner
point2mod = glm.vec3(
knob1*w2, knob2*h2, 0 ) -- a vec3 to move point2, knob1=x, knob2=y
of.translate( point2 + point2mod )
of.setColor(0) -- set color to black
of.drawBitmapString( "point 2", text ) -- draw the text, with x axis offset
of.setColor( of.Color.red ) -- set color to green
of.drawBox( h32 ) -- draw the box, no 2nd argument places it 0,0,0
---------------------------- draw a grid of boxes that can be rotated on knob3
of.popMatrix() -- recall last matrix (0,0,0)
of.pushMatrix() -- save again
of.translate( 0, h2 ) -- move to bottom left, top left
offsetX = w2 / 10 -- get the width space for the quadrant
offsetY = h2 / 10 -- get the height space
gridP = glm.vec3( offsetX/2, offsetY/2, 0 ) -- define a new point and...
of.translate( gridP ) -- translate again to center the grid
for i = 0, 9 do -- the 10 columns
x = i * offsetX -- get the x steps
for j = 0, 9 do
-- save the current matrix above, ***note we still have the(0,0,0)matrix saved, so two pops will bring us back to 0,0,0
of.pushMatrix()
y = j * offsetY -- get the y steps
gridP.x = x -- change gridP by using the name.x
gridP.y = y -- change gridP.y
of.translate( gridP ) -- translate to our position
of.rotateDeg( knob3*360, 0, 1, 0) -- rotate the box on its own y axis
of.rotateDeg( knob4*360, 1, 0, 0) -- rotate the box on its own x axis
of.setColor(0) -- set color to black
of.drawBitmapString(
(i*10)+j, text ) -- draw the text, with x axis offset
of.setColor( of.Color.blue ) -- set color to blue
of.drawBox( h32 ) -- draw the box
of.popMatrix() -- recall last matrix stored for this loop
end
end
-------------------------------
of.popMatrix() -- recall (0,0,0) matrix
of.pushMatrix() -- save again
of.translate( w2+w4, h2+h4 ) -- move to bottom right, center
of.rotateDeg( knob5*360, 0,1,0 ) -- rotate the following on the y axis
of.translate( -w8, -h8 ) -- move to bottom right, top left
offsetX = w4 / 5 -- get the width space for the quadrant
offsetY = h4 / 5 -- get the height space
gridP = glm.vec3( offsetX/2, offsetY/2, 0 ) -- define a new point and...
of.translate( gridP ) -- translate again to center the grid
for i = 0, 4 do -- the 10 columns
x = i * offsetX -- get the x steps
for j = 0, 4 do
of.pushMatrix()
num = ( i * 10 ) + j -- calculate the number
audio = inL[ num+1 ] -- audio buffer 1-100
aRange = audio * h2 -- audio range is h2
y = j * offsetY -- get the y steps
gridP.x = x -- change gridP by using the name.x
gridP.y = y -- change gridP.y
gridP.z = aRange -- change the z axis with the audio
of.translate( gridP ) -- translate to our position
of.rotateDeg( knob3*360, 0, 1, 0) -- rotate the box on its own y axis
of.rotateDeg( knob4*360, 1, 0, 0) -- rotate the box on its own x axis
of.setColor(0) -- set color to black
of.drawBitmapString(
num, text ) -- draw the text, with x axis offset
of.setColor( of.Color.cyan ) -- set color to blue
of.drawBox( h32 ) -- draw the box
of.popMatrix() -- recall last matrix stored for this loop
end
end
------------------------ disable lighting and depth
myLight:disable() -- end rendering for myLight
of.disableLighting() -- disable lighting globally
of.disableDepthTest() -- enable 3D rendering globally
of.popMatrix() -- recall last matrix
end
---------------------------------------------------------------------------
------ function for audio average, takes the whole 100 pt audio buffer and averages.
function avG()
a = 0
for i = 1, 100 do
aud = math.abs( inL[i])
a = a + aud
end
x = a / 100
if( x <= 0.001 ) then
x = 0
else
x = x
end
return x
end
-- the exit function ends the update and draw loops
function exit()
-- so we know the script is done
print("script finished")
end |
function __TS__StringIncludes(self, searchString, position)
if not position then
position = 1
else
position = position + 1
end
local index = string.find(self, searchString, position, true)
return index ~= nil
end
|
local K, C = unpack(select(2, ...))
local Module = K:NewModule("TooltipAzerite")
-- Credit: AzeriteTooltip, by jokair9
function Module:AzeriteArmor()
local strfind, format = string.find, string.format
local tinsert, ipairs = table.insert, ipairs
local tipList = {}
local function scanTooltip(tooltip)
for i = 9, tooltip:NumLines() do
local line = _G[tooltip:GetName().."TextLeft"..i]
local text = line:GetText()
if text and strfind(text, "%-") then
tinsert(tipList, i)
end
end
return #tipList
end
local iconString = "|T%s:18:22:0:0:64:64:5:59:5:59"
local function getIconString(icon, known)
if known then
return format(iconString..":255:255:255|t", icon)
else
return format(iconString..":120:120:120|t", icon)
end
end
local powerData = {}
local function convertPowerID(id)
local spellID = powerData[id]
if not spellID then
local powerInfo = C_AzeriteEmpoweredItem.GetPowerInfo(id)
if powerInfo and powerInfo.spellID then
spellID = powerInfo.spellID
powerData[id] = spellID
end
end
return spellID
end
local function lookingForAzerite(tooltip, powerName)
for i = 8, tooltip:NumLines() do
local line = _G[tooltip:GetName().."TextLeft"..i]
local text = line:GetText()
if text and strfind(text, "%- "..powerName) then
return true
end
end
end
local cache = {}
local function updateAzeriteArmor(self)
local link = select(2, self:GetItem())
if not link then return end
if not C_AzeriteEmpoweredItem.IsAzeriteEmpoweredItemByID(link) then return end
local allTierInfo = cache[link]
if not allTierInfo then
allTierInfo = C_AzeriteEmpoweredItem.GetAllTierInfoByItemID(link)
cache[link] = allTierInfo
end
if not allTierInfo then return end
local count = scanTooltip(self)
local index = 1
for i = 1, #allTierInfo do
local powerIDs = allTierInfo[i].azeritePowerIDs
if powerIDs[1] == 13 then break end
local tooltipText = ""
for _, id in ipairs(powerIDs) do
local spellID = convertPowerID(id)
if not spellID then break end
local name, _, icon = GetSpellInfo(spellID)
local found = lookingForAzerite(self, name)
if found then
tooltipText = tooltipText.." "..getIconString(icon, true)
else
tooltipText = tooltipText.." "..getIconString(icon)
end
end
if tooltipText ~= "" and count > 0 then
local line = _G[self:GetName().."TextLeft"..tipList[index]]
line:SetText(line:GetText().."\n "..tooltipText)
count = count - 1
index = index + 1
end
end
wipe(tipList)
end
GameTooltip:HookScript("OnTooltipSetItem", updateAzeriteArmor)
ItemRefTooltip:HookScript("OnTooltipSetItem", updateAzeriteArmor)
ShoppingTooltip1:HookScript("OnTooltipSetItem", updateAzeriteArmor)
EmbeddedItemTooltip:HookScript("OnTooltipSetItem", updateAzeriteArmor)
end
function Module:OnEnable()
if not C["Tooltip"].AzeriteArmor then
return
end
if IsAddOnLoaded("AzeriteTooltip") then
return
end
self:AzeriteArmor()
end |
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
_menuPool = NativeUI.CreatePool()
_menuPool:RefreshIndex()
ESX = nil
animBind = NativeUI.CreateMenu("RedSide", "", 0, 0)
_menuPool:Add(animBind)
Citizen.CreateThread(function()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
Citizen.Wait(0)
end
end)
function ShowAboveRadarMessage(message, back)
if back then Citizen.InvokeNative(0x92F0DA1E27DB96DC, back) end
SetNotificationTextEntry("jamyfafi")
AddTextComponentString(message)
if string.len(message) > 99 and AddLongString then AddLongString(message) end
return DrawNotification(0, 1)
end
pavAnimName = {}
pavAnim = {}
local barberShops = nil
function OpenBindMenu()
_menuPool:CloseAllMenus()
for k , v in pairs(Config.Anims) do
for i=1,#v,1 do
table.insert( pavAnim, v[i].name )
table.insert( pavAnimName,v[i])
end
end
menu = animBind
pavInd = { "Pav 7", "Pav 8", "Pav 9" }
pavName = { "pav7", "pav8", "pav9" }
local selectedBindAnim = nil
local selectedAnim
local selectedDict = nil
pref = menu
local selectedmood = nil
local selecteddemarhce = nil
bind = NativeUI.CreateListItem("Touches : ", pavInd, 0, "Choisissez une animation a mettre sur une touche !")
animq = NativeUI.CreateListItem("Animations : ", pavAnim, 0, "")
pref:AddItem(bind)
pref:AddItem(animq)
p = NativeUI.CreateItem("Annuler l\'animation","")
menu:AddItem(p)
pref.OnItemSelect = function(_,_,index)
if index == 1 then
local ped = GetPlayerPed(-1);
if ped then
ClearPedTasks(ped);
end
SetEnableHandcuffs(ped, false)
end
end
pref.OnListSelect = function(_, item, index)
--(index)
if item == bind then
if selectedBindAnim ~= nil then
TriggerEvent("dqp:shownotif", "Touches d\'animations : " .. selectedBindAnim .. "~n~sur la touche " .. pavInd[index], 26)
TriggerServerEvent("dqp:saveBind", selectedAnim, pavName[index])
else
TriggerEvent("dqp:shownotif", "Aucune animation selectionne !", 6)
end
end
if item == animq then
TriggerEvent("dqp:shownotif", "Animation Choisi : " .. pavAnim[index], 26)
selectedBindAnim = pavAnim[index]
selectedAnim = pavAnimName[index]
print(pavAnimName[index])
end
end
for k , v in pairs(Config.Anims) do
tpl = _menuPool:AddSubMenu(menu, k,"",true,true)
for i = 1 ,#v,1 do
p = NativeUI.CreateItem(v[i].name,"")
tpl:AddItem(p)
end
tpl.OnItemSelect = function(_, _, index)
if type(v[index].func) == "function" then v[index].func(GetPlayerPed(-1)) return end
if v[index].anim then
doAnim(v[index].anim, nil, v[index].func)
elseif v[index].anims then
local firstAnim = v[index].anims.enter[#v[index].anims.enter]
local selected = v[index].anims.exit and IsEntityPlayingAnim(ped, firstAnim.anim[1], firstAnim.anim[2], 3) and v[index].anims.exit or v[index].anims.enter
TaskSynchronizedTasks(GetPlayerPed(-1), selected)
end
end
_menuPool:RefreshIndex()
end
_menuPool:RefreshIndex()
end
function TaskSynchronizedTasks(ped, animData, clearTasks)
for _,v in pairs(animData) do
if not HasAnimDictLoaded(v.anim[1]) then
RequestAnimDict(v.anim[1])
while not HasAnimDictLoaded(v.anim[1]) do Citizen.Wait(0) end
end
end
local _, sequence = OpenSequenceTask(0)
for _,v in pairs(animData) do
TaskPlayAnim(0, v.anim[1], v.anim[2], 2.0, -2.0, math.floor(v.time or -1), v.flag or 48, 0, 0, 0, 0)
end
CloseSequenceTask(sequence)
if clearTasks then ClearPedTasks(ped) end
TaskPerformSequence(ped, sequence)
ClearSequenceTask(sequence)
for _,v in pairs(animData) do
RemoveAnimDict(v.anim[1])
end
return sequence
end
function canDoIt()
return true
end
function doAnim(animName, time, flag, ped, customPos)
if type(animName) ~= "table" then animName = {animName} end
ped, flag = ped or GetPlayerPed(-1), flag and tonumber(flag) or false
if not animName or not animName[1] or string.len(animName[1]) < 1 then return end
print(IsEntityPlayingAnim(ped, animName[1], animName[2], 3))
if IsEntityPlayingAnim(ped, animName[1], animName[2], 3) or IsPedActiveInScenario(ped) then ClearPedTasks(ped) print("o") return end
Citizen.CreateThread(function()
forceAnim(animName, flag, { ped = ped, time = time, pos = customPos })
end)
end
function forceAnim(animName, flag, args)
flag, args = flag and tonumber(flag) or false, args or {}
local ped, time, clearTasks, animPos, animRot, animTime = args.ped or GetPlayerPed(-1), args.time, args.clearTasks, args.pos, args.ang
if IsPedInAnyVehicle(ped) and (not flag or flag < 40) then return end
if not clearTasks then ClearPedTasks(ped) end
if not animName[2] and femaleFix[animName[1]] and GetEntityModel(ped) == -1667301416 then
animName = femaleFix[animName[1]]
end
if animName[2] and not HasAnimDictLoaded(animName[1]) then
if not DoesAnimDictExist(animName[1]) then return end
RequestAnimDict(animName[1])
while not HasAnimDictLoaded(animName[1]) do
Citizen.Wait(10)
end
end
if not animName[2] then
ClearAreaOfObjects(GetEntityCoords(ped), 1.0)
TaskStartScenarioInPlace(ped, animName[1], -1, not tableHasValue(animBug, animName[1]))
else
if not animPos then
TaskPlayAnim(ped, animName[1], animName[2], 8.0, -8.0, -1, flag or 44, 0, 0, 0, 0, 0)
else
TaskPlayAnimAdvanced(ped, animName[1], animName[2], animPos.x, animPos.y, animPos.z, animRot.x, animRot.y, animRot.z, 8.0, -8.0, -1, flag or 44, animTime or -1, 0, 0)
end
end
if time and type(time) == "number" then
Citizen.Wait(time)
ClearPedTasks(ped)
end
if not args.dict then RemoveAnimDict(animName[1]) end
end
-- Key controls
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
_menuPool:ProcessMenus()
if IsControlPressed(0, Keys['F10']) then
animBind:Visible(true)
end
if IsControlJustReleased(0, Keys['W']) and IsInputDisabled(0) and not isDead then
ClearPedTasks(PlayerPedId())
end
end
end)
OpenBindMenu()
RegisterNetEvent("dqp:shownotif")
AddEventHandler("dqp:shownotif", function(text, color)
if color == 210 then
color = 18
end
Citizen.InvokeNative(0x92F0DA1E27DB96DC, tonumber(color))
SetNotificationTextEntry("STRING")
AddTextComponentString(text)
DrawNotification(false, true)
end)
local Pad7 = {}
Citizen.CreateThread(function()
while true do
Wait(0)
if IsControlPressed(0, 117) and GetLastInputMethod(0) then
Wait(200)
if GetLastInputMethod(0) then
if Pad7[1] ~= nil then
if type(Pad7[2].func) == "function" then Pad7[2].func(GetPlayerPed(-1)) return end
if Pad7[1].anim then
doAnim(Pad7[1].anim, nil, Pad7[1].func)
else
local firstAnim = Pad7[1].anims.enter[#Pad7[1].anims.enter]
local selected = Pad7[1].anims.exit and IsEntityPlayingAnim(ped, firstAnim.anim[1], firstAnim.anim[2], 3) and Pad7[1].anims.exit or Pad7[1].anims.enter
TaskSynchronizedTasks(GetPlayerPed(-1), selected)
end
Wait(500)
end
end
end
if IsControlJustReleased(0, 111) and GetLastInputMethod(0) then
Wait(200)
if GetLastInputMethod(0) then
if Pad7[2] ~= nil then
if type(Pad7[2].func) == "function" then Pad7[2].func(GetPlayerPed(-1)) return end
if Pad7[2].anim then
doAnim(Pad7[2].anim, nil, Pad7[2].func)
else
local firstAnim = Pad7[2].anims.enter[#Pad7[2].anims.enter]
local selected = Pad7[2].anims.exit and IsEntityPlayingAnim(ped, firstAnim.anim[1], firstAnim.anim[2], 3) and Pad7[2].anims.exit or Pad7[2].anims.enter
TaskSynchronizedTasks(GetPlayerPed(-1), selected)
end
end
end
Wait(500)
end
if IsControlPressed(0, 118) and GetLastInputMethod(0) then
Wait(200)
if GetLastInputMethod(0) then
if Pad7[3] ~= nil then
if type(Pad7[3].func) == "function" then Pad7[3].func(GetPlayerPed(-1)) return end
if Pad7[3].anim then
doAnim(Pad7[3].anim, nil, Pad7[3].func)
elseif Pad7[3].anims then
local firstAnim = Pad7[3].anims.enter[#Pad7[3].anims.enter]
local selected = Pad7[3].anims.exit and IsEntityPlayingAnim(ped, firstAnim.anim[1], firstAnim.anim[2], 3) and Pad7[3].anims.exit or Pad7[1].anims.enter
TaskSynchronizedTasks(GetPlayerPed(-1), selected)
end
Wait(500)
end
end
end
end
end)
function tableHasValue(tbl, value, k)
if not tbl or not value or type(tbl) ~= "table" then return end
for _,v in pairs(tbl) do
if k and v[k] == value or v == value then return true, _ end
end
end
function PlayAnimSaved(anim, dict)
local ad = anim
player = GetPlayerPed(-1)
if (DoesEntityExist(player) and not IsEntityDead(player)) then
loadAnimDict(ad)
if (IsEntityPlayingAnim(player, ad, dict, 3)) then
ClearPedSecondaryTask(PlayerPedId())
else
TaskPlayAnim(player, ad, dict, 8.0, 1.0, -1, 49, 0, 0, 0, 0)
end
end
end
function loadAnimDict(dict)
while (not HasAnimDictLoaded(dict)) do
RequestAnimDict(dict)
Citizen.Wait(1)
end
end
femaleFix = {
["WORLD_HUMAN_BUM_WASH"] = {"amb@world_human_bum_wash@male@high@idle_a", "idle_a"},
["WORLD_HUMAN_SIT_UPS"] = {"amb@world_human_sit_ups@male@idle_a", "idle_a"},
["WORLD_HUMAN_PUSH_UPS"] = {"amb@world_human_push_ups@male@base", "base"},
["WORLD_HUMAN_BUM_FREEWAY"] = {"amb@world_human_bum_freeway@male@base", "base"},
["WORLD_HUMAN_CLIPBOARD"] = {"amb@world_human_clipboard@male@base", "base"},
["WORLD_HUMAN_VEHICLE_MECHANIC"] = {"amb@world_human_vehicle_mechanic@male@base", "base"},
}
RegisterNetEvent('dqp:ready')
AddEventHandler('dqp:ready', function()
ESX.TriggerServerCallback("dqp:getsettings", function(result)
if result[1] ~= nil then
Pad7 = {}
pav7 = json.decode(result[1].pav7)
pav8 = json.decode(result[1].pav8)
pav9 = json.decode(result[1].pav9)
table.insert(Pad7, { anim = pav7.anim, dict = pav7.dict })
table.insert(Pad7, { anim = pav8.anim, dict = pav8.dict })
table.insert(Pad7, { anim = pav9.anim, dict = pav9.dict })
TriggerEvent("dqp:shownotif", "Touche enregistrée", 26)
end
end)
end)
AddEventHandler("playerSpawned", function(_)
while ESX == nil do
Wait(1)
end
ESX.TriggerServerCallback("dqp:getsettings", function(result)
if result[1] ~= nil then
Pad7 = {}
pav7 = json.decode(result[1].pav7)
pav8 = json.decode(result[1].pav8)
pav9 = json.decode(result[1].pav9)
table.insert(Pad7, { anim = pav7.anim, dict = pav7.dict })
table.insert(Pad7, { anim = pav8.anim, dict = pav8.dict })
table.insert(Pad7, { anim = pav9.anim, dict = pav9.dict })
TriggerEvent("dqp:shownotif", "Touche enregistrée", 26)
end
end)
end) |
script.Parent.MouseButton1Click:Connect(function()--destory the gui when the user clicks the button
script.Parent.Parent.Parent:Destroy()
end) |
data:extend(
{
{
type = "fluid",
name = "nitrogen-dioxide",
default_temperature = 25,
heat_capacity = "1KJ",
base_color = {r=0.8, g=0.0, b=1.0},
flow_color = {r=0.0, g=0.0, b=1.0},
max_temperature = 100,
icon = "__Engineersvsenvironmentalist__/graphics/icons/chemicals/nitrogen-dioxide.png",
-- pressure_to_speed_ratio = 0.6,
pressure_to_speed_ratio = 0.4,
flow_to_energy_ratio = 0.59,
order = "a[fluid]-g[nitrogen-dioxide]"
},
{
type = "recipe",
name = "nitrogen-dioxide-2",
category = "chemistry",
enabled = false,
energy_required = 0.1,
ingredients =
{
{type="fluid", name="nitrogen-oxide", amount=2},
{type="fluid", name="oxygen", amount=1}
},
results=
{
{type="fluid", name="nitrogen-dioxide", amount=2},
{type="item", name="heat-enthalpy1GJ", amount=1},
},
subgroup = "gas-processing",
icon = "__Engineersvsenvironmentalist__/graphics/icons/chemicals/nitrogen-dioxide.png",
order = "b[fluid-chemistry]-b[nitrogen-dioxide]"
},
{
type = "recipe",
name = "nitrogen-dioxide-1",
category = "chemistry",
enabled = false,
energy_required = 0.1,
ingredients =
{
{type="fluid", name="nitrogen-oxide", amount=2},
{type="fluid", name="oxygen", amount=1}
},
results=
{
{type="fluid", name="nitrogen-dioxide", amount=2},
{type="item", name="heat-enthalpy1GJ", amount=1},
},
subgroup = "gas-processing",
icon = "__Engineersvsenvironmentalist__/graphics/icons/chemicals/nitrogen-dioxide.png",
order = "b[fluid-chemistry]-b[nitrogen-dioxide]"
},
}
) |
local table, pairs, next, type, require, ipairs = table, pairs, next, type, require, ipairs
local tostring, debug, error, setmetatable = tostring, debug, error, setmetatable
local checkTypes = require"luv.checktypes".checkTypes
module(...)
table.keys = checkTypes("table", function (self)
local res = {}
for key, _ in pairs(self) do
table.insert(res, key)
end
return res
end, "table")
table.map = checkTypes("table", function (self, func)
local res = {}
for key, val in pairs(self) do
if "string" == type(func) then
res[key] = val[func](val)
else
res[key] = func(val)
end
end
return res
end, "table")
table.imap = checkTypes("table", function (self, func)
local res = {}
for _, val in ipairs(self) do
local newVal
if "string" == type(func) then
newVal = val[func](val)
else
newVal = func(val)
end
if newVal then
table.insert(res, func(val))
end
end
return res
end, "table")
table.ifind = checkTypes("table", function (self, val)
for k, v in ipairs(self) do
if val == v then
return k
end
end
end)
table.find = checkTypes("table", function (self, val)
for k, v in pairs(self) do
if val == v then
return k
end
end
end)
table.iremoveValue = checkTypes("table", function (self, val)
local key = table.ifind(self, val)
if key then
return table.remove(self, key)
end
end)
table.removeValue = checkTypes("table", function (self, val)
local key = table.find(self, val)
if key then
return table.remove(self, key)
end
end)
table.copy = checkTypes("table", function (self)
local res = {}
for k, v in pairs(self) do
res[k] = v
end
return res
end, "table")
table.deepCopy = checkTypes("table", function (tbl, seen)
local res = {}
seen = seen or {}
seen[tbl] = res
for k, v in pairs(tbl) do
if "table" == type(v) then
if seen[v] then
res[k] = seen[v]
else
res[k] = table.deepCopy(v, seen)
end
else
res[k] = v
end
end
seen[tbl] = nil
return res
end, "table")
table.join = checkTypes("table", function (tbl, sep)
local res
sep = sep or ""
for _, v in pairs(tbl) do
res = (res and res..sep or "")..tostring(v)
end
return res or ""
end, "string")
table.ijoin = checkTypes("table", function (self, sep)
local res
sep = sep or ""
for _, v in ipairs(self) do
res = (res and res..sep or "")..tostring(v)
end
return res or ""
end, "string")
table.size = checkTypes("table", function (tbl)
local count = 0
for _ in pairs(tbl) do
count = count + 1
end
return count
end, "number")
table.empty = checkTypes("table", function (self)
return nil == next(self)
end, "boolean")
return table
|
data:extend({
{
type = 'item-subgroup',
name = 'nm-alien-breeding',
group = 'intermediate-products',
order = 'z'
},
})
|
MusicManager = {}
MusicManager.mt = { __index=MusicManager }
MusicManager.tracks = {
{ src=love.audio.newSource("assets/music/1(FLUTE)F.wav", "static"), vol=1 },
{ src=love.audio.newSource("assets/music/1(BASS)F.wav", "static"), vol=1 },
{ src=love.audio.newSource("assets/music/1(BATERIA)F.wav", "static"), vol=1 },
{ src=love.audio.newSource("assets/music/1(TECLADO)F.wav", "static"), vol=1 },
{ src=love.audio.newSource("assets/music/1(STRINGS)F.wav", "static"), vol=1 },
}
MusicManager.loop_time = MusicManager.tracks[1].src:getDuration() / 16 -- 16 compassos no loop
for i, track in ipairs(MusicManager.tracks) do
track.src:setLooping(true)
end
function MusicManager.new()
local t = {}
setmetatable(t, MusicManager.mt)
t:stopAll()
t:playAll()
t:muteAll()
t.timer = 0
t.current_room = 1
t.onLoopEnd = t.onLoopEndFunctions[1]
t.tracks[1].src:setVolume(t.tracks[1].vol)
return t
end
function MusicManager:muteAll()
for i,track in ipairs(self.tracks) do
track.src:setVolume(0)
end
end
function MusicManager:playAll()
for i,track in ipairs(self.tracks) do
track.src:play()
end
end
function MusicManager:stopAll()
for i,track in ipairs(self.tracks) do
track.src:stop()
track.src:rewind()
end
end
function MusicManager:nextRoom()
self.requested_change = true;
self.current_room = self.current_room + 1
self.onLoopEnd = self.onLoopEndFunctions[self.current_room]
end
function MusicManager:update(dt)
self:updateTimer(dt)
if self.timer >= self.loop_time then
self.timer = self.timer - self.loop_time
self:muteAll()
self:onLoopEnd()
if self.requested_change then
self.requested_change = false
end
end
end
function MusicManager:updateTimer(dt)
-- Hacky way of synchronizing the timer with the actual music time
if self.timer < 3 * self.loop_time / 4 then
self.timer = self.tracks[1].src:tell()
else
self.timer = self.timer + dt
end
end
function MusicManager:stage1Music()
local tracks_to_play = { 1 }
for i=1,#tracks_to_play do
self.tracks[tracks_to_play[i]].src:setVolume(self.tracks[tracks_to_play[i]].vol)
end
end
function MusicManager:stage2Music()
local tracks_to_play = { 1, 2, 3 }
for i=1,#tracks_to_play do
self.tracks[tracks_to_play[i]].src:setVolume(self.tracks[tracks_to_play[i]].vol)
end
end
function MusicManager:stage3Music()
local tracks_to_play = { 1, 2, 3, 4 }
for i=1,#tracks_to_play do
self.tracks[tracks_to_play[i]].src:setVolume(self.tracks[tracks_to_play[i]].vol)
end
end
function MusicManager:stage4Music()
local tracks_to_play = { 1, 2, 3, 4, 5 }
for i=1,#tracks_to_play do
self.tracks[tracks_to_play[i]].src:setVolume(self.tracks[tracks_to_play[i]].vol)
end
end
function MusicManager:stage5Music()
local tracks_to_play = { 1, 2, 3, 4, 5 }
for i=1,#tracks_to_play do
self.tracks[tracks_to_play[i]].src:setVolume(self.tracks[tracks_to_play[i]].vol)
end
end
MusicManager.onLoopEndFunctions = {
MusicManager.stage1Music,
MusicManager.stage2Music,
MusicManager.stage3Music,
MusicManager.stage4Music,
MusicManager.stage5Music,
}
|
--[[
This module was written by @Vyon, and is another way to create and handle custom signals without the use of filthy instances like
bindable events! (jokes)
[Signal.lua]:
[Methods]:
New():
Constructs an object from the signal class.
@params: None
@ret: (signal: Dictionary<string>)
Connect( self, callback ):
Creates a new thread to handle the callback.
@params: (self: Dictionary<string>, callback: Function)
@ret: (connection: Dictionary<string>)
Disconnect():
Closes the handler thread and removes it from _Callbacks for cleanup
@params: None
@ret: nil
Fire( self, ... ):
Loops through all saved callbacks and fires to each of them with the given arguments
@params: (self: Dictionary<string>, ...: any)
@ret: nil
Wait():
Yields the current thread until the fire method is used.
@params: None
@ret: (arguments: Array<number>)
--]]
local signal = {}
signal.__index = signal
signal.__type = 'LunarScriptSignal'
function signal.New()
local self = setmetatable({}, signal)
self._Callbacks = {}
self._Args = nil
return self
end
function signal:Connect(callback: any)
local index = #self._Callbacks + 1
table.insert(self._Callbacks, callback)
return {
Disconnect = function()
self._Callbacks[index] = nil
end
}
end
function signal:Fire(...)
for _, callback in pairs(self._Callbacks) do
task.spawn(callback, ...)
end
self._Args = {...}
task.wait()
self._Args = nil
end
function signal:Wait()
local _Args = nil
repeat _Args = self._Args task.wait() until _Args
return _Args
end
return signal |
local GeneEngineering = {}
local Rand = require("api.Rand")
local Skill = require("mod.elona_sys.api.Skill")
local Gui = require("api.Gui")
local Chara = require("api.Chara")
local ChooseAllyMenu = require("api.gui.menu.ChooseAllyMenu")
local Input = require("api.Input")
local Anim = require("mod.elona_sys.api.Anim")
local I18N = require("api.I18N")
local Save = require("api.Save")
local CharacterInfoMenu = require("api.gui.menu.CharacterInfoMenu")
-- TODO data_ext
local NON_DONATABLE_BODY_PARTS = table.set {
"elona.ammo",
"elona.ranged",
"elona.body",
}
local function can_donate_body_parts(donor)
if donor:has_tag("man") then
return false
end
if donor.splits or donor.splits2 then
return false
end
return true
end
function GeneEngineering.calc_donated_body_part(target, donor)
-- >>>>>>>> shade2/action.hsp:2228 *gene_body ...
if not can_donate_body_parts(donor) then
return nil
end
-- NOTE: Unlike vanilla, there is no check for free body part slots, since
-- there is no longer a hard body part limit per character.
-- Exclude some parts like ammo/ranged (they come on all characters)
local filter = function(part)
return not NON_DONATABLE_BODY_PARTS[part.body_part._id]
end
local parts = donor:iter_all_body_parts(true):filter(filter):to_list()
Rand.set_seed(donor.uid)
Rand.shuffle(parts)
-- If the target does not have a body part, then always donate it
local does_not_have_part = function(part)
return target:body_part_count(part.body_part._id) == 0
end
local body_part = fun.iter(parts):filter(does_not_have_part):nth(1)
if body_part then
Rand.set_seed()
return {
_id = body_part.body_part._id,
slot = body_part.slot
}
end
-- Find a part whose total number on the donor is greater than the number on
-- the target, and donate that.
local fold = function(acc, part)
acc[part.body_part._id] = (acc[part.body_part._id] or 0) + 1
return acc
end
local counts = fun.iter(parts):foldl(fold, {})
local body_part_ids = table.keys(counts)
Rand.shuffle(body_part_ids)
local found_id = nil
for _, body_part_id in ipairs(body_part_ids) do
local count = counts[body_part_ids]
if count and count < target:body_part_count(body_part_id) then
found_id = body_part_id
break
end
end
Rand.set_seed()
if not found_id then
return nil
end
body_part = assert(fun.iter(parts):filter(function(p) return p.body_part._id == found_id end):nth(1))
return {
_id = found_id,
slot = body_part.slot
}
-- <<<<<<<< shade2/action.hsp:2272 if f=falseM:return rtval(1):else:return falseM ..
end
local function can_donate_skills(donor)
return not (donor.splits or donor.splits2)
end
function GeneEngineering.calc_donated_skills(target, donor)
-- >>>>>>>> shade2/action.hsp:2208 *gene_skill ...
if not can_donate_skills(donor) then
return {}
end
-- Find skills not on the target that are on the donor.
-- NOTE: This counts temporary skill levels, as with vanilla (sdata instead
-- of sORG)
local filter = function(skill)
return not target:has_skill(skill._id) and donor:has_skill(skill._id)
end
local skills = Skill.iter_normal_skills()
:filter(filter)
:to_list()
if #skills == 0 then
return {}
end
Rand.set_seed(donor.uid)
Rand.shuffle(skills)
local result = { skills[1] }
if Rand.one_in(3) then
local filter = function(s) return s._id ~= skills[1]._id end
result[#result+1] = fun.iter(skills):filter(filter):nth(1)
end
local to_entry = function(s)
return { _id = s._id, level = 1 }
end
Rand.set_seed()
return fun.iter(result):map(to_entry):to_list()
-- <<<<<<<< shade2/action.hsp:2226 return dbMax ..
end
function GeneEngineering.calc_gained_levels(target, donor)
-- >>>>>>>> shade2/action.hsp:2142 if cLevel(tc)>cLevel(rc){ ...
if donor.level <= target.level then
return 0
end
return math.floor((donor.level - target.level) / 2) + 1
-- <<<<<<<< shade2/action.hsp:2143 lv=(cLevel(tc)-cLevel(rc))/2+1 ..
end
function GeneEngineering.calc_gained_stat_experience(target, donor, level_diff)
-- >>>>>>>> shade2/action.hsp:2149 listMax=0 ...
if level_diff <= 0 then
return {}
end
local stats = {}
local org_level = function(stat)
return { _id = stat._id, level = donor:base_skill_level(stat._id) }
end
local sort = function(a, b)
return a.level > b.level
end
local highest_donor_stats = Skill.iter_base_attributes()
:map(org_level)
:into_sorted(sort)
:take(3)
:to_list()
for _, entry in ipairs(highest_donor_stats) do
local target_level = target:base_skill_level(entry._id)
if entry.level > target_level then
-- The target character can gain at most 5 levels for each stat.
local experience = (entry.level - target_level) * 500
experience = math.clamp(experience * 10 / math.clamp(level_diff, 2, 10), 1000, 10000)
stats[#stats+1] = {
_id = entry._id,
experience = experience
}
end
end
return stats
-- <<<<<<<< shade2/action.hsp:2161 loop ..
end
function GeneEngineering.do_gene_engineer(target, donor)
local body_part = GeneEngineering.calc_donated_body_part(target, donor)
if body_part then
local body_part_name = I18N.localize("base.body_part", body_part._id, "name")
Gui.mes_c("action.use.gene_machine.gains.body_part", "Green", target, body_part_name)
target:add_body_part(body_part._id)
end
local skills = GeneEngineering.calc_donated_skills(target, donor)
for _, skill in ipairs(skills) do
Skill.gain_skill(target, skill._id, skill.level)
local skill_name = I18N.localize("base.skill", skill._id, "name")
Gui.mes_c("action.use.gene_machine.gains.ability", "Green", target, skill_name)
end
local levels = GeneEngineering.calc_gained_levels(target, donor)
local stats = GeneEngineering.calc_gained_stat_experience(target, donor, levels)
if levels > 0 then
for _ = 1, levels do
Skill.gain_level(target, false)
end
Gui.mes_c("action.use.gene_machine.gains.level", "Green", target, target.level)
end
if stats then
for _, entry in ipairs(stats) do
Skill.gain_fixed_skill_exp(target, entry._id, entry.experience)
end
end
donor:vanquish()
end
function GeneEngineering.can_gene_engineer(chara, target)
return chara:skill_level("elona.gene_engineer") + 5 >= target.level
end
function GeneEngineering.use_gene_machine(chara, item)
local COLOR_INVALID = {160, 10, 10}
local topic_list_colorizer = function(self, c)
if not GeneEngineering.can_gene_engineer(chara, c) then
return COLOR_INVALID
end
end
local topic_on_select = function(self, c)
if not GeneEngineering.can_gene_engineer(chara, c) then
Gui.play_sound("base.fail1")
Gui.mes("ui.ally_list.gene_engineer.skill_too_low")
return false
end
return true
end
local target, donor
local filter = function(ally) return Chara.is_alive(ally) and ally ~= target end
do
Gui.mes_newline()
Gui.mes("action.use.gene_machine.choose_original")
local topic = {
window_title = "ui.ally_list.gene_engineer.title",
x_offset = 0,
list_colorizer = topic_list_colorizer,
on_select = topic_on_select
}
local allies = chara:iter_other_party_members():filter(filter):to_list()
Gui.mes("ui.ally_list.gene_engineer.prompt")
local result, canceled = ChooseAllyMenu:new(allies, topic):query()
if canceled then
return false
end
target = result.chara
end
do
Gui.mes_newline()
Gui.mes("action.use.gene_machine.choose_subject")
local topic = {
window_title = "ui.ally_list.gene_engineer.title",
header_status = "ui.ally_list.gene_engineer.body_skill",
x_offset = 0,
list_colorizer = topic_list_colorizer,
on_select = topic_on_select
}
topic.info_formatter = function(c)
-- >>>>>>>> shade2/command.hsp:563 if allyCtrl=5 :if rc!0{ ...
local body_part = GeneEngineering.calc_donated_body_part(target, c)
local skills = GeneEngineering.calc_donated_skills(target, c)
local body_part_name
if body_part then
body_part_name = I18N.localize("base.body_part", body_part._id, "name")
else
body_part_name = I18N.get("ui.ally_list.gene_engineer.none")
end
local skill_names
if #skills > 0 then
local localize = function(s) return I18N.localize("base.skill", s._id, "name") end
local names = fun.iter(skills):map(localize):to_list()
skill_names = table.concat(names, ", ")
else
skill_names = I18N.get("ui.ally_list.gene_engineer.none")
end
return ("%s/%s"):format(body_part_name, skill_names)
-- <<<<<<<< shade2/command.hsp:566 } ..
end
local allies = chara:iter_other_party_members():filter(filter):to_list()
Gui.mes("ui.ally_list.gene_engineer.prompt")
local result, canceled = ChooseAllyMenu:new(allies, topic):query()
if canceled then
return false
end
donor = result.chara
end
Gui.mes_newline()
Gui.mes("action.use.gene_machine.prompt", target, donor)
if not Input.yes_no() then
return false
end
Gui.mes_newline()
Gui.mes_c("action.use.gene_machine.has_inherited", "Yellow", target, donor)
local cb = Anim.gene_engineering(target.x, target.y)
Gui.start_draw_callback(cb)
GeneEngineering.do_gene_engineer(target, donor)
Save.queue_autosave()
Skill.gain_skill_exp(chara, "elona.gene_engineer", 1200)
CharacterInfoMenu:new(target, "ally_status"):query()
return true
end
return GeneEngineering
|
---@class Font : FontInstance
---[Documentation](https://wow.gamepedia.com/UIOBJECT_Font)
local Font = {}
---[Documentation](https://wow.gamepedia.com/API_Font_CopyFontObject)
function Font:CopyFontObject(otherFont) end
---[Documentation](https://wow.gamepedia.com/API_Font_GetAlpha)
function Font:GetAlpha() end
---[Documentation](https://wow.gamepedia.com/API_Font_SetAlpha)
function Font:SetAlpha(alpha) end
|
-- provides collect, submit at study or series level
-- test version 20120719
function split(str, pat)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t,cap)
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cap)
end
return t
end
function findpattern(text, pattern, start)
if string.find(text, pattern, start) then
return string.sub(text, string.find(text, pattern, start))
else
return ""
end
end
HTML('Content-type: text/html\n\n');
print([[
<H3>Conquest DICOM server version: ]]..version..[[</H3>
<p> </p>
<p><b><font color = #FF0000"></p>
<div id = "pbar"></div></b></font>
<script type = "text/javascript">
var percent = 0; // adjust starting value to suit
var timePeriod = 100; // adjust milliseconds to suit
var status='';
function getBar()
{ var retBar = '';
for (i = 0; i < percent/2; i++) {retBar += "|";}
return retBar;
}
function progressBar()
{ if (percent >= 0)
{ document.getElementById("pbar").innerHTML = "        Loading : " + percent + " %" + " " + getBar();
setTimeout ("progressBar()", timePeriod);
}
else
{ document.getElementById("pbar").innerHTML = "";
document.body.style.display = "";
}
}
function Status()
{ document.getElementById("myframe").src = "]]..script_name..[[?mode=OpenClinica/SubmitStatus";
setTimeout ("Status()", timePeriod);
}
</script>
]])
local key, source;
key = CGI('key')
source = gpps('OpenClinica', 'Source', '(local)');
if CGI('option')=='collectstudy' or CGI('option')=='collectseries' then
print([[
<script>
progressBar();
</script>
]])
if source=='(local)' then
s = servercommand('get_param:MyACRNema')
else
s = source;
end
b=newdicomobject();
b.PatientID = CGI('patientid');
b.StudyInstanceUID = CGI('studyuid');
b.SeriesInstanceUID = CGI('seriesuid', '')
b.QueryRetrieveLevel = 'SERIES'
-- it is possible to anonymize here (add private tag; the script should set OID's)
-- b.['9999,0900']='call anonymize.lua';
HTML('<H3>Collecting data set</H3>')
dicommove(s, servercommand('get_param:MyACRNema'), b,
[[--print(Global.StatusString);
--print'<br>'
print('<script>percent=')
print(math.floor(100*Command.NumberOfCompletedSuboperations/
(Command.NumberOfCompletedSuboperations+Command.NumberOfRemainingSuboperations)))
print('</script>')
]]
);
HTML('<H3>Done collecting data</H3>')
print([[<script>percent = -1;</script>]])
end
if CGI('option')=='submitstudy' or CGI('option')=='submitseries' then
print([[
<iframe id="myframe" BORDER=0 HEIGHT=80>
<p>Your browser does not support iframes.</p>
</iframe>
<script>
Status()
</script>
<script>
timePeriod=200
</script>
]])
local targetserver = gpps('OpenClinica', 'TargetServer', '[email protected]:');
local password = gpps('OpenClinica', 'Password', 'xxxxxxx');
HTML('<H3>Submitting data to ECRF</H3>');
HTML('Key = ' .. CGI('key'));
HTML('<br>');
HTML('PatientID=' .. CGI('patientid'));
HTML('<br>');
HTML('StudyUID=' .. CGI('studyuid'));
HTML('<br>');
HTML('SeriesUID=' .. CGI('seriesuid', ''));
-- it is possible to anonymize below here (replace nop by script; the script should set OID's)
servercommand('submit:'..CGI('patientid')..','..CGI('studyuid')..','..CGI('seriesuid', '')
..',,'..targetserver..','..password..',anonymize_script.cq')
--HTML('submit:'..CGI('patientid')..','..CGI('studyuid')..','..CGI('seriesuid', '')
-- ..',,'..targetserver..','..password..',nop');
HTML('<br>')
HTML('<br>')
print([[
<script>
timePeriod=1000
</script>
]])
end
--print([[
--<a href="#" onclick="history.go(-1)">Return</a>
--]])
|
local gfx = require("/dynamic/helpers/mesh_helpers.lua")
local w = 100
function new_bullet(frame)
local mesh = gfx.new_mesh()
local angle_offset = 6.28318530718 * frame / 32
for y_loop = -1,1,1 do
local y_offset = y_loop * 13
local vertexes = {}
local colors = {}
for x=-20,20, 3 do
local y = 10 * math.cos(angle_offset + (x / 5))
table.insert(vertexes, {x, y + y_offset})
table.insert(colors, 0x00ffffff)
end
gfx.add_line_to_mesh(mesh, vertexes, colors, false)
end
return mesh
end
meshes = {}
for i=1,32 do
table.insert(meshes, new_bullet(i))
end
|
----------------------------------------------------------------------------
-------------------------- Stick creator -------------------------------
----------------------------------------------------------------------------
function gooi.newJoy(params)
params = params or {}
local s = {}
local defSize = gooi.unit * 4
local x, y, w, h = gooi.checkBounds(
"..........",
params.x or 10,
params.y or 10,
params.w or defSize,
params.h or defSize,
"joystick"
)
-- Note that the sitck has x and y on the center.
s = component.new("joystick", x, y, params.size or defSize, params.size or defSize, params.group)
s = gooi.setStyleComp(s)
s.radiusCorner = s.h / 2
s.deadZone = params.deadZone or 0 -- Given in percentage (0 to 1).
if s.deadZone < 0 then s.deadZone = 0 end
if s.deadZone > 1 then s.deadZone = 1 end
s.stickPressed = false
s.dx, s.dy = 0, 0
s.spring = true
s.sxImg, s.syImg = 1, 1
s.digitalH, s.digitalV = "", ""
function s:drawSpecifics(fg)
love.graphics.setColor(fg)
self:drawStick()
end
function s:rebuild()
self.r = self.smallerSide / 2
self.rStick = self.r / 2
self.xStick = (self.x) + (self.r)
self.yStick = (self.y) + (self.r)
--self:generateBorder()
end
s:rebuild()
function s:setImage(image)
if image then
if type(image) == "string" then
image = love.graphics.newImage(image)
end
self.image = image
self.image:setFilter("linear", "linear")
end
return self
end
s:setImage(params.image)
function s:noScaling()
self.notS = true
return self
end
function s:anyPoint()
self.anyP = true
return self
end
function s:setDigital(directions)-- 4 or 8
if directions and
directions ~= "4" and
directions ~= "8" then
end
self.digital = directions or "8"
return self
end
function s:drawStick()
local fg = self.style.fgColor
if self.image then
love.graphics.setColor(1, 1, 1, fg[4] or 1)
local sx = self.rStick * 2 / self.image:getWidth()
local sy = self.rStick * 2 / self.image:getHeight()
local x, y = self.xStick, self.yStick
if self.notS then
sx, sy = 1, 1
x, y = (self.xStick), (self.yStick)
end
if self.digital then
x, y = self:computeDigital()
end
love.graphics.draw(self.image,
math.floor(x), math.floor(y),
0, sx, sy,
self.image:getWidth() / 2,
self.image:getHeight() / 2)
else
local x = self.xStick
local y = self.yStick
if self.digital then
x, y = self:computeDigital()
end
love.graphics.circle("line", math.floor(x), math.floor(y), self.rStick, circleRes)
end
end
function s:computeDigital()
-- horizontal directions:
local xv = self:xValue()
local yv = self:yValue()
if self.digital == "8" then
-- horizontal direction:
if xv < -0.5 then
self.digitalH = "l"
x = self.x + self.rStick
elseif xv > 0.5 then
self.digitalH = "r"
x = self.x + self.w - self.rStick
else
self.digitalH = ""
x = self.x + self.w / 2
end
--vertical:
if yv < -0.5 then
self.digitalV = "t"
y = self.y + self.rStick
elseif yv > 0.5 then
self.digitalV = "b"
y = self.y + self.h - self.rStick
else
self.digitalV = ""
y = self.y + self.h / 2
end
elseif self.digital == "4" then-- 4 directions joystick:
--ToDo
end
return x, y
end
function s:move(direction)
if (self.pressed or self.touch) and self.stickPressed then
local daX, daY = love.mouse.getPosition()
daX = daX / gooi.sx
daY = daY / gooi.sy
if self.touch then
daX, daY = self.touch.x, self.touch.y
end
if self:butting() then
local dX = self:theX() - daX - self.dx
local dY = self:theY() - daY - self.dy
local angle = (math.atan2(dY, dX) + math.rad(180));
self.xStick = self.x + (self.r - self.rStick) * math.cos(angle) + self.r
self.yStick = self.y + (self.r - self.rStick) * math.sin(angle) + self.r
else
self.xStick, self.yStick = daX + self.dx, daY + self.dy
end
end
end
function s:restore()
if self.spring then
self.xStick, self.yStick = self:theX(), self:theY()
end
self.stickPressed = false
self.dx = 0
self.dy = 0
end
function s:noSpring()
self.spring = false
return self
end
function s:butting()
local hyp = 0
local daX, daY = love.mouse.getPosition()
daX = daX / gooi.sx
daY = daY / gooi.sy
if self.touch then
daX, daY = self.touch.x, self.touch.y
end
hyp = math.sqrt(
math.pow(self:theX() - daX - self.dx, 2) +
math.pow(self:theY() - daY - self.dy, 2))
return hyp >= self.r - self.rStick
end
-- Get numbers with presicion of two decimals:
function s:xValue()
if self:onDeadZone() then return 0 end
return gooi.round((self.xStick - self:theX()) / (self.r - self.rStick), 2)
end
function s:yValue()
if self:onDeadZone() then return 0 end
return gooi.round((self.yStick - self:theY()) / (self.r - self.rStick), 2)
end
function s:direction()
if self.digital then
return self.digitalV..self.digitalH
else
return ""
end
end
function s:overStick(x, y)
local dx = (self.xStick - x)
local dy = (self.yStick - y)
return math.sqrt(math.pow(dx, 2) + math.pow(dy, 2)) < self.rStick * 1.1
end
function s:onDeadZone()
local dx, dy = self:theX() - self.xStick, self:theY() - self.yStick
return math.sqrt(math.pow(dx, 2) + math.pow(dy, 2)) <= self.deadZone * (self.r - self.rStick)
end
function s:theX() return (self.x) + (self.r) end
function s:theY() return (self.y) + (self.r) end
return gooi.storeComponent(s, id)
end
|
local t = require( "taptest" )
local isleafdir = require( "isleafdir" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )
-- setup
t( mkdirtree{
[ "middir" ] = {
[ "leafdir" ] = {
[ "tmpfile.txt" ] = ""
}
}
}, true )
-- test
t( isleafdir( "middir/leafdir" ), true )
t( isleafdir( "middir" ), false )
-- teardown
t( rmdirtree( "middir" ), true )
t()
|
--NPC CODES
--Assassins
--Orcs
--Skeletons
--Noobs
--Chocolate Zombies
--Overlord
--Werewolf
--Cactus King
--Guest
--Snowmen
--Gingerbread Men
--Frost Guard
--THE SCRIPT
_G.Fuck = true -- false to Turn Off
local enemi = game.Workspace.Enemies.Assassins -- Change Assasins to Any NPC you want
while _G.Fuck do
wait()
game.Players.LocalPlayer.Character.Humanoid.Health = math.huge
for _,v in pairs(enemi:GetChildren()) do
game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = v.HumanoidRootPart.CFrame+Vector3.new(1, 0, 0)
end
end |
A={
boneCorrespondences ={
Head ="Neck",
Hips ="Hips",
LeftArm ="LeftShoulder",
LeftFoot ="LeftAnkle",
LeftForeArm ="LeftElbow",
LeftLeg ="LeftKnee",
LeftUpLeg ="LeftHip",
RightArm ="RightShoulder",
RightFoot ="RightAnkle",
RightForeArm ="RightElbow",
RightLeg ="RightKnee",
RightUpLeg ="RightHip",
Spine ="Chest",
},
reusePreviousBinding =true,
skel ="/home/taesoobear/taesooLib_full/Resource/motion/woody/wd2_2foot_walk_turn2.bvh",
skinScale =1.06,
}
B={
EE ={
},
motion ="../Resource/motion/locomotion_hyunwoo/hyunwoo_lowdof_T_locomotion_hl.dof",
skel ="../Resource/motion/locomotion_hyunwoo/hyunwoo_lowdof_T.wrl",
skinScale =100,
}
bindposes={{"__userdata", "vectorn", {0, 100.42400360107, 0, 0.99891659345597, -0.027958918822979, -0.037140004628999, 0.0021350018084217, -0.047300691242952, 0.019897799762149, -0.13283299904816, -0.028409597581773, 0.15702343998049, -0.18005340846782, 0.08821801837958, -0.095184673021281, -0.004445824947724, 0.00080642591900343, 9.2657614482197e-06, 0.011565284698752, 0.01736866121363, -0.19666196293474, 0.001684235738417, 0.0054879432889613, 0.46042310177187, -0.003466119243049, 0.043832023791665, -0.2206288148488, -0.080516747395938, -0.70411122981426, 0.16133892607939, -0.28206264816426, -0.71217634685946, -0.54621823444835, -0.17031464448032, -0.23905426103516, 0.29425553174103, -0.1480927622915, 0.38798318932993, 0.15695920786395, 0.010200681996493, 0.88324130368739, 0.23914326054984, 0.34087153675129, 0.31915265911336, -0.76722581738318, -0.045633901940456, 0.12661264536768, 0.5309832552479, 0.13632312991336, -0.11774427732583, 0.16541444471933, 0.04926767705695, 0.028276951353541, 0.0017205943891547, 0.11442552919916, 0.019266688840449, 0.15956690862433, 0.36049600463943, -0.078193547141386, -0.068716929751313, 0.0025652849786066, -2.3603832276699e-11, 1.5275436283235e-07, -2.5657038150668e-10, }, }, {"__userdata", "vectorn", {0.0026619609288237, 0.992, 0.0025358482855842, 0.99963331117671, 0.0024290896128339, -0.026601687908946, 0.0044376694250666, 0.022682924220343, 0.044880141416971, -0.031737288359185, 0.055948861451972, 0.22598124879198, 0.12570346060904, -0.036067167154379, -0.040065486295269, -0.026188686949655, 0.091038330188987, -0.31860630194633, 0.18089397238159, -0, -0, -0, -1.4065246085983, 0.38458757170633, -0.047071976056341, -0.29445151074821, 1.4472115342761, 0.51698299822646, -0.17639680420731, 0.39659474303259, -0, -0, -0, }, }, } |
----------------------------------------------------------------------------------
-- Total RP 3
-- Directory
-- ---------------------------------------------------------------------------
-- Copyright 2014 Sylvain Cossement ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
----------------------------------------------------------------------------------
---@type TRP3_API
local _, TRP3_API = ...;
local Ellyb = Ellyb(...);
-- imports
local Globals, Events = TRP3_API.globals, TRP3_API.events;
local Utils = TRP3_API.utils;
local stEtN = Utils.str.emptyToNil;
local loc = TRP3_API.loc;
local get = TRP3_API.profile.getData;
local assert, table, _G, date, pairs, error, tinsert, wipe, time = assert, table, _G, date, pairs, error, tinsert, wipe, time;
local isUnitIDKnown, getCharacterList = TRP3_API.register.isUnitIDKnown, TRP3_API.register.getCharacterList;
local unitIDToInfo, tsize = Utils.str.unitIDToInfo, Utils.table.size;
local handleMouseWheel = TRP3_API.ui.list.handleMouseWheel;
local initList = TRP3_API.ui.list.initList;
local setTooltipForSameFrame = TRP3_API.ui.tooltip.setTooltipForSameFrame;
local isMenuRegistered = TRP3_API.navigation.menu.isMenuRegistered;
local registerMenu, selectMenu, openMainFrame = TRP3_API.navigation.menu.registerMenu, TRP3_API.navigation.menu.selectMenu, TRP3_API.navigation.openMainFrame;
local registerPage, setPage = TRP3_API.navigation.page.registerPage, TRP3_API.navigation.page.setPage;
local setupFieldSet = TRP3_API.ui.frame.setupFieldPanel;
local getUnitIDCharacter = TRP3_API.register.getUnitIDCharacter;
local getUnitIDProfile = TRP3_API.register.getUnitIDProfile;
local hasProfile = TRP3_API.register.hasProfile;
local getCompleteName, getPlayerCompleteName = TRP3_API.register.getCompleteName, TRP3_API.register.getPlayerCompleteName;
local TRP3_RegisterListEmpty = TRP3_RegisterListEmpty;
local getProfile, getProfileList = TRP3_API.register.getProfile, TRP3_API.register.getProfileList;
local getIgnoredList, unignoreID, isIDIgnored = TRP3_API.register.getIgnoredList, TRP3_API.register.unignoreID, TRP3_API.register.isIDIgnored;
local getRelationText, getRelationTooltipText = TRP3_API.register.relation.getRelationText, TRP3_API.register.relation.getRelationTooltipText;
local unregisterMenu = TRP3_API.navigation.menu.unregisterMenu;
local displayDropDown, showAlertPopup, showConfirmPopup = TRP3_API.ui.listbox.displayDropDown, TRP3_API.popup.showAlertPopup, TRP3_API.popup.showConfirmPopup;
local showTextInputPopup = TRP3_API.popup.showTextInputPopup;
local deleteProfile, deleteCharacter, getProfileList = TRP3_API.register.deleteProfile, TRP3_API.register.deleteCharacter, TRP3_API.register.getProfileList;
local toast = TRP3_API.ui.tooltip.toast;
local ignoreID = TRP3_API.register.ignoreID;
local refreshList;
local NOTIFICATION_ID_NEW_CHARACTER = TRP3_API.register.NOTIFICATION_ID_NEW_CHARACTER;
local getCurrentPageID = TRP3_API.navigation.page.getCurrentPageID;
local checkGlanceActivation = TRP3_API.register.checkGlanceActivation;
local getCompanionProfiles = TRP3_API.companions.register.getProfiles;
local getRelationColors = TRP3_API.register.relation.getRelationColors;
local getCompanionNameFromSpellID = TRP3_API.companions.getCompanionNameFromSpellID;
local safeMatch = TRP3_API.utils.str.safeMatch;
local unitIDIsFilteredForMatureContent = TRP3_API.register.unitIDIsFilteredForMatureContent;
local profileIDISFilteredForMatureContent = TRP3_API.register.profileIDISFilteredForMatureContent;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Logic
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local REGISTER_LIST_PAGEID = "register_list";
local playerMenu = "main_10_player";
local currentlyOpenedProfilePrefix = TRP3_API.register.MENU_LIST_ID_TAB;
local REGISTER_PAGE = TRP3_API.register.MENU_LIST_ID;
local function openPage(profileID, unitID)
local profile = getProfile(profileID);
if isMenuRegistered(currentlyOpenedProfilePrefix .. profileID) then
-- If the character already has his "tab", simply open it
selectMenu(currentlyOpenedProfilePrefix .. profileID);
else
-- Else, create a new menu entry and open it.
local tabText = UNKNOWN;
if profile.characteristics and profile.characteristics.FN then
tabText = profile.characteristics.FN;
end
registerMenu({
id = currentlyOpenedProfilePrefix .. profileID,
text = tabText,
onSelected = function() setPage("player_main", {profile = profile, profileID = profileID}) end,
isChildOf = REGISTER_PAGE,
closeable = true,
icon = "Interface\\ICONS\\pet_type_humanoid",
});
selectMenu(currentlyOpenedProfilePrefix .. profileID);
if (unitID and unitIDIsFilteredForMatureContent(unitID)) or (profileID and profileIDISFilteredForMatureContent(profileID)) then
TRP3_API.popup.showPopup("mature_filtered");
TRP3_MatureFilterPopup.profileID = profileID;
TRP3_MatureFilterPopup.unitID = unitID;
TRP3_MatureFilterPopup.menuID = currentlyOpenedProfilePrefix .. profileID;
end
end
end
TRP3_API.register.openPageByProfileID = openPage;
local function openCompanionPage(profileID)
local profile = getCompanionProfiles()[profileID];
if isMenuRegistered(currentlyOpenedProfilePrefix .. profileID) then
-- If the character already has his "tab", simply open it
selectMenu(currentlyOpenedProfilePrefix .. profileID);
else
-- Else, create a new menu entry and open it.
local tabText = UNKNOWN;
if profile.data and profile.data.NA then
tabText = profile.data.NA;
end
registerMenu({
id = currentlyOpenedProfilePrefix .. profileID,
text = tabText,
onSelected = function() setPage(TRP3_API.navigation.page.id.COMPANIONS_PAGE, {profile = profile, profileID = profileID, isPlayer = false}) end,
isChildOf = REGISTER_PAGE,
closeable = true,
icon = "Interface\\ICONS\\pet_type_beast",
});
selectMenu(currentlyOpenedProfilePrefix .. profileID);
end
end
TRP3_API.companions.register.openPage = openCompanionPage;
local function openPageByUnitID(unitID)
if unitID == Globals.player_id then
selectMenu(playerMenu);
elseif isUnitIDKnown(unitID) and hasProfile(unitID) then
openPage(hasProfile(unitID), unitID);
end
end
TRP3_API.register.openPageByUnitID = openPageByUnitID;
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local sortingType = 1;
local function switchNameSorting()
sortingType = sortingType == 2 and 1 or 2;
refreshList();
end
local function switchInfoSorting()
sortingType = sortingType == 4 and 3 or 4;
refreshList();
end
local function switchTimeSorting()
sortingType = sortingType == 6 and 5 or 6;
refreshList();
end
local function nameComparator(elem1, elem2)
return elem1[2]:lower() < elem2[2]:lower();
end
local function nameComparatorInverted(elem1, elem2)
return elem1[2]:lower() > elem2[2]:lower();
end
local function infoComparator(elem1, elem2)
return elem1[3]:lower() < elem2[3]:lower();
end
local function infoComparatorInverted(elem1, elem2)
return elem1[3]:lower() > elem2[3]:lower();
end
local function timeComparator(elem1, elem2)
return elem1[4] < elem2[4];
end
local function timeComparatorInverted(elem1, elem2)
return elem1[4] > elem2[4];
end
local comparators = {
nameComparator, nameComparatorInverted, infoComparator, infoComparatorInverted, timeComparator, timeComparatorInverted
}
local function getCurrentComparator()
return comparators[sortingType];
end
local ARROW_DOWN = "Interface\\Buttons\\Arrow-Down-Up";
local ARROW_UP = "Interface\\Buttons\\Arrow-Up-Up";
local ARROW_SIZE = 15;
local function getComparatorArrows()
local nameArrow, relationArrow, timeArrow = "", "", "";
if sortingType == 1 then
nameArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 2 then
nameArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 3 then
relationArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 4 then
relationArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 5 then
timeArrow = " |T" .. ARROW_DOWN .. ":" .. ARROW_SIZE .. "|t";
elseif sortingType == 6 then
timeArrow = " |T" .. ARROW_UP .. ":" .. ARROW_SIZE .. "|t";
end
return nameArrow, relationArrow, timeArrow;
end
local MODE_CHARACTER, MODE_PETS, MODE_IGNORE = 1, 2, 3;
local selectedIDs = {};
local ICON_SIZE = 30;
local currentMode = 1;
local DATE_FORMAT = "%d/%m/%y %H:%M";
local IGNORED_ICON = Utils.str.texture("Interface\\Buttons\\UI-GroupLoot-Pass-Down", 15);
local GLANCE_ICON = Utils.str.texture("Interface\\MINIMAP\\TRACKING\\None", 15);
local NEW_ABOUT_ICON = Utils.str.texture("Interface\\Buttons\\UI-GuildButton-PublicNote-Up", 15);
local MATURE_CONTENT_ICON = Utils.str.texture("Interface\\AddOns\\totalRP3\\resources\\18_emoji.tga", 15);
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : CHARACTERS
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local characterLines = {};
local function decorateCharacterLine(line, characterIndex)
local profileID = characterLines[characterIndex][1];
local profile = getProfile(profileID);
line.id = profileID;
local name = getCompleteName(profile.characteristics or {}, UNKNOWN, true);
local leftTooltipTitle, leftTooltipText = name, "";
_G[line:GetName().."Name"]:SetText(name);
if profile.characteristics and profile.characteristics.IC then
leftTooltipTitle = Utils.str.icon(profile.characteristics.IC, ICON_SIZE) .. " " .. name;
end
local hasGlance = profile.misc and profile.misc.PE and checkGlanceActivation(profile.misc.PE);
local hasNewAbout = profile.about and not profile.about.read;
local atLeastOneIgnored = false;
_G[line:GetName().."Info2"]:SetText("");
local firstLink;
if profile.link and tsize(profile.link) > 0 then
leftTooltipText = leftTooltipText .. loc.REG_LIST_CHAR_TT_CHAR;
for unitID, _ in pairs(profile.link) do
if not firstLink then
firstLink = unitID;
end
local unitName, unitRealm = unitIDToInfo(unitID);
if isIDIgnored(unitID) then
leftTooltipText = leftTooltipText .. "\n|cffff0000 - " .. unitName .. " ( " .. unitRealm .. " ) - " .. IGNORED_ICON .. " " .. loc.REG_LIST_CHAR_IGNORED;
atLeastOneIgnored = true;
else
leftTooltipText = leftTooltipText .. "\n|cff00ff00 - " .. unitName .. " ( " .. unitRealm .. " )";
end
end
else
leftTooltipText = leftTooltipText .. "|cffffff00" .. loc.REG_LIST_CHAR_TT_CHAR_NO;
end
if profile.time and profile.zone then
local formatDate = date(DATE_FORMAT, profile.time);
leftTooltipText = leftTooltipText .. "\n|r" .. loc.REG_LIST_CHAR_TT_DATE:format(formatDate, profile.zone);
end
-- Middle column : relation
local relation, relationRed, relationGreen, relationBlue = getRelationText(profileID), getRelationColors(profileID);
local color = Utils.color.colorCode(relationRed * 255, relationGreen * 255, relationBlue * 255);
if relation:len() > 0 then
local middleTooltipTitle, middleTooltipText = relation, getRelationTooltipText(profileID, profile);
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"], "TOPLEFT", 0, 5, middleTooltipTitle, color .. middleTooltipText);
else
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
end
_G[line:GetName().."Info"]:SetText(color .. relation);
local timeStr = "";
if profile.time then
timeStr = date(DATE_FORMAT, profile.time);
end
_G[line:GetName().."Time"]:SetText(timeStr);
-- Third column : flags
local rightTooltipTitle, rightTooltipText, flags;
if atLeastOneIgnored then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. IGNORED_ICON;
rightTooltipText = rightTooltipText .. IGNORED_ICON .. " " .. loc.REG_LIST_CHAR_TT_IGNORE;
end
if hasGlance then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. GLANCE_ICON;
rightTooltipText = rightTooltipText .. GLANCE_ICON .. " " .. loc.REG_LIST_CHAR_TT_GLANCE;
end
if hasNewAbout then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. NEW_ABOUT_ICON;
rightTooltipText = rightTooltipText .. NEW_ABOUT_ICON .. " " .. loc.REG_LIST_CHAR_TT_NEW_ABOUT;
end
if profile.hasMatureContent then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. MATURE_CONTENT_ICON;
rightTooltipText = rightTooltipText .. MATURE_CONTENT_ICON .. " " .. loc.MATURE_FILTER_TOOLTIP_WARNING;
end
if rightTooltipText then
setTooltipForSameFrame(_G[line:GetName().."ClickRight"], "TOPLEFT", 0, 5, loc.REG_LIST_FLAGS, rightTooltipText);
else
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
_G[line:GetName().."Info2"]:SetText(flags);
local addon = Globals.addon_name;
if profile.msp then
addon = "Mary-Sue Protocol";
if firstLink and isUnitIDKnown(firstLink) then
local character = getUnitIDCharacter(firstLink);
addon = character.client or "Mary-Sue Protocol";
end
end
_G[line:GetName().."Addon"]:SetText(addon);
_G[line:GetName().."Select"]:SetChecked(selectedIDs[profileID]);
_G[line:GetName().."Select"]:Show();
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, leftTooltipTitle, leftTooltipText .. "\n\n" ..
Ellyb.Strings.clickInstruction(Ellyb.System.CLICKS.CLICK, loc.CM_OPEN) .. "\n" ..
Ellyb.Strings.clickInstruction(
Ellyb.System:FormatKeyboardShortcut(Ellyb.System.MODIFIERS.SHIFT, Ellyb.System.CLICKS.CLICK),
loc.CL_TOOLTIP
));
end
local function getCharacterLines()
local nameSearch = TRP3_RegisterListFilterCharactName:GetText():lower();
local guildSearch = TRP3_RegisterListFilterCharactGuild:GetText():lower();
local realmOnly = TRP3_RegisterListFilterCharactRealm:GetChecked();
local profileList = getProfileList();
local fullSize = tsize(profileList);
wipe(characterLines);
for profileID, profile in pairs(profileList) do
local nameIsConform, guildIsConform, realmIsConform = false, false, false;
-- Defines if at least one character is conform to the search criteria
for unitID, _ in pairs(profile.link or Globals.empty) do
local unitName, unitRealm = unitIDToInfo(unitID);
if safeMatch(unitName:lower(), nameSearch) then
nameIsConform = true;
end
if unitRealm == Globals.player_realm_id then
realmIsConform = true;
end
local character = getUnitIDCharacter(unitID);
if character.guild and safeMatch(character.guild:lower(), guildSearch) then
guildIsConform = true;
end
end
local completeName = getCompleteName(profile.characteristics or {}, "", true);
if not nameIsConform and safeMatch(completeName:lower(), nameSearch) then
nameIsConform = true;
end
nameIsConform = nameIsConform or nameSearch:len() == 0;
guildIsConform = guildIsConform or guildSearch:len() == 0;
realmIsConform = realmIsConform or not realmOnly;
if nameIsConform and guildIsConform and realmIsConform then
tinsert(characterLines, {profileID, completeName, getRelationText(profileID), profile.time});
end
end
table.sort(characterLines, getCurrentComparator());
local lineSize = #characterLines;
if lineSize == 0 then
if fullSize == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_CHAR_EMPTY);
else
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_CHAR_EMPTY2);
end
end
setupFieldSet(TRP3_RegisterListCharactFilter, loc.REG_LIST_CHAR_FILTER:format(lineSize, fullSize), 200);
local nameArrow, relationArrow, timeArrow = getComparatorArrows();
TRP3_RegisterListHeaderName:SetText(loc.REG_PLAYER .. nameArrow);
TRP3_RegisterListHeaderInfo:SetText(loc.REG_RELATION .. relationArrow);
TRP3_RegisterListHeaderTime:SetText(loc.REG_TIME .. timeArrow);
TRP3_RegisterListHeaderTimeTT:Enable();
TRP3_RegisterListHeaderInfoTT:Enable();
TRP3_RegisterListHeaderNameTT:Enable();
TRP3_RegisterListHeaderInfo2:SetText(loc.REG_LIST_FLAGS);
TRP3_RegisterListHeaderActions:Show();
return characterLines;
end
local MONTH_IN_SECONDS = 2592000;
local function onCharactersActionSelected(value, button)
-- PURGES
if value == "purge_time" then
local profiles = getProfileList();
local profilesToPurge = {};
for profileID, profile in pairs(profiles) do
if profile.time and time() - profile.time > MONTH_IN_SECONDS then
tinsert(profilesToPurge, profileID);
end
end
if #profilesToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_TIME_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_TIME_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
end
elseif value == "purge_unlinked" then
local profiles = getProfileList();
local profilesToPurge = {};
for profileID, profile in pairs(profiles) do
if not profile.link or tsize(profile.link) == 0 then
tinsert(profilesToPurge, profileID);
end
end
if #profilesToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_UNLINKED_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_UNLINKED_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
end
elseif value == "purge_ignore" then
local profilesToPurge, characterToPurge = TRP3_API.register.getIDsToPurge();
if #profilesToPurge + #characterToPurge == 0 then
showAlertPopup(loc.REG_LIST_ACTIONS_PURGE_IGNORE_C:format(loc.REG_LIST_ACTIONS_PURGE_EMPTY));
else
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_IGNORE_C:format(loc.REG_LIST_ACTIONS_PURGE_COUNT:format(#profilesToPurge + #characterToPurge)), function()
for _, profileID in pairs(profilesToPurge) do
deleteProfile(profileID, true);
end
for _, unitID in pairs(characterToPurge) do
deleteCharacter(unitID);
end
refreshList();
end);
end
elseif value == "purge_all" then
local list = getProfileList();
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_ALL_C:format(tsize(list)), function()
for profileID, _ in pairs(list) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
-- Mass actions
elseif value == "actions_delete" then
showConfirmPopup(loc.REG_LIST_ACTIONS_MASS_REMOVE_C:format(tsize(selectedIDs)), function()
for profileID, _ in pairs(selectedIDs) do
deleteProfile(profileID, true);
end
Events.fireEvent(Events.REGISTER_DATA_UPDATED);
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
refreshList();
end);
elseif value == "actions_ignore" then
local charactToIgnore = {};
for profileID, _ in pairs(selectedIDs) do
for unitID, _ in pairs(getProfile(profileID).link or Globals.empty) do
charactToIgnore[unitID] = true;
end
end
showTextInputPopup(loc.REG_LIST_ACTIONS_MASS_IGNORE_C:format(tsize(charactToIgnore)), function(text)
for unitID, _ in pairs(charactToIgnore) do
ignoreID(unitID, text);
end
refreshList();
end);
end
end
local function onCharactersActions(self)
local values = {};
tinsert(values, {loc.REG_LIST_ACTIONS_PURGE, {
{loc.REG_LIST_ACTIONS_PURGE_TIME, "purge_time"},
{loc.REG_LIST_ACTIONS_PURGE_UNLINKED, "purge_unlinked"},
{loc.REG_LIST_ACTIONS_PURGE_IGNORE, "purge_ignore"},
{loc.REG_LIST_ACTIONS_PURGE_ALL, "purge_all"},
}});
if tsize(selectedIDs) > 0 then
tinsert(values, {loc.REG_LIST_ACTIONS_MASS:format(tsize(selectedIDs)), {
{loc.REG_LIST_ACTIONS_MASS_REMOVE, "actions_delete"},
{loc.REG_LIST_ACTIONS_MASS_IGNORE, "actions_ignore"},
}});
end
displayDropDown(self, values, onCharactersActionSelected, 0, true);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : COMPANIONS
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local companionIDToInfo, getAssociationsForProfile = TRP3_API.utils.str.companionIDToInfo, TRP3_API.companions.register.getAssociationsForProfile;
local getCompanionProfiles, deleteCompanionProfile = TRP3_API.companions.register.getProfiles, TRP3_API.companions.register.deleteProfile;
local companionLines = {};
local function decorateCompanionLine(line, index)
local profileID = companionLines[index][1];
local profile = getCompanionProfiles()[profileID];
line.id = profileID;
local hasGlance = profile.PE and checkGlanceActivation(profile.PE);
local hasNewAbout = profile.data and profile.data.read == false;
local name = UNKNOWN;
if profile.data and profile.data.NA then
name = profile.data.NA;
end
_G[line:GetName().."Name"]:SetText(name);
local tooltip, secondLine = name, "";
if profile.data and profile.data.IC then
tooltip = Utils.str.icon(profile.data.IC, ICON_SIZE) .. " " .. name;
end
local links, masters = {}, {};
local fulllinks = getAssociationsForProfile(profileID);
for _, companionFullID in pairs(fulllinks) do
local ownerID, companionID = companionIDToInfo(companionFullID);
links[companionID] = 1;
masters[ownerID] = 1;
end
local companionList = "";
for companionID, _ in pairs(links) do
companionList = companionList .. "- |cff00ff00" .. getCompanionNameFromSpellID(companionID) .. "|r\n";
end
local masterList, firstMaster = "", "";
for ownerID, _ in pairs(masters) do
masterList = masterList .. "- |cff00ff00" .. ownerID .. "|r\n";
if firstMaster == "" then
firstMaster = ownerID;
end
end
if isUnitIDKnown(firstMaster) and TRP3_API.register.profileExists(firstMaster) then
firstMaster = getCompleteName(getUnitIDProfile(firstMaster).characteristics or {}, "", true);
end
_G[line:GetName().."Addon"]:SetText(firstMaster);
secondLine = loc.REG_LIST_PETS_TOOLTIP .. ":\n" .. companionList .. "\n" .. loc.REG_LIST_PETS_TOOLTIP2 .. ":\n" .. masterList;
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, tooltip, secondLine .. "\n\n" ..
Ellyb.Strings.clickInstruction(Ellyb.System.CLICKS.CLICK, loc.CM_OPEN) .. "\n" ..
Ellyb.Strings.clickInstruction(
Ellyb.System:FormatKeyboardShortcut(Ellyb.System.MODIFIERS.SHIFT, Ellyb.System.CLICKS.CLICK),
loc.CL_TOOLTIP
));
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
-- Third column : flags
local rightTooltipTitle, rightTooltipText, flags;
if hasGlance then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. GLANCE_ICON;
rightTooltipText = rightTooltipText .. GLANCE_ICON .. " " .. loc.REG_LIST_CHAR_TT_GLANCE;
end
if hasNewAbout then
if not rightTooltipText then rightTooltipText = "" else rightTooltipText = rightTooltipText .. "\n" end
if not flags then flags = "" else flags = flags .. " " end
flags = flags .. NEW_ABOUT_ICON;
rightTooltipText = rightTooltipText .. NEW_ABOUT_ICON .. " " .. loc.REG_LIST_CHAR_TT_NEW_ABOUT;
end
if rightTooltipText then
setTooltipForSameFrame(_G[line:GetName().."ClickRight"], "TOPLEFT", 0, 5, loc.REG_LIST_FLAGS, rightTooltipText);
else
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
_G[line:GetName().."Info2"]:SetText(flags);
_G[line:GetName().."Select"]:SetChecked(selectedIDs[profileID]);
_G[line:GetName().."Select"]:Show();
_G[line:GetName().."Info"]:SetText("");
_G[line:GetName().."Time"]:SetText("");
end
local function getCompanionLines()
local nameSearch = TRP3_RegisterListPetFilterName:GetText():lower();
local typeSearch = TRP3_RegisterListPetFilterType:GetText():lower();
local masterSearch = TRP3_RegisterListPetFilterMaster:GetText():lower();
local profiles = getCompanionProfiles();
local fullSize = tsize(profiles);
wipe(companionLines);
for profileID, profile in pairs(profiles) do
local nameIsConform, typeIsConform, masterIsConform = false, false, false;
-- Run this test only if there are criterias
if typeSearch:len() > 0 or masterSearch:len() > 0 then
for companionFullID, _ in pairs(profile.links) do
local masterID, companionID = companionIDToInfo(companionFullID);
if safeMatch(companionID:lower(), typeSearch) then
typeIsConform = true;
end
if safeMatch(masterID:lower(), masterSearch) then
masterIsConform = true;
end
end
end
local companionName = UNKNOWN;
if profile.data and profile.data.NA then
companionName = profile.data.NA;
end
if nameSearch:len() ~= 0 and profile.data and profile.data.NA and safeMatch(profile.data.NA:lower(), nameSearch) then
nameIsConform = true;
end
nameIsConform = nameIsConform or nameSearch:len() == 0;
typeIsConform = typeIsConform or typeSearch:len() == 0;
masterIsConform = masterIsConform or masterSearch:len() == 0;
if nameIsConform and typeIsConform and masterIsConform then
tinsert(companionLines, {profileID, companionName, companionName, companionName});
end
end
table.sort(companionLines, getCurrentComparator());
local lineSize = #companionLines;
if lineSize == 0 then
if fullSize == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_PETS_EMPTY);
else
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_PETS_EMPTY2);
end
end
setupFieldSet(TRP3_RegisterListPetFilter, loc.REG_LIST_PETS_FILTER:format(lineSize, fullSize), 200);
local nameArrow, relationArrow, timeArrow = getComparatorArrows();
TRP3_RegisterListHeaderName:SetText(loc.REG_COMPANION .. nameArrow);
TRP3_RegisterListHeaderInfo:SetText("");
TRP3_RegisterListHeaderTime:SetText("");
TRP3_RegisterListHeaderTimeTT:Disable();
TRP3_RegisterListHeaderInfoTT:Disable();
TRP3_RegisterListHeaderNameTT:Enable();
TRP3_RegisterListHeaderInfo2:SetText(loc.REG_LIST_FLAGS);
TRP3_RegisterListHeaderActions:Show();
return companionLines;
end
local DO_NOT_FIRE_EVENTS = true;
local function onCompanionActionSelected(value, button)
if value == "purge_all" then
local list = getCompanionProfiles();
showConfirmPopup(loc.REG_LIST_ACTIONS_PURGE_ALL_COMP_C:format(tsize(list)), function()
for profileID, _ in pairs(list) do
-- We delete the companion profile without fire events to prevent UI freeze
deleteCompanionProfile(profileID, DO_NOT_FIRE_EVENTS);
end
-- We then fire the event once every profile we needed to delete has been deleted
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
elseif value == "actions_delete" then
showConfirmPopup(loc.REG_LIST_ACTIONS_MASS_REMOVE_C:format(tsize(selectedIDs)), function()
for profileID, _ in pairs(selectedIDs) do
-- We delete the companion profile without fire events to prevent UI freeze
deleteCompanionProfile(profileID, DO_NOT_FIRE_EVENTS);
end
-- We then fire the event once every profile we needed to delete has been deleted
Events.fireEvent(Events.REGISTER_PROFILE_DELETED);
end);
end
end
local function onPetsActions(self)
local values = {};
tinsert(values, {loc.REG_LIST_ACTIONS_PURGE, {
{loc.REG_LIST_ACTIONS_PURGE_ALL, "purge_all"},
}});
if tsize(selectedIDs) > 0 then
tinsert(values, {loc.REG_LIST_ACTIONS_MASS:format(tsize(selectedIDs)), {
{loc.REG_LIST_ACTIONS_MASS_REMOVE, "actions_delete"},
}});
end
displayDropDown(self, values, onCompanionActionSelected, 0, true);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : IGNORED
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local function decorateIgnoredLine(line, unitID)
line.id = unitID;
_G[line:GetName().."Name"]:SetText(unitID);
_G[line:GetName().."Info"]:SetText("");
_G[line:GetName().."Time"]:SetText("");
_G[line:GetName().."Info2"]:SetText("");
_G[line:GetName().."Addon"]:SetText("");
_G[line:GetName().."Select"]:Hide();
setTooltipForSameFrame(_G[line:GetName().."Click"], "TOPLEFT", 0, 5, unitID, loc.REG_LIST_IGNORE_TT:format(getIgnoredList()[unitID]));
setTooltipForSameFrame(_G[line:GetName().."ClickMiddle"]);
setTooltipForSameFrame(_G[line:GetName().."ClickRight"]);
end
local function getIgnoredLines()
if tsize(getIgnoredList()) == 0 then
TRP3_RegisterListEmpty:SetText(loc.REG_LIST_IGNORE_EMPTY);
end
TRP3_RegisterListHeaderName:SetText(loc.REG_PLAYER);
TRP3_RegisterListHeaderInfo:SetText("");
TRP3_RegisterListHeaderTime:SetText("");
TRP3_RegisterListHeaderTimeTT:Disable();
TRP3_RegisterListHeaderInfoTT:Disable();
TRP3_RegisterListHeaderNameTT:Disable();
TRP3_RegisterListHeaderInfo2:SetText("");
return getIgnoredList();
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- UI : LIST
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function refreshList()
local lines;
TRP3_RegisterListEmpty:Hide();
TRP3_RegisterListHeaderActions:Hide();
if currentMode == MODE_CHARACTER then
lines = getCharacterLines();
TRP3_RegisterList.decorate = decorateCharacterLine;
elseif currentMode == MODE_PETS then
lines = getCompanionLines();
TRP3_RegisterList.decorate = decorateCompanionLine;
elseif currentMode == MODE_IGNORE then
lines = getIgnoredLines();
TRP3_RegisterList.decorate = decorateIgnoredLine;
end
if tsize(lines) == 0 then
TRP3_RegisterListEmpty:Show();
end
initList(TRP3_RegisterList, lines, TRP3_RegisterListSlider);
end
local function onLineClicked(self, button)
if currentMode == MODE_CHARACTER then
assert(self:GetParent().id, "No profileID on line.");
if IsShiftKeyDown() then
TRP3_API.RegisterPlayerChatLinksModule:InsertLink(self:GetParent().id);
else
openPage(self:GetParent().id);
end
elseif currentMode == MODE_PETS then
assert(self:GetParent().id, "No profileID on line.");
if IsShiftKeyDown() then
TRP3_API.ChatLinks:OpenMakeImportablePrompt(loc.CL_COMPANION_PROFILE, function(canBeImported)
TRP3_API.RegisterCompanionChatLinksModule:InsertLink(self:GetParent().id, canBeImported);
end);
else
openCompanionPage(self:GetParent().id);
end
elseif currentMode == MODE_IGNORE then
assert(self:GetParent().id, "No unitID on line.");
unignoreID(self:GetParent().id);
refreshList();
end
end
local function onLineSelected(self, button)
assert(self:GetParent().id, "No id on line.");
selectedIDs[self:GetParent().id] = self:GetChecked();
end
local function changeMode(tabWidget, value)
currentMode = value;
wipe(selectedIDs);
TRP3_RegisterListCharactFilter:Hide();
TRP3_RegisterListPetFilter:Hide();
TRP3_RegisterListHeaderAddon:SetText("");
if currentMode == MODE_CHARACTER then
TRP3_RegisterListCharactFilter:Show();
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_ADDON);
elseif currentMode == MODE_PETS then
TRP3_RegisterListPetFilter:Show();
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_PET_MASTER);
end
refreshList();
Events.fireEvent(Events.NAVIGATION_TUTORIAL_REFRESH, REGISTER_LIST_PAGEID);
end
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-- Init
--*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
local tabGroup;
local function createTabBar()
local frame = CreateFrame("Frame", "TRP3_RegisterMainTabBar", TRP3_RegisterList);
frame:SetSize(400, 30);
frame:SetPoint("TOPLEFT", 17, 0);
frame:SetFrameLevel(1);
tabGroup = TRP3_API.ui.frame.createTabPanel(frame,
{
{loc.REG_LIST_CHAR_TITLE, 1, 150},
{loc.REG_LIST_PETS_TITLE, 2, 150},
{loc.REG_LIST_IGNORE_TITLE, 3, 150},
},
changeMode
);
tabGroup:SelectTab(1);
end
local TUTORIAL_CHARACTER;
local function createTutorialStructure()
TUTORIAL_CHARACTER = {
{
box = {
x = 20, y = -45, anchor = "TOPLEFT", width = 28, height = 340
},
button = {
x = 0, y = 0, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_ACTIONS,
arrow = "LEFT"
}
},
{
box = {
x = 50, y = -45, anchor = "TOPLEFT", width = 470, height = 340
},
button = {
x = 0, y = 0, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_LIST,
textWidth = 400,
arrow = "DOWN"
}
},
{
box = {
x = 20, y = -387, anchor = "TOPLEFT", width = 500, height = 60
},
button = {
x = 0, y = 10, anchor = "CENTER",
text = loc.REG_LIST_CHAR_TUTO_FILTER,
textWidth = 400,
arrow = "UP"
}
}
}
end
local function tutorialProvider()
if currentMode == MODE_CHARACTER then
return TUTORIAL_CHARACTER;
end
end
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOAD, function()
createTutorialStructure();
-- To try, but I'm afraid for performances ...
Events.listenToEvent(Events.REGISTER_DATA_UPDATED, function(unitID, profileID, dataType)
if getCurrentPageID() == REGISTER_LIST_PAGEID and unitID ~= Globals.player_id and (not dataType or dataType == "characteristics") then
refreshList();
end
end);
Events.listenToEvent(Events.REGISTER_PROFILE_DELETED, function(profileID)
if profileID then
selectedIDs[profileID] = nil;
if isMenuRegistered(currentlyOpenedProfilePrefix .. profileID) then
unregisterMenu(currentlyOpenedProfilePrefix .. profileID);
end
end
if getCurrentPageID() == REGISTER_LIST_PAGEID then
refreshList();
end
end);
registerMenu({
id = REGISTER_PAGE,
closeable = true,
text = loc.REG_REGISTER,
onSelected = function() setPage(REGISTER_LIST_PAGEID); end,
});
registerPage({
id = REGISTER_LIST_PAGEID,
templateName = "TRP3_RegisterList",
frameName = "TRP3_RegisterList",
frame = TRP3_RegisterList,
onPagePostShow = function() tabGroup:SelectTab(1); end,
tutorialProvider = tutorialProvider,
});
TRP3_RegisterListSlider:SetValue(0);
handleMouseWheel(TRP3_RegisterListContainer, TRP3_RegisterListSlider);
local widgetTab = {};
for i=1,14 do
local widget = _G["TRP3_RegisterListLine"..i];
local widgetClick = _G["TRP3_RegisterListLine"..i.."Click"];
local widgetSelect = _G["TRP3_RegisterListLine"..i.."Select"];
widgetSelect:SetScript("OnClick", onLineSelected);
widgetClick:SetScript("OnClick", onLineClicked);
widgetClick:SetHighlightTexture("Interface\\FriendsFrame\\UI-FriendsFrame-HighlightBar-Blue");
widgetClick:SetAlpha(0.75);
table.insert(widgetTab, widget);
end
TRP3_RegisterList.widgetTab = widgetTab;
TRP3_RegisterListFilterCharactName:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListFilterCharactGuild:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListFilterCharactRealm:SetScript("OnClick", refreshList);
TRP3_RegisterListCharactFilterButton:SetScript("OnClick", function(self, button)
if button == "RightButton" then
TRP3_RegisterListFilterCharactName:SetText("");
TRP3_RegisterListFilterCharactGuild:SetText("");
TRP3_RegisterListFilterCharactRealm:SetChecked(true);
end
refreshList();
end)
setTooltipForSameFrame(TRP3_RegisterListCharactFilterButton, "LEFT", 0, 5, loc.REG_LIST_FILTERS, loc.REG_LIST_FILTERS_TT);
TRP3_RegisterListFilterCharactNameText:SetText(loc.REG_LIST_NAME);
TRP3_RegisterListFilterCharactGuildText:SetText(loc.REG_LIST_GUILD);
TRP3_RegisterListFilterCharactRealmText:SetText(loc.REG_LIST_REALMONLY);
TRP3_RegisterListHeaderAddon:SetText(loc.REG_LIST_ADDON);
TRP3_API.ui.frame.setupEditBoxesNavigation({TRP3_RegisterListFilterCharactName, TRP3_RegisterListFilterCharactGuild});
TRP3_RegisterListPetFilterName:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterType:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterMaster:SetScript("OnEnterPressed", refreshList);
TRP3_RegisterListPetFilterButton:SetScript("OnClick", function(self, button)
if button == "RightButton" then
TRP3_RegisterListPetFilterName:SetText("");
TRP3_RegisterListPetFilterType:SetText("");
TRP3_RegisterListPetFilterMaster:SetText("");
end
refreshList();
end)
setTooltipForSameFrame(TRP3_RegisterListPetFilterButton, "LEFT", 0, 5, loc.REG_LIST_FILTERS, loc.REG_LIST_FILTERS_TT);
TRP3_RegisterListPetFilterNameText:SetText(loc.REG_LIST_PET_NAME);
TRP3_RegisterListPetFilterTypeText:SetText(loc.REG_LIST_PET_TYPE);
TRP3_RegisterListPetFilterMasterText:SetText(loc.REG_LIST_PET_MASTER);
TRP3_API.ui.frame.setupEditBoxesNavigation({TRP3_RegisterListPetFilterName, TRP3_RegisterListPetFilterType, TRP3_RegisterListPetFilterMaster});
TRP3_RegisterListHeaderNameTT:SetScript("OnClick", switchNameSorting);
TRP3_RegisterListHeaderInfoTT:SetScript("OnClick", switchInfoSorting);
TRP3_RegisterListHeaderTimeTT:SetScript("OnClick", switchTimeSorting);
setTooltipForSameFrame(TRP3_RegisterListHeaderActions, "TOP", 0, 0, loc.CM_ACTIONS);
TRP3_RegisterListHeaderActions:SetScript("OnClick", function(self)
if currentMode == MODE_CHARACTER then
onCharactersActions(self);
elseif currentMode == MODE_PETS then
onPetsActions(self);
end
end);
createTabBar();
-- Resizing
TRP3_API.events.listenToEvent(TRP3_API.events.NAVIGATION_RESIZED, function(containerwidth, containerHeight)
for _, line in pairs(widgetTab) do
line:SetHeight((containerHeight - 120) * 0.065);
if containerwidth < 690 then
_G[line:GetName() .. "Time"]:SetWidth(2);
else
_G[line:GetName() .. "Time"]:SetWidth(160);
end
if containerwidth < 850 then
_G[line:GetName() .. "Addon"]:SetWidth(2);
else
_G[line:GetName() .. "Addon"]:SetWidth(160);
end
end
if containerwidth < 690 then
TRP3_RegisterListHeaderTime:SetWidth(2);
else
TRP3_RegisterListHeaderTime:SetWidth(160);
end
if containerwidth < 850 then
TRP3_RegisterListHeaderAddon:SetWidth(2);
else
TRP3_RegisterListHeaderAddon:SetWidth(160);
end
end);
end);
TRP3_API.events.listenToEvent(TRP3_API.events.WORKFLOW_ON_LOADED, function()
if TRP3_API.target then
TRP3_API.target.registerButton({
id = "aa_player_a_page",
configText = loc.TF_OPEN_CHARACTER,
onlyForType = TRP3_API.ui.misc.TYPE_CHARACTER,
condition = function(targetType, unitID)
return unitID == Globals.player_id or (isUnitIDKnown(unitID) and hasProfile(unitID));
end,
onClick = function(unitID)
openMainFrame();
openPageByUnitID(unitID);
end,
adapter = function(buttonStructure, unitID, currentTargetType)
buttonStructure.tooltip = loc.REG_PLAYER;
buttonStructure.tooltipSub = "|cffffff00" .. loc.CM_CLICK .. ": |r" .. loc.TF_OPEN_CHARACTER;
buttonStructure.alert = nil;
if unitID ~= Globals.player_id and hasProfile(unitID) then
local profile = getUnitIDProfile(unitID);
if profile.about and not profile.about.read then
buttonStructure.tooltipSub = "|cff00ff00" .. loc.REG_TT_NOTIF .. "\n" .. buttonStructure.tooltipSub;
buttonStructure.alert = true;
end
end
end,
alertIcon = "Interface\\GossipFrame\\AvailableQuestIcon",
icon = "inv_inscription_scroll"
});
end
end); |
local PANEL = {}
AccessorFunc( PANEL, "m_Color", "Color" )
AccessorFunc( PANEL, "m_BorderColor", "BorderColor" )
AccessorFunc( PANEL, "m_Type", "Type" )
local RenderTypes = {}
function RenderTypes.Rect( pnl )
surface.SetDrawColor( pnl:GetColor() )
surface.DrawRect( 0, 0, pnl:GetSize() )
end
function PANEL:Init()
self:SetColor( Color( 255, 255, 255, 255 ) )
self:SetMouseInputEnabled( false )
self:SetKeyboardInputEnabled( false )
end
function PANEL:Paint()
RenderTypes[ self.m_Type ]( self )
end
derma.DefineControl( "DShape", "A shape", PANEL, "DPanel" )
-- Convenience function
function VGUIRect( x, y, w, h )
local shape = vgui.Create( "DShape" )
shape:SetType( "Rect" )
shape:SetPos( x, y )
shape:SetSize( w, h )
return shape
end
|
require "config"
require "tools"
local math = require "math"
local local_run_test = lunit and function() end or run_test
local lunit = require "lunit"
local skip = assert(lunit.skip)
local TEST_CASE = assert(lunit.TEST_CASE)
local function SKIP(msg) return function() lunit.skip(msg) end end
local arg = {...}
local _ENV = TEST_CASE 'Statement bind'
if not TEST_PROC_CREATE then test = SKIP(DBMS .. " does not support SP with resultset")
else
local function assert_opt_string(v, ...)
if v == nil then return v, ... end
return assert_string(v, ...)
end
local env, cnn, stmt
function teardown()
if cnn and cnn:connected() then drop_proc(cnn) end
if stmt then stmt:destroy() end
if cnn then cnn:destroy() end
if env then env:destroy() end
cnn = nil
env = nil
end
function setup()
env, cnn = do_connect()
assert_not_nil(env, cnn)
end
local x = function(b)
return(string.gsub(b, "([a-fA-F0-9][a-fA-F0-9])", function(v)
return string.char( tonumber(v, 16) )
end))
end
local X = function(b)
return(string.gsub(b, ".", function(v)
return string.format("%.2X", string.byte(v))
end))
end
local inIntVal = -0x7FFFFFFF
local inUIntVal = 0xFFFFFFFF
local inDoubleVal = 1234.235664879123456
local inStringVal = "Hello world"
local inBinaryVal = "\000\001\002\003"
local inDateVal = "2011-01-01"
local inNullVal = odbc.NULL
local inDefaultVal = 1234
local inBoolVal = true
local inGuidVal = 'B1BB49A2-B401-4413-BEBB-7ACD10399875'
local inBigIntVal = -0x7FFFFFFFFFFFFFFF
if not GUID_USE_DASH then
inGuidVal = string.gsub(inGuidVal, '%-', '')
end
local function get_int()
return inIntVal;
end
local function get_uint()
return inUIntVal
end
local function get_double()
return inDoubleVal
end
local function get_date()
return inDateVal
end
local function get_bool()
return inBoolVal
end
local function create_get_bin_by(str,n)
local pos = 1
return function()
local data = str:sub(pos,pos+n-1)
pos = pos + n
return data
end
end
local function get_uuid()
return inGuidVal
end
local function get_bigint()
return inBigIntVal;
end
local function EXEC_AND_ASSERT(qrySQL)
if qrySQL then assert_equal(stmt, stmt:execute(qrySQL))
else assert_equal(stmt, stmt:execute()) end
assert_equal(1, stmt:rowcount())
local outIntVal, outUIntVal, outDoubleVal, outStringVal,
outBinaryVal, outDateVal, outNullVal,outBoolVal,outGuidVal,
outBigIntVal, outDefaultVal = stmt:fetch()
if not PROC_SUPPORT_DEFAULT then
outDefaultVal = "----"
end
if not HAS_GUID_TYPE then
outGuidVal, outBigIntVal = nil, outGuidVal
end
local test_bin_val = inBinaryVal
if DBMS == 'MySQL' then
test_bin_val = inBinaryVal .. ('\0'):rep(#outBinaryVal - #inBinaryVal)
end
stmt:close()
-- print()
-- print('IntVal =', outIntVal )
-- print('UIntVal =', outUIntVal )
-- print('DoubleVal =', outDoubleVal )
-- print('StringVal =', outStringVal )
-- print('BinaryVal =', outBinaryVal )
-- print('DateVal =', outDateVal )
-- print('NullVal =', outNullVal )
-- print('DefaultVal =', outDefaultVal )
-- print('BoolVal =', outBoolVal )
-- print('GuidVal =', outGuidVal )
-- print('BigIntVal =', outBigIntVal )
-- print"================================="
assert_equal(inIntVal , outIntVal )
assert_equal(inUIntVal , outUIntVal )
assert_equal(inDoubleVal , outDoubleVal )
assert_equal(inStringVal , outStringVal )
assert_equal(test_bin_val, outBinaryVal )
assert_equal(inDateVal , outDateVal )
assert_equal(inNullVal , outNullVal )
assert_equal(BIT_LUA_TRUE, outBoolVal )
if HAS_GUID_TYPE then
assert_equal(inGuidVal , outGuidVal )
end
assert_equal(inBigIntVal , outBigIntVal )
if PROC_SUPPORT_DEFAULT then
assert_equal(inDefaultVal, outDefaultVal )
end
end
local function VEXEC_AND_ASSERT(qrySQL)
if qrySQL then assert_equal(stmt, stmt:execute(qrySQL))
else assert_equal(stmt, stmt:execute()) end
local i = 1
local outIntVal = assert( odbc.slong() :bind_col(stmt, i ) ) i = i + 1
local outUIntVal = assert( odbc.ulong() :bind_col(stmt, i ) ) i = i + 1
local outDoubleVal = assert( odbc.double() :bind_col(stmt, i ) ) i = i + 1
local outStringVal = assert( odbc.char(#inStringVal) :bind_col(stmt, i ) ) i = i + 1
local outBinaryVal = assert( odbc.binary(#inBinaryVal) :bind_col(stmt, i ) ) i = i + 1
local outDateVal = assert( odbc.date() :bind_col(stmt, i ) ) i = i + 1
local outNullVal = assert( odbc.utinyint() :bind_col(stmt, i ) ) i = i + 1
local outBoolVal = assert( odbc.bit() :bind_col(stmt, i ) ) i = i + 1
local outGuidVal if HAS_GUID_TYPE then
if DBMS == 'PgSQL' then
outGuidVal = assert( odbc. char(#inGuidVal) :bind_col(stmt, i ) ) i = i + 1
else
outGuidVal = assert( odbc.binary(#inGuidVal) :bind_col(stmt, i ) ) i = i + 1
end
end
local outBigIntVal = assert( odbc.sbigint() :bind_col(stmt, i ) ) i = i + 1
local outDefaultVal if PROC_SUPPORT_DEFAULT then
outDefaultVal = assert( odbc.ulong() :bind_col(stmt, i ) ) i = i + 1
end
assert_true(stmt:vfetch())
stmt:close()
-- print()
-- print('IntVal =', outIntVal :get())
-- print('UIntVal =', outUIntVal :get())
-- print('DoubleVal =', outDoubleVal :get())
-- print('StringVal =', outStringVal :get())
-- print('BinaryVal =', outBinaryVal :get())
-- print('DateVal =', outDateVal :get())
-- print('NullVal =', outNullVal :get())
-- print('DefaultVal =', outDefaultVal :get())
-- print('BoolVal =', outBoolVal :get())
-- print('GuidVal =', outGuidVal :get())
-- print"================================="
assert_equal(inIntVal , outIntVal :get())
assert_equal(inUIntVal , outUIntVal :get())
assert_equal(inDoubleVal , outDoubleVal :get())
assert_equal(inStringVal , outStringVal :get())
assert_equal(inBinaryVal , outBinaryVal :get())
assert_equal(inDateVal , outDateVal :get())
assert_equal(inNullVal , outNullVal :get())
assert_equal(inBoolVal , outBoolVal :get())
if HAS_GUID_TYPE then
if DBMS == 'PgSQL' then
assert_equal(inGuidVal, outGuidVal :get())
else
assert_equal(x(inGuidVal), outGuidVal :get())
end
end
assert_equal(inBigIntVal , outBigIntVal :get())
if PROC_SUPPORT_DEFAULT then
assert_equal(inDefaultVal, outDefaultVal :get())
end
end
local function BIND(stmt)
local i = 1
assert_true(stmt:bindnum (i,inIntVal )) i = i + 1
assert_true(stmt:bindnum (i,inUIntVal )) i = i + 1
assert_true(stmt:bindnum (i,inDoubleVal )) i = i + 1
assert_true(stmt:bindstr (i,inStringVal )) i = i + 1
assert_true(stmt:bindbin (i,inBinaryVal )) i = i + 1
assert_true(stmt:bindstr (i,inDateVal )) i = i + 1
assert_true(stmt:bindnull (i )) i = i + 1
assert_true(stmt:bindbool (i,inBoolVal )) i = i + 1
if HAS_GUID_TYPE then
assert_true(stmt:bindstr (i,inGuidVal )) i = i + 1
end
assert_true(stmt:bindnum (i,inBigIntVal )) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_true(stmt:binddefault(i )) i = i + 1
end
end
local function BIND_CB(stmt)
local i = 1
assert_true(stmt:bindnum (i, get_int )) i = i + 1
assert_true(stmt:bindnum (i, get_uint )) i = i + 1
assert_true(stmt:bindnum (i, get_double )) i = i + 1
assert_true(stmt:bindstr (i, create_get_bin_by(inStringVal,10))) i = i + 1
assert_true(stmt:bindbin (i, create_get_bin_by(inBinaryVal,10))) i = i + 1
assert_true(stmt:bindstr (i, get_date, #inDateVal )) i = i + 1
assert_true(stmt:bindnull (i )) i = i + 1
assert_true(stmt:bindbool (i, get_bool )) i = i + 1
if HAS_GUID_TYPE then
assert_true(stmt:bindstr (i, get_uuid ,#inGuidVal)) i = i + 1
end
-- Use `bindint` instead of `bindnum` because there no way to detect value type
-- before execute so with callback we have to point value type explicity
assert_true(stmt:bindint (i, get_bigint )) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_true(stmt:binddefault(i )) i = i + 1
end
end
function test_1()
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
assert_false(stmt:prepared())
assert_nil(stmt:colnames())
assert_nil(stmt:coltypes())
assert_equal(-1, stmt:parcount())
BIND(stmt)
assert_equal(-1, stmt:parcount())
EXEC_AND_ASSERT(TEST_PROC_CALL)
end
function test_2()
if DBMS == 'MySQL' then return skip'MySQL does not supported' end
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
assert_true(stmt:prepare(TEST_PROC_CALL))
assert_true(stmt:prepared())
local col = assert_table(stmt:colnames())
local typ = assert_table(stmt:coltypes())
local par_count = 11
if not HAS_GUID_TYPE then par_count = par_count - 1 end
if not PROC_SUPPORT_DEFAULT then par_count = par_count - 1 end
local real_pars = assert_number(stmt:parcount())
if real_pars ~= -1 then
assert_equal(par_count, real_pars)
end
BIND(stmt)
EXEC_AND_ASSERT()
assert_equal(col, stmt:colnames())
assert_equal(typ, stmt:coltypes())
assert_true(stmt:reset())
assert_false(stmt:prepared())
assert_nil(stmt:colnames())
assert_nil(stmt:coltypes())
assert_equal(-1, stmt:parcount())
assert_true(stmt:destroy())
end
function test_3()
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
BIND_CB(stmt)
EXEC_AND_ASSERT(TEST_PROC_CALL)
assert_true(stmt:destroy())
end
function test_4()
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
assert_true(stmt:prepare(TEST_PROC_CALL))
BIND_CB(stmt)
EXEC_AND_ASSERT()
assert_true(stmt:destroy())
end
function test_coltypes()
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
assert_true(stmt:prepare(TEST_PROC_CALL))
local types = stmt:coltypes()
local int_name = math.type and 'integer' or 'number'
local i = 1
assert_equal(int_name, types[i]) i = i + 1
assert_equal(int_name, types[i]) i = i + 1
assert_equal('number', types[i]) i = i + 1
assert_equal('string', types[i]) i = i + 1
assert_equal('binary', types[i]) i = i + 1
assert_equal('string', types[i]) i = i + 1
assert_equal(int_name, types[i]) i = i + 1
assert_equal(BIT_LUA_TYPE, types[i]) i = i + 1
if HAS_GUID_TYPE then
assert_equal('string', types[i]) i = i + 1
end
assert_equal(int_name, types[i]) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_equal(int_name, types[i]) i = i + 1
end
assert_true(stmt:destroy())
end
function test_colnames()
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
assert_true(stmt:prepare(TEST_PROC_CALL))
local names = stmt:colnames()
local i = 1
assert_string(names[i]); assert_equal('inintval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('inuintval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('indoubleval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('instringval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('inbinaryval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('indateval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('innullval', string.lower(names[i])) i = i + 1
assert_string(names[i]); assert_equal('inbitval', string.lower(names[i])) i = i + 1
if HAS_GUID_TYPE then
assert_string(names[i]); assert_equal('inguidval', string.lower(names[i])) i = i + 1
end
assert_string(names[i]); assert_equal('inbigint', string.lower(names[i])) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_string(names[i]); assert_equal('indefaultval', string.lower(names[i])) i = i + 1
end
assert_true(stmt:destroy())
end
function test_bind_value()
local vIntVal = odbc.slong(inIntVal)
local vUIntVal = odbc.ulong(inUIntVal)
local vDoubleVal = odbc.double(inDoubleVal)
local vStringVal = odbc.char(inStringVal)
local vBinaryVal = odbc.binary(inBinaryVal)
local vDateVal = odbc.char(inDateVal) -- sybase has error. for date : Cannot convert SQLDATETIME to a date
local vNullVal = odbc.utinyint()
local vDefaultVal = odbc.ulong(inDefaultVal)
local vBoolVal = odbc.bit(inBoolVal)
local vGuidVal = odbc.binary(x(inGuidVal))
local vBigIntVal = odbc.sbigint(inBigIntVal)
if DBMS == 'PgSQL' then
vGuidVal = odbc.char(inGuidVal)
end
assert_boolean(proc_exists(cnn))
assert(ensure_proc(cnn))
assert_true(proc_exists(cnn))
stmt = cnn:statement()
local i = 1
assert_equal(vIntVal , vIntVal :bind_param(stmt, i )) i = i + 1
assert_equal(vUIntVal , vUIntVal :bind_param(stmt, i )) i = i + 1
assert_equal(vDoubleVal , vDoubleVal :bind_param(stmt, i )) i = i + 1
assert_equal(vStringVal , vStringVal :bind_param(stmt, i )) i = i + 1
assert_equal(vBinaryVal , vBinaryVal :bind_param(stmt, i )) i = i + 1
assert_equal(vDateVal , vDateVal :bind_param(stmt, i, odbc.PARAM_INPUT, odbc.DATE)) i = i + 1
assert_equal(vNullVal , vNullVal :bind_param(stmt, i )) i = i + 1
assert_equal(vBoolVal , vBoolVal :bind_param(stmt, i )) i = i + 1
if HAS_GUID_TYPE then
assert_equal(vGuidVal , vGuidVal :bind_param(stmt, i )) i = i + 1
end
assert_equal(vBigIntVal , vBigIntVal :bind_param(stmt, i )) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_equal(vDefaultVal,vDefaultVal :bind_param(stmt, i )) i = i + 1
end
EXEC_AND_ASSERT(TEST_PROC_CALL)
VEXEC_AND_ASSERT(TEST_PROC_CALL)
stmt:prepare(TEST_PROC_CALL)
local i = 1
assert_equal(vIntVal , vIntVal :bind_param(stmt, i )) i = i + 1
assert_equal(vUIntVal , vUIntVal :bind_param(stmt, i )) i = i + 1
assert_equal(vDoubleVal , vDoubleVal :bind_param(stmt, i )) i = i + 1
assert_equal(vStringVal , vStringVal :bind_param(stmt, i )) i = i + 1
assert_equal(vBinaryVal , vBinaryVal :bind_param(stmt, i )) i = i + 1
assert_equal(vDateVal , vDateVal :bind_param(stmt, i, odbc.PARAM_INPUT, odbc.DATE)) i = i + 1
assert_equal(vNullVal , vNullVal :bind_param(stmt, i )) i = i + 1
assert_equal(vBoolVal , vBoolVal :bind_param(stmt, i )) i = i + 1
if HAS_GUID_TYPE then
assert_equal(vGuidVal , vGuidVal :bind_param(stmt, i )) i = i + 1
end
assert_equal(vBigIntVal , vBigIntVal :bind_param(stmt, i )) i = i + 1
if PROC_SUPPORT_DEFAULT then
assert_equal(vDefaultVal,vDefaultVal :bind_param(stmt, i )) i = i + 1
end
EXEC_AND_ASSERT()
VEXEC_AND_ASSERT()
assert_true(stmt:destroy())
end
end
local_run_test(arg) |
local rt_dap = require("rust-tools.dap")
local config = require("rust-tools.config")
local utils = require("rust-tools.utils.utils")
local M = {}
local function get_params()
return {
textDocument = vim.lsp.util.make_text_document_params(),
position = nil, -- get em all
}
end
local function build_label(args)
local ret = ""
for _, value in ipairs(args.cargoArgs) do
ret = ret .. value .. " "
end
for _, value in ipairs(args.cargoExtraArgs) do
ret = ret .. value .. " "
end
if not vim.tbl_isempty(args.executableArgs) then
ret = ret .. "-- "
for _, value in ipairs(args.executableArgs) do
ret = ret .. value .. " "
end
end
return ret
end
local function get_options(result)
local option_strings = {}
for _, debuggable in ipairs(result) do
local label = build_label(debuggable.args)
local str = label
table.insert(option_strings, str)
end
return option_strings
end
local function is_valid_test(args)
local is_not_cargo_check = args.cargoArgs[1] ~= "check"
return is_not_cargo_check
end
-- rust-analyzer doesn't actually support giving a list of debuggable targets,
-- so work around that by manually removing non debuggable targets (only cargo
-- check for now).
-- This function also makes it so that the debuggable commands are more
-- debugging friendly. For example, we move cargo run to cargo build, and cargo
-- test to cargo test --no-run.
local function sanitize_results_for_debugging(result)
local ret = {}
ret = vim.tbl_filter(function(value)
return is_valid_test(value.args)
end, result)
for i, value in ipairs(ret) do
if value.args.cargoArgs[1] == "run" then
ret[i].args.cargoArgs[1] = "build"
elseif value.args.cargoArgs[1] == "test" then
table.insert(ret[i].args.cargoArgs, 2, "--no-run")
end
end
return ret
end
local function handler(_, result)
result = sanitize_results_for_debugging(result)
local options = get_options(result)
vim.ui.select(options, { prompt = "Debuggables", kind = "rust-tools/debuggables" }, function(_, choice)
local args = result[choice].args
rt_dap.start(args)
end)
end
-- Sends the request to rust-analyzer to get the runnables and handles them
-- The opts provided here are forwarded to telescope, other than use_telescope
-- which is used to check whether we want to use telescope or the vanilla vim
-- way for input
function M.debuggables()
utils.request(0, "experimental/runnables", get_params(), handler)
end
return M
|
local Commodity = {}
function Commodity:new(o)
o = o or {} -- create object if user does not provide one
setmetatable(o, self)
self.__index = self
self.item = Item.GetDataFromId(o.id)
self.buy1 = '--'
self.buy10 = '--'
self.buy50 = '--'
self.sell1 = '--'
self.sell10 = '--'
self.sell50 = '--'
self.sellOrderCount = '--'
self.buyOrderCount = '--'
self.buyWatchPrice = '--'
self.sellWatchPrice = '--'
return o
end
function Commodity:GetId()
return self.id
end
function Commodity:GetName()
return Item.GetDataFromId(self.id):GetName() or "Undefined"
end
function Commodity:GetIcon()
return Item.GetDataFromId(self.id):GetIcon() or "Undefined"
end
function Commodity:GetItem()
return Item.GetDataFromId(self.id)
end
function Commodity:SetBuyWatchPrice(price)
self.buyWatchPrice = price
end
function Commodity:SetSellWatchPrice(price)
self.sellWatchPrice = price
end
function Commodity:UpdateTStats(tStats)
self.sell1 = tStats.arBuyOrderPrices[1].monPrice:GetAmount()
self.sell10 = tStats.arBuyOrderPrices[2].monPrice:GetAmount()
self.sell50 = tStats.arBuyOrderPrices[3].monPrice:GetAmount()
self.buy1 = tStats.arSellOrderPrices[1].monPrice:GetAmount()
self.buy10 = tStats.arSellOrderPrices[2].monPrice:GetAmount()
self.buy50 = tStats.arSellOrderPrices[3].monPrice:GetAmount()
self.sellOrderCount = tStats.nSellOrderCount
self.buyOrderCount = tStats.nBuyOrderCount
end
Apollo.RegisterPackage(Commodity, "Commodity", 1, {}) |
function travel_worm_recipe(tier)
return {
type = 'recipe',
name = 'nm-travel-worm-'..tier,
localised_name = {'entity-name.nm-travel-worm-'..tier},
localised_description = {'entity-description.nm-travel-worm-'..tier},
category = 'nm-alien-growing',
energy_required = 120,
enabled = false,
ingredients = {
{ 'nm-sandtrout-'..tier, 1 },
{ 'nm-spice', 50 }
},
result = 'nm-travel-worm-'..tier
}
end
data:extend({
-- Entities
{
type = 'recipe',
name = 'nm-water-injector-proxy',
localised_name = {'entity-name.nm-water-injector'},
localised_description = {'entity-description.nm-water-injector'},
energy_required = 2,
enabled = false,
ingredients = {
{ 'steel-plate', 5 },
{ 'pipe', 23 }
},
result = 'nm-water-injector-proxy'
},
{
type = 'recipe',
name = 'nm-drying-rig',
localised_name = {'entity-name.nm-drying-rig'},
localised_description = {'entity-description.nm-drying-rig'},
category = 'crafting',
energy_required = 20,
enabled = false,
ingredients = {
{ 'solar-panel', 4 },
{ 'advanced-circuit', 4 },
{ 'nm-solar-component-foil', 10 },
},
result = 'nm-drying-rig'
},
{
type = 'recipe',
name = 'nm-alien-growth-chamber',
localised_name = {'entity-name.nm-alien-growth-chamber'},
localised_description = {'entity-description.nm-alien-growth-chamber'},
category = 'crafting',
energy_required = 20,
enabled = false,
ingredients = {
{ 'solar-panel', 4 },
{ 'advanced-circuit', 4 },
{ 'nm-solar-component-foil', 10 },
},
result = 'nm-alien-growth-chamber'
},
travel_worm_recipe('small'),
travel_worm_recipe('medium'),
travel_worm_recipe('big'),
travel_worm_recipe('behemoth'),
{
type = 'recipe',
name = 'nm-spacing-guild',
localised_name = {'entity-name.nm-spacing-guild'},
localised_description = {'entity-description.nm-spacing-guild'},
category = 'crafting',
energy_required = 20,
enabled = false,
ingredients = {
{ 'nm-spice', 40 },
{ 'pipe', 20 },
{ 'advanced-circuit', 20 },
{ 'steel-plate', 20 },
},
result = 'nm-spacing-guild'
},
{
type = 'recipe',
name = 'nm-d-u-n-e',
normal = {
enabled = true,
energy_required = 5,
ingredients =
{
{'engine-unit', 32},
{'steel-plate', 50},
{'iron-gear-wheel', 15},
{'advanced-circuit', 10}
},
result = 'nm-d-u-n-e'
},
expensive = {
enabled = true,
energy_required = 8,
ingredients =
{
{'engine-unit', 64},
{'steel-plate', 100},
{'iron-gear-wheel', 30},
{'advanced-circuit', 20}
},
result = 'nm-d-u-n-e'
}
},
-- Items
{
type = 'recipe',
name = 'nm-solar-component-foil',
localised_name = {'item-name.nm-solar-component-foil'},
localised_description = {'item-description.nm-solar-component-foil'},
category = 'crafting',
energy_required = 10,
enabled = false,
ingredients = {
{ 'copper-plate', 3 },
{ 'plastic-bar', 2 },
{ 'iron-plate', 3 },
},
results = {
{ type = 'item', name = 'nm-solar-component-foil', amount = 20 }
},
},
{
type = 'recipe',
name = 'nm-spice',
category = 'nm-drying',
energy_required = 60,
enabled = false,
ingredients = {{ 'nm-pre-spice-mass', 20 }},
results = {
{ type = 'item', name = 'nm-spice', amount = 20 }
},
},
{
type = 'recipe',
name = 'nm-sandtrout-small',
localised_name = {'item-name.nm-sandtrout-small'},
localised_description = {'item-description.nm-sandtrout-small'},
category = 'nm-alien-growing',
energy_required = 60,
enabled = false,
ingredients = {
{ 'nm-pre-spice-mass', 20 },
{ 'nm-worm-sample-small', 1 }
},
results = {
{ type = 'item', name = 'nm-sandtrout-small', amount = 1 }
},
},
{
type = 'recipe',
name = 'nm-sandtrout-medium',
localised_name = {'item-name.nm-sandtrout-medium'},
localised_description = {'item-description.nm-sandtrout-medium'},
category = 'nm-alien-growing',
energy_required = 120,
enabled = false,
ingredients = {
{ 'nm-sandtrout-small', 1 },
{ 'nm-pre-spice-mass', 40 },
{ 'nm-worm-sample-medium', 1 }
},
results = {
{ type = 'item', name = 'nm-sandtrout-medium', amount = 1 }
},
},
{
type = 'recipe',
name = 'nm-sandtrout-big',
localised_name = {'item-name.nm-sandtrout-big'},
localised_description = {'item-description.nm-sandtrout-big'},
category = 'nm-alien-growing',
energy_required = 240,
enabled = false,
ingredients = {
{ 'nm-sandtrout-medium', 1 },
{ 'nm-pre-spice-mass', 40 },
{ 'nm-worm-sample-big', 1 }
},
results = {
{ type = 'item', name = 'nm-sandtrout-big', amount = 1 }
},
},
{
type = 'recipe',
name = 'nm-sandtrout-behemoth',
localised_name = {'item-name.nm-sandtrout-behemoth'},
localised_description = {'item-description.nm-sandtrout-behemoth'},
category = 'nm-alien-growing',
energy_required = 240,
enabled = false,
ingredients = {
{ 'nm-sandtrout-big', 1 },
{ 'nm-pre-spice-mass', 100 },
{ 'nm-worm-sample-behemoth', 1 }
},
results = {
{ type = 'item', name = 'nm-sandtrout-behemoth', amount = 1 }
},
},
{
type = 'recipe',
name = 'nm-biter-leech',
localised_name = {'item-name.nm-biter-leech'},
localised_description = {'item-description.nm-biter-leech'},
category = 'nm-alien-growing',
energy_required = 60,
enabled = false,
ingredients = {
{ 'nm-pre-spice-mass', 20 },
{ 'nm-biter-sample', 20 }
},
results = {
{ type = 'item', name = 'nm-biter-leech', amount = 20 }
},
},
{
type = 'recipe',
name = 'nm-alien-probe',
localised_name = {'item-name.nm-alien-probe'},
localised_description = {'item-description.nm-alien-probe'},
category = 'crafting',
energy_required = 4,
enabled = false,
ingredients = {
{ 'iron-plate', 2 },
{ 'iron-stick', 1 },
},
result = 'nm-alien-probe'
},
{
type = 'recipe',
name = 'nm-thumper',
localised_name = {'item-name.nm-thumper'},
localised_description = {'item-description.nm-thumper'},
category = 'crafting',
energy_required = 4,
enabled = false,
ingredients = {
{ 'iron-stick', 1 },
},
result = 'nm-thumper'
},
{
type = 'recipe',
name = 'nm-thumper-creative',
localised_name = {'item-name.nm-thumper-creative'},
localised_description = {'item-description.nm-thumper-creative'},
category = 'crafting',
energy_required = 4,
enabled = true,
ingredients = {
{ 'iron-stick', 1 },
},
result = 'nm-thumper-creative'
},
{
type = 'recipe',
name = 'nm-biter-navigator',
localised_name = {'item-name.nm-biter-navigator'},
localised_description = {'item-description.nm-biter-navigator'},
category = 'nm-space-education',
energy_required = 60,
enabled = false,
ingredients = {
{ type = 'item', name = 'nm-biter-leech', amount = 1 },
{ type = 'item', name = 'low-density-structure', amount = 10 },
{ type = 'item', name = 'advanced-circuit', amount = 4 },
{ type = 'fluid', name = 'nm-spice-gas', amount = 200 },
},
result = 'nm-biter-navigator'
},
{
type = 'recipe',
name = 'nm-fish-navigator',
localised_name = {'item-name.nm-fish-navigator'},
localised_description = {'item-description.nm-fish-navigator'},
category = 'nm-space-education',
energy_required = 60,
enabled = false,
ingredients = {
{ type = 'item', name = 'raw-fish', amount = 1 },
{ type = 'item', name = 'low-density-structure', amount = 10 },
{ type = 'item', name = 'advanced-circuit', amount = 4 },
{ type = 'fluid', name = 'nm-spice-gas', amount = 200 },
},
result = 'nm-fish-navigator'
},
})
|
-- read environment variables as if they were global variables
local f=function (t,i) return os.getenv(i) end
setmetatable(getfenv(),{__index=f})
-- an example
print(a,USER,PATH)
|
local periodicStuff = createLinkedList()
function clearInventories(manufacturer)
for _,v in pairs(manufacturer:getInventories()) do
v:flush()
end
end
function initNetwork()
networkHandler(100, null, { -- table of message handlers
})
end
---@type FluidContainer[]
local containers = {}
function scheduler()
for _, v in pairs(containers) do
local container = v.container:get()
local stock = container:getInventories()[1].ItemCount
print(v.itemName .. " has " .. tostring(stock) .. "(" .. tostring(v.outstanding) .. ") and should be at " .. tostring(v.limit) )
if v.limit - stock - v.outstanding > v.treshold and v.outstanding < v.maxOutstanding then
v.outstanding = v.outstanding + v.treshold
print("Order " .. tostring(v.treshold) .. " " .. v.itemName)
---@type ProdMgrRequestToMsg
local request = {
name = v.itemName,
count = v.treshold,
bus = scriptInfo.puller
}
scriptInfo.network:send(scriptInfo.addresses.ProdMgr, 100, "requestTo", "json", json.encode(request))
end
end
end
---@class FluidContainer
---@field public itemName string
---@field public treshold number
---@field public limit number
---@field public container ComponentReference
---@field public maxOutstanding number
---@field public outstanding number
local FluidContainer = {}
---@param itemName string
---@param compID string
---@param treshold number
---@param limit number
---@param maxOutstanding number
---@return FluidContainer
function FluidContainer.new(itemName, compID, treshold, limit, maxOutstanding)
---@type FluidContainer
local obj = {
itemName = itemName,
treshold = treshold,
limit = limit,
container = createReference(compID),
maxOutstanding = maxOutstanding
}
setmetatable(obj, FluidContainer)
FluidContainer.__index = FluidContainer
end
function FluidContainer:onItem()
self.outstanding = outstanding - 1
end
function initContainers()
local all = component.findComponent("");
for _,id in pairs(all) do
local comp = component.proxy(id)
local cname = comp.nick
local p = explode("_", cname)
if p[1] == scriptInfo.containerPrefix then
local itemName = p[2]
local parameters = parseOutputs(p[3])
print("Found container for ".. itemName)
printArray(parameters)
local treshold = parameters["T"]
if treshold == nil then
treshold = stackSize[itemName]
end
local fillTo = parameters["L"]
local maxOutstanding = parameters["O"]
if maxOutstanding == nil then
maxOutstanding = treshold
end
local container = FluidContainer.new(itemName, comp.id, tonumber(treshold), tonumber(fillTo), tonumber(maxOutstanding))
local container = {
itemName = itemName,
treshold = tonumber(treshold),
limit = tonumber(fillTo),
container = createReference(comp.id),
maxOutstanding = tonumber(maxOutstanding),
outstanding = 0,
onItem = function(self)
self.outstanding = self.outstanding - 1
end
}
local connector = comp:getFactoryConnectors()[tonumber(parameters["I"])]
registerEvent(connector, container, container.onItem, nil, true)
table.insert(containers, container)
end
end
end
function main()
initNetwork()
initContainers()
--printArray(stock.Coal, 2)
rmessage("Startup delay")
wait(4000)
rmessage("System Operational")
schedulePeriodicTask(PeriodicTask.new(scheduler, nil, nil, "Fluid Scheduler"))
print( " -- - INIT DONE - - -- ")
for _, v in pairs(containers) do
print(v.itemName .. " @ " .. tostring(v.limit))
end
print( " -- - STARTUP DONE - - -- ")
commonMain(10, 1)
end |
luachip.AddFunction("print", print)
luachip.AddFunction("yield", function()
coroutine.yield()
end)
luachip.AddFunction("Entity", Entity) |
function onCreate()
-- background shit
makeLuaSprite('alleybg', 'alleybg', -500, -300);
setLuaSpriteScrollFactor('alleybg', 0.9, 0.9);
makeLuaSprite('alleyfloor', 'alleyfloor', -500, -300);
setLuaSpriteScrollFactor('alleyfloor', 0.9, 0.9);
makeLuaSprite('alleycat', 'alleycat', -500, -300);
setLuaSpriteScrollFactor('alleycat', 1.3, 1.3);
scaleObject('alleycat', 0.9, 0.9);
end
addLuaSprite('alleybg', false);
addLuaSprite('alleyfloor', false);
addLuaSprite('alleycat', false);
close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage
end |
--[[
Surface: Keyboard Arturia Keylab MKII
Developer: Thierry Fraudet / Modified for MKII by Wade Carson
Version: 1.3
Date: 21/12/2019
]]
g_lcd_line1_index = 1
g_lcd_line2_index = 2
g_lcd_line1_new_text = ""
g_lcd_line1_old_text = ""
g_lcd_line2_new_text = ""
g_lcd_line2_old_text = ""
g_preset_jog_wheel_index = 44
g_cat_jog_wheel_index = 51
g_quartet_effect_selected = ""
g_sweeper_effect_selected = ""
function remote_init(manufacturer, model)
local items = {
{name="lcd-1", output="text"},
{name="lcd-2", output="text"},
{name="Keyboard", input="keyboard"},
{name="Channel Pressure", input="value", min=0, max=127},
{name="Mod Wheel", input="value", min=0, max=127},
{name="Pitch Bend", input="value", min=0, max=16384},
{name="Expression", input="value", min=0, max=127},
{name="Breath", input="value", min=0, max=127},
{name="Damper Pedal", input="value", min=0, max=127},
{name="pad-1", input="button", output="value"},
{name="pad-2", input="button", output="value"},
{name="pad-3", input="button", output="value"},
{name="pad-4", input="button", output="value"},
{name="pad-5", input="button", output="value"},
{name="pad-6", input="button", output="value"},
{name="pad-7", input="button", output="value"},
{name="pad-8", input="button", output="value"},
{name="pad-9", input="button", output="value"},
{name="pad-10", input="button", output="value"},
{name="pad-11", input="button", output="value"},
{name="pad-12", input="button", output="value"},
{name="pad-13", input="button", output="value"},
{name="pad-14", input="button", output="value"},
{name="pad-15", input="button", output="value"},
{name="pad-16", input="button", output="value"},
{name="fader-1", input="value", output="value", min=0, max=127},
{name="fader-2", input="value", output="value", min=0, max=127},
{name="fader-3", input="value", output="value", min=0, max=127},
{name="fader-4", input="value", output="value", min=0, max=127},
{name="fader-5", input="value", output="value", min=0, max=127},
{name="fader-6", input="value", output="value", min=0, max=127},
{name="fader-7", input="value", output="value", min=0, max=127},
{name="fader-8", input="value", output="value", min=0, max=127},
{name="pan-1", input="value", output="value", min=0, max=127},
{name="pan-2", input="value", output="value", min=0, max=127},
{name="pan-3", input="value", output="value", min=0, max=127},
{name="pan-4", input="value", output="value", min=0, max=127},
{name="pan-5", input="value", output="value", min=0, max=127},
{name="pan-6", input="value", output="value", min=0, max=127},
{name="pan-7", input="value", output="value", min=0, max=127},
{name="pan-8", input="value", output="value", min=0, max=127},
{name="master-pan", input="value", output="value", min=0, max=127},
{name="master-volume", input="value", output="value", min=0, max=127},
-- index 51
{name="preset-jog-wheel", input="delta"},
{name="preset-jog-wheel-button", input="button"},
{name="preset-prev", input="button", output="value"},
{name="preset-next", input="button", output="value"},
{name="part1-next", input="button", output="value"},
{name="part2-prev", input="button", output="value"},
{name="live-bank", input="button", output="value"},
{name="cat-jog-wheel", input="delta"},
{name="cat-jog-wheel-button", input="button"},
{name="cat-prev", input="button", output="value"},
{name="cat-next", input="button", output="value"},
{name="left-arrow", input="button", output="value"},
{name="right-arrow", input="button", output="value"},
-- index is 57
{name="pan-1-var-a", input="value", output="value", min=0, max=127},
{name="pan-2-var-a", input="value", output="value", min=0, max=127},
{name="pan-3-var-a", input="value", output="value", min=0, max=127},
{name="pan-4-var-a", input="value", output="value", min=0, max=127},
{name="pan-5-var-a", input="value", output="value", min=0, max=127},
{name="pan-6-var-a", input="value", output="value", min=0, max=127},
{name="pan-7-var-a", input="value", output="value", min=0, max=127},
{name="pan-8-var-a", input="value", output="value", min=0, max=127},
{name="master-pan-var-a", input="value", output="value", min=0, max=127},
-- index is 66
{name="pan-1-var-b", input="value", output="value", min=0, max=127},
{name="pan-2-var-b", input="value", output="value", min=0, max=127},
{name="pan-3-var-b", input="value", output="value", min=0, max=127},
{name="pan-4-var-b", input="value", output="value", min=0, max=127},
{name="pan-5-var-b", input="value", output="value", min=0, max=127},
{name="pan-6-var-b", input="value", output="value", min=0, max=127},
{name="pan-7-var-b", input="value", output="value", min=0, max=127},
{name="pan-8-var-b", input="value", output="value", min=0, max=127},
{name="master-pan-var-b", input="value", output="value", min=0, max=127},
-- index is 75
{name="pan-1-var-c", input="value", output="value", min=0, max=127},
{name="pan-2-var-c", input="value", output="value", min=0, max=127},
{name="pan-3-var-c", input="value", output="value", min=0, max=127},
{name="pan-4-var-c", input="value", output="value", min=0, max=127},
{name="pan-5-var-c", input="value", output="value", min=0, max=127},
{name="pan-6-var-c", input="value", output="value", min=0, max=127},
{name="pan-7-var-c", input="value", output="value", min=0, max=127},
{name="pan-8-var-c", input="value", output="value", min=0, max=127},
{name="master-pan-var-c", input="value", output="value", min=0, max=127},
-- index is 84
{name="pan-1-var-d", input="value", output="value", min=0, max=127},
{name="pan-2-var-d", input="value", output="value", min=0, max=127},
{name="pan-3-var-d", input="value", output="value", min=0, max=127},
{name="pan-4-var-d", input="value", output="value", min=0, max=127},
{name="pan-5-var-d", input="value", output="value", min=0, max=127},
{name="pan-6-var-d", input="value", output="value", min=0, max=127},
{name="pan-7-var-d", input="value", output="value", min=0, max=127},
{name="pan-8-var-d", input="value", output="value", min=0, max=127},
{name="master-pan-var-d", input="value", output="value", min=0, max=127},
{name="Select1", input="button", output="value"},
{name="Select2", input="button", output="value"},
{name="Select3", input="button", output="value"},
{name="Select4", input="button", output="value"},
{name="Select5", input="button", output="value"},
{name="Select6", input="button", output="value"},
{name="Select7", input="button", output="value"},
{name="Select8", input="button", output="value"},
{name="Multi", input="button", output="value"},
}
remote.define_items(items)
----------------------------------------------------------------------------
local inputs = {
{pattern="e? xx yy", name="Pitch Bend", value="y*128 + x"},
{pattern="b? 01 xx", name="Mod Wheel"},
{pattern="b? 0b xx", name="Expression"},
{pattern="b? 02 xx", name="Breath"},
{pattern="d? xx", name="Channel Pressure"},
{pattern="b? 40 xx", name="Damper Pedal"},
{pattern="<100x>? yy zz", name="Keyboard"},
--[[
{pattern="<100y>? 24 zz", name="pad-1"},
{pattern="<100y>0 25 xx", name="pad-2"},
{pattern="<100y>0 26 xx", name="pad-3"},
{pattern="<100y>0 27 xx", name="pad-4"},
{pattern="<100y>0 28 xx", name="pad-5"},
{pattern="<100y>0 29 xx", name="pad-6"},
{pattern="<100y>0 2a xx", name="pad-7"},
{pattern="<100y>0 2b xx", name="pad-8"},
{pattern="<100y>0 2c xx", name="pad-9"},
{pattern="<100y>0 2d xx", name="pad-10"},
{pattern="<100y>0 2e xx", name="pad-11"},
{pattern="<100y>0 2f xx", name="pad-12"},
{pattern="<100y>0 00 xx", name="pad-13"},
{pattern="<100y>0 31 xx", name="pad-14"},
{pattern="<100y>0 32 xx", name="pad-15"},
{pattern="<100y>0 33 xx", name="pad-16"},
]]
{pattern="b? 49 xx", name="fader-1", value="x"},
{pattern="b? 4b xx", name="fader-2", value="x"},
{pattern="b? 4f xx", name="fader-3", value="x"},
{pattern="b? 48 xx", name="fader-4", value="x"},
{pattern="b? 50 xx", name="fader-5", value="x"},
{pattern="b? 51 xx", name="fader-6", value="x"},
{pattern="b? 52 xx", name="fader-7", value="x"},
{pattern="b? 53 xx", name="fader-8", value="x"},
{pattern="b? 4a xx", name="pan-1", value="x"},
{pattern="b? 47 xx", name="pan-2", value="x"},
{pattern="b? 4c xx", name="pan-3", value="x"},
{pattern="b? 4d xx", name="pan-4", value="x"},
{pattern="b? 5d xx", name="pan-5", value="x"},
{pattern="b? 12 xx", name="pan-6", value="x"},
{pattern="b? 13 xx", name="pan-7", value="x"},
{pattern="b? 10 xx", name="pan-8", value="x"},
{pattern="b? 11 xx", name="master-pan", value="x"},
{pattern="b? 55 xx", name="master-volume", value="x"},
{pattern="b? 1e 0<000x>", name="Select1", value="x"}, -- b0 1e 01
{pattern="b? 1e 0<001x>", name="Select2", value="x"}, -- b0 1e 03
{pattern="b? 1e 0<010x>", name="Select3", value="x"}, -- b0 1e 05
{pattern="b? 1e 0<011x>", name="Select4", value="x"}, -- b0 1e 07
{pattern="b? 1e 0<100x>", name="Select5", value="x"}, -- b0 1e 09
{pattern="b? 1e 0<101x>", name="Select6", value="x"}, -- b0 1e 0b
{pattern="b? 1e 0<110x>", name="Select7", value="x"}, -- b0 1e 0d
{pattern="b? 1e 0<111x>", name="Select8", value="x"}, -- b0 1e 0f
{pattern="b? 1e 1<000x>", name="Multi", value="x"}, -- b0 1e 11
{pattern="b? 72 <?y??><???x>", name="preset-jog-wheel", value="x*(2*y-1)"}, -- when "Preset" is selected, 41 <0100><0001> ou 3f <0011><1111>
{pattern="b? 73 xx", name="preset-jog-wheel-button", value="x"}, -- When "Preset" is selected
-- {pattern="b? 72 3f", name="preset-prev", value="1"},
-- {pattern="b? 72 41", name="preset-next", value="1"},
{pattern="b? 70 <?y??><???x>", name="cat-jog-wheel", value="x*(2*y-1)"}, -- when "Cat" is selected, 41 <0100><0001> ou 3f <0011><1111>
{pattern="b? 71 xx", name="cat-jog-wheel-button", value="x"}, -- when "Cat" is selected
-- {pattern="b? 70 3f", name="cat-prev", value="1"},
-- {pattern="b? 70 41", name="cat-next", value="1"},
{pattern="b? 16 xx", name="part1-next", value="x"},
{pattern="b? 17 xx", name="part2-prev", value="x"},
{pattern="b? 18 xx", name="live-bank", value="x"},
{pattern="b? 1c xx", name="left-arrow", value="x"},
{pattern="b? 1d xx", name="right-arrow", value="x"},
}
remote.define_auto_inputs(inputs)
--Auto outputs
local outputs = {
{name="pan-1", pattern="b? 4a xx"},
{name="pan-2", pattern="b? 47 xx"},
{name="pan-3", pattern="b? 4c xx"},
{name="pan-4", pattern="b? 4d xx"},
{name="pan-5", pattern="b? 5d xx"},
{name="pan-6", pattern="b? 12 xx"},
{name="pan-7", pattern="b? 13 xx"},
{name="pan-8", pattern="b? 10 xx"},
{name="master-pan", pattern="b? 11 xx"},
{name="fader-1", pattern="b? 49 xx"},
{name="fader-2", pattern="b? 4b xx"},
{name="fader-4", pattern="b? 48 xx"},
{name="fader-5", pattern="b? 50 xx"},
{name="fader-6", pattern="b? 51 xx"},
{name="fader-7", pattern="b? 52 xx"},
{name="fader-8", pattern="b? 53 xx"},
{name="master-volume", pattern="b? 55 xx"},
{name="part1-next", pattern="b? 16 xx"},
{name="part2-prev", pattern="b? 17 xx"},
{name="live-bank", pattern="b? 18 xx"},
{name="Select1", pattern="b? 1e 0<000x>"}, -- b0 1e 01
{name="Select2", pattern="b? 1e 0<001x>"}, -- b0 1e 03
{name="Select3", pattern="b? 1e 0<010x>"}, -- b0 1e 05
{name="Select4", pattern="b? 1e 0<011x>"}, -- b0 1e 07
{name="Select5", pattern="b? 1e 0<100x>"}, -- b0 1e 09
{name="Select6", pattern="b? 1e 0<101x>"}, -- b0 1e 0b
{name="Select7", pattern="b? 1e 0<110x>"}, -- b0 1e 0d
{name="Select8", pattern="b? 1e 0<111x>"}, -- b0 1e 0f
{name="Multi", pattern="b? 1e 1<000x>"}, -- b0 1e 11
--[[
{name="pad-1", pattern="<100y>? 24 zz"},
{name="pad-2", pattern="<100y>0 25 xx"},
{name="pad-3", pattern="<100y>0 26 xx"},
{name="pad-4", pattern="<100y>0 27 xx"},
{name="pad-5", pattern="<100y>0 28 xx"},
{name="pad-6", pattern="<100y>0 29 xx"},
{name="pad-7", pattern="<100y>0 2a xx"},
{name="pad-8", pattern="<100y>0 2b xx"},
{name="pad-9", pattern="<100y>0 2c xx"},
{name="pad-10", pattern="<100y>0 2d xx"},
{name="pad-11", pattern="<100y>0 2e xx"},
{name="pad-12", pattern="<100y>0 2f xx"},
{name="pad-13", pattern="<100y>0 00 xx"},
{name="pad-14", pattern="<100y>0 31 xx"},
{name="pad-15", pattern="<100y>0 32 xx"},
{name="pad-16", pattern="<100y>0 33 xx"},
]]
}
remote.define_auto_outputs(outputs)
end
encoder_patterns = {
"b? 4a xx", -- pan-1
"b? 47 xx", -- pan-2
"b? 4c xx", -- pan-3
"b? 4d xx", -- pan-4
"b? 5d xx", -- pan-5
"b? 12 xx", -- pan-6
"b? 13 xx", -- pan-7
"b? 10 xx", -- pan-8
"b? 11 xx", -- master pan
}
-- Return the encoder that has been activated (1 to 8 and 9 for the master-pan) or -1 if any
function incomingMidiMessageFromEncoder(event)
for key,value in ipairs(encoder_patterns) do
ret = remote.match_midi(value,event)
if ret~=nil then
return key
end
end
return -1
end
function remote_process_midi(event) -- handle incoming midi event
--test if preset jog-wheel turn right
--ret = remote.match_midi("b? 72 41",event)
--if ret~=nil then
-- remote.trace(" Send preset-next to Reason\n")
-- local msg={ time_stamp=event.time_stamp, item=47, value=1 }
-- remote.handle_input(msg)
-- return true
--end
--test if preset jog-wheel turn left
--ret = remote.match_midi("b? 72 3f",event)
--if ret~=nil then
-- remote.trace(" Send preset-prev to Reason\n")
-- local msg={ time_stamp=event.time_stamp, item=46, value=1 }
-- remote.handle_input(msg)
-- return true
--end
local tab_index = {Chorus = 57, BDD = 66, FFT = 75, Grain = 84}
if string.starts(g_lcd_line1_new_text,"Quartet") then
local encoder_number = incomingMidiMessageFromEncoder(event) -- which encoder number send midi ?
local item_to_activate
-- tell reason to process the translated incoming midi message
if encoder_number > 0 then
-- handle midi msg depending on selected effect on Quartet
if g_quartet_effect_selected == "Chorus" then
item_to_activate = tab_index.Chorus + (encoder_number-1)
elseif g_quartet_effect_selected == "BBD" then
item_to_activate = tab_index.BDD + (encoder_number-1)
elseif g_quartet_effect_selected == "FFT" then
item_to_activate = tab_index.FFT + (encoder_number-1)
elseif g_quartet_effect_selected == "Grain" then
item_to_activate = tab_index.Grain + (encoder_number-1)
end
-- decode the incoming midi message for the activated encoder
ret = remote.match_midi(encoder_patterns[encoder_number],event)
if ret~=nil then
msg={ time_stamp=event.time_stamp, item=item_to_activate, value=ret.x }
remote.handle_input(msg)
return true
end
end
end
return false
end
g_rv7_algorithms = { "Hall", "Large Hall", "Hall 2", "Large Room", "Medium Room", "Small Room", "Gated", "Low Density","Stereo Echoes","Pan Room"}
g_matrix_bank = { "A", "B", "C", "D"}
function remote_set_state(changed_items) --handle incoming changes sent by Reason
for i,item_index in ipairs(changed_items) do
-- if i==0 then g_lcd_line2_new_text = '!'; end
if item_index==g_lcd_line1_index then
--g_is_lcd_enabled=remote.is_item_enabled(item_index)
g_lcd_line1_new_text=remote.get_item_text_value(item_index)
end
if item_index==g_lcd_line2_index then
--g_is_lcd_enabled=remote.is_item_enabled(item_index)
g_lcd_line2_new_text=remote.get_item_text_value(item_index)
end
if item_index==g_preset_jog_wheel_index then
if g_lcd_line1_new_text == "RV-7 (reverb)" then
g_lcd_line2_new_text = g_rv7_algorithms[remote.get_item_text_value(item_index)+1]
end
if g_lcd_line1_new_text == "Matrix" then
bank = math.floor(remote.get_item_text_value(item_index) / 8) +1
if bank == 0 then
g_lcd_line2_new_text = "Bank - / Pat. -"
else
pattern = remote.get_item_text_value(item_index) - ((bank-1)*8) +1
g_lcd_line2_new_text = "Bank "..g_matrix_bank[bank].." / Pat. "..pattern
end
end
if g_lcd_line1_new_text == "Audiomatic" then
g_lcd_line2_new_text = remote.get_item_text_value(item_index)
end
end
if string.starts(g_lcd_line1_new_text,"Quartet") then
if item_index==g_cat_jog_wheel_index then
g_quartet_effect_selected = remote.get_item_text_value(item_index)
g_lcd_line1_new_text = "Quartet ("..g_quartet_effect_selected..")"
end
end
if string.starts(g_lcd_line1_new_text,"Sweeper") then
if item_index==g_cat_jog_wheel_index then
g_sweeper_effect_selected = remote.get_item_text_value(item_index)
g_lcd_line1_new_text = "Sweeper("..g_sweeper_effect_selected..")"
end
end
end
end
function remote_deliver_midi(max_bytes, port)
local ret_events={}
-- if there is a new message to display
if (g_lcd_line1_new_text ~= g_lcd_line1_old_text) then
g_lcd_line1_old_text = g_lcd_line1_new_text
table.insert(ret_events,make_lcd_midi_message(g_lcd_line1_new_text, g_lcd_line2_old_text))
end
-- if there is a new message to display
if (g_lcd_line2_new_text ~= g_lcd_line2_old_text) then
g_lcd_line2_old_text = g_lcd_line2_new_text
table.insert(ret_events,make_lcd_midi_message(g_lcd_line1_old_text, g_lcd_line2_new_text))
end
return ret_events
end
function remote_probe(manufacturer,model,prober)
-- Arturia Manufacturer SysEx ID Numbers is: 00 20 6b
-- Need to be rework, for hardware with multiple ports must be done programaticaly (see Remote SDK documentation page 26 & 27)
assert(model == "Keylab61 Essential")
local controlRequest="f0 7e 7f 06 01 f7" -- sysex de demande d'identification
local controlResponse="F0 7E 7F 06 02 00 20 6B 02 00 05 54 3D 02 01 01 F7"
return {
request=controlRequest,
response=controlResponse
}
end
function remote_prepare_for_use()
local retEvents={
-- Display message on LCD
make_lcd_midi_message("Reason Remote", "connected"),
}
return retEvents
end
function remote_release_from_use()
local retEvents={
-- Display message on LCD
make_lcd_midi_message("Reason Remote", "disconnected"),
}
return retEvents
end
function stringToHex(text)
local hexStringToReturn = ""
for i=1, string.len(text) do
if string.len(hexStringToReturn) > 0 then
hexStringToReturn = hexStringToReturn .. " "
end
hexStringToReturn = hexStringToReturn .. string.format("%X", string.byte(text,i))
end
return hexStringToReturn
end
function make_lcd_midi_message(line1, line2)
local sysex = "f0 00 20 6b 7f 42 04 00 60 01" .. stringToHex(string.sub(line1,1,16)) .. " 00 02" .. stringToHex(string.sub(line2,1,16)) .. " 00 f7"
local event=remote.make_midi(sysex)
return event
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start)) == Start
end
|
require("floodgate")
--At most 500 messages can be sent per second
timer.Create("Floodgate",1,0,function()
ConsoleFloodgate(500)
end) |
local PlaybackConfiguration = require("PlaybackConfiguration")
local Runner = require("Runner")
local PlayerControl = require("PlayerControl")
local PlaybackController = { }
local metatable = { __index = PlaybackController }
PlaybackController.playback_state =
{
tick_1_prepare_to_attach_runner = 1,
tick_2_attach_runner = 2,
tick_3_running = 3,
tick_4_prepare_to_attach_player = 4,
tick_5_attach_player = 5
}
function PlaybackController.set_metatable(instance)
if getmetatable(instance) ~= nil then
return
end
setmetatable(instance, metatable)
PlaybackConfiguration.set_metatable(instance.configuration)
if instance.configuration_after_runners_have_stepped ~= nil then
PlaybackConfiguration.set_metatable(instance.configuration_after_runners_have_stepped)
end
for i = 1, #instance.runner_instances do
Runner.set_metatable(instance.runner_instances[i].runner)
end
end
function PlaybackController.new()
local new =
{
playback_state = PlaybackController.playback_state.paused,
num_times_to_step = nil,
runner_being_stepped_index = nil,
runner_instances = { },
configuration = PlaybackConfiguration.new_paused(),
configuration_after_runners_have_stepped = nil
}
PlaybackController.set_metatable(new)
new:_apply_configuration(PlaybackConfiguration.new_paused())
return new
end
-- Create a new runner and character entity
-- Returns nil if sequence is empty
function PlaybackController:new_runner(sequence, controller_type)
fail_if_missing(sequence)
if controller_type ~= defines.controllers.character and controller_type ~= defines.controllers.god then
error()
end
if self:get_runner(sequence) ~= nil then
error()
end
local new =
{
runner = Runner.new(sequence),
controller_type = controller_type
}
if controller_type == defines.controllers.character then
new.character = util.spawn_character()
end
self.runner_instances[#self.runner_instances + 1] = new
end
-- Removes (and murders) the runner.
function PlaybackController:remove_runner(runner)
fail_if_missing(runner)
for i=1, #self.runner_instances do
local instance = self.runner_instances[i]
if instance.runner == runner then
-- murder it
if is_valid(instance.character) then
if instance.character.destroy() == false then
log_error( { "TAS-err-generic", "couldn't destroy character :( pls fix" })
end
end
table.remove(self.runner_instances, i)
return
end
end
error()
end
function PlaybackController:_get_runner_instance(sequence)
for k, runner_instance in pairs(self.runner_instances) do
if runner_instance.runner:get_sequence() == sequence then
return runner_instance
end
end
end
function PlaybackController:get_runner(sequence)
local instance = self:_get_runner_instance(sequence)
if instance ~= nil then
return instance.runner
end
end
function PlaybackController:try_get_character(sequence)
local instance = self:_get_runner_instance(sequence)
if instance ~= nil then
return instance.character
end
end
function PlaybackController:runners_exist()
return #self.runner_instances > 0
end
function PlaybackController:_reset_runners()
local runner_instances_clone = util.clone_table(self.runner_instances)
for i = 1, #runner_instances_clone do
local runner = runner_instances_clone[i].runner
local sequence = runner:get_sequence()
self:remove_runner(runner)
self:new_runner(sequence, runner_instances_clone[i].controller_type)
end
end
function PlaybackController:on_tick()
if self:runners_exist() == false then return end
if self:is_paused() == true then return end
local player = self.configuration.player
local runner_properties = self.runner_instances[self.runner_being_stepped_index]
local runner = runner_properties.runner
local character = runner_properties.character
if self.playback_state == PlaybackController.playback_state.tick_1_prepare_to_attach_runner then
self:freeze_player(player)
self.playback_state = PlaybackController.playback_state.tick_2_attach_runner
elseif self.playback_state == PlaybackController.playback_state.tick_2_attach_runner then
self:attach_player(player, character)
player.cheat_mode = false
self.playback_state = PlaybackController.playback_state.tick_3_running
elseif self.playback_state == PlaybackController.playback_state.tick_3_running then
runner:set_player(player)
runner:step()
if self.runner_being_stepped_index < #self.runner_instances then
self.runner_being_stepped_index = self.runner_being_stepped_index + 1
self.playback_state = PlaybackController.playback_state.tick_1_prepare_to_attach_runner
else
if self.configuration_after_runners_have_stepped == nil then
self.runner_being_stepped_index = 1
if #self.runner_instances ~= 1 then
-- only attach a new player if there are multiple runners to switch between
self.playback_state = PlaybackController.playback_state.tick_1_prepare_to_attach_runner
end
if self.num_times_to_step ~= nil then
self.num_times_to_step = self.num_times_to_step - 1
if self.num_times_to_step <= 0 then
self.playback_state = PlaybackController.playback_state.tick_4_prepare_to_attach_player
end
end
else
-- Get ready to apply the pending configuration.
self.playback_state = PlaybackController.playback_state.tick_4_prepare_to_attach_player
end
end
elseif self.playback_state == PlaybackController.playback_state.tick_4_prepare_to_attach_player then
self:freeze_player(player)
self.playback_state = PlaybackController.playback_state.tick_5_attach_player
elseif self.playback_state == PlaybackController.playback_state.tick_5_attach_player then
local player_original_character = self.configuration.player_character_after_playback_completes
self:attach_player(player, player_original_character)
player.cheat_mode = true
if self.configuration_after_runners_have_stepped ~= nil then
self:_apply_configuration(self.configuration_after_runners_have_stepped)
else
self:_apply_configuration(PlaybackConfiguration.new_paused())
end
end
end
function PlaybackController:freeze_player(player_entity)
-- Make character stand still
if player_entity.character ~= nil then
player_entity.character.walking_state = { walking = false }
end
-- move items from cursor to inventory.
-- Fixed sometime around 0.15: cursor_stack remains with character when changing controllers
--[[if player_entity.cursor_stack.valid_for_read == true then
player_entity.get_inventory(defines.inventory.player_main).insert(player_entity.cursor_stack)
player_entity.cursor_stack.clear()
end--]]
end
--[Comment]
-- Sets the player controller to the character.
-- if character is nil, the player enters god mode.
function PlaybackController:attach_player(player_entity, character)
self:freeze_player(player_entity)
if character ~= nil then
player_entity.set_controller( { type = defines.controllers.character, character = character })
else
player_entity.set_controller( { type = defines.controllers.god })
end
self:freeze_player(player_entity)
end
--[Comment]
-- Immediately applies the PlaybackConfiguration.
function PlaybackController:_apply_configuration(config)
fail_if_missing(config)
if config.mode == PlaybackConfiguration.mode.pause then
self.configuration = config
self.playback_state = nil
self.num_times_to_step = nil
self.runner_being_stepped_index = nil
elseif config.mode == PlaybackConfiguration.mode.reset then
self:_reset_runners()
self.configuration = PlaybackConfiguration.new_paused()
self.playback_state = nil
self.num_times_to_step = nil
self.runner_being_stepped_index = nil
elseif config.mode == PlaybackConfiguration.mode.play then
self.configuration = config
self.playback_state = PlaybackController.playback_state.tick_1_prepare_to_attach_runner
self.num_times_to_step = config.num_times_to_step
self.runner_being_stepped_index = 1
end
self.configuration_after_runners_have_stepped = nil
end
function PlaybackController:reset()
local config = PlaybackConfiguration.new_reset()
if self:is_paused() then
self:_apply_configuration(config)
else
self.configuration_after_runners_have_stepped = config
end
end
-- player is the user that will be controlled to run the sequence.
-- setting num_times_to_step to nil denotes that it will step indefinitely.
function PlaybackController:play(player_entity, num_times_to_step)
fail_if_invalid(player_entity)
local config = PlaybackConfiguration.new_playing(player_entity, num_times_to_step)
if self:is_playing() == true then
if player_entity ~= self.configuration.player then
self.configuration_after_runners_have_stepped = config
else
self.configuration_after_runners_have_stepped = nil
if num_times_to_step == nil then
-- begin running forever
self.num_times_to_step = nil
elseif self.num_times_to_step == nil then
self.num_times_to_step = num_times_to_step
else
self.num_times_to_step = self.num_times_to_step + num_times_to_step
end
end
elseif self:is_paused() == true then
self:_apply_configuration(config)
else
self.configuration_after_runners_have_stepped = config
end
end
--[Comment]
-- Sets the controller to pause as soon as possible.
-- Returns if the controller is currently paused.
function PlaybackController:pause()
if self:is_paused() then
return true
end
self.configuration_after_runners_have_stepped = PlaybackConfiguration.new_paused()
return false
end
function PlaybackController:is_paused()
return self.configuration.mode == PlaybackConfiguration.mode.pause
end
function PlaybackController:is_playing()
return
self.playback_state == PlaybackController.playback_state.tick_1_prepare_to_attach_runner or
self.playback_state == PlaybackController.playback_state.tick_2_attach_runner or
self.playback_state == PlaybackController.playback_state.tick_3_running
end
function PlaybackController:is_player_controlled(player_index)
fail_if_missing(player_index)
if self.configuration == nil then
return false
end
local player = self.configuration.player
if is_valid(player) == false or player.index ~= player_index then
return false
end
return true
end
function PlaybackController:try_get_pause_control(player_index)
fail_if_missing(player_index)
if self.configuration == nil then
return nil
end
local player = self.configuration.player
if is_valid(player) == false then
return nil
end
if player.index ~= player_index then
return nil
end
local character = self.configuration.player_character_after_playback_completes
local control = nil
if character == nil then
control = defines.controllers.god
elseif is_valid(character) == false then
control = defines.controllers.ghost
-- What if playback begins when the player is already a ghost?
else
control = defines.controllers.character
end
return control
end
return PlaybackController |
local http = require "resty.http"
local cjson = require "cjson"
-- Verify the domain name and return its result.
return function(auto_ssl_instance, domain)
local httpc = http.new()
local url = auto_ssl_instance:get("verification_url")
if not url then
return true, nil
end
url = url .. "?d=" .. domain
httpc:set_timeout(10000)
local res, req_err = httpc:request_uri(url, {
ssl_verify = false,
method = "GET"
})
if not res then
return false, "Verification failed (" .. (url or "") .. "): " .. (req_err or "")
end
if res.status ~= 200 then
return false, "Verification returns bad HTTP status code (" .. (url or "") .. "): " .. (res.status or "")
end
local resp = res.body
if not resp or resp == "" then
return false, "Verification returns bad response body (" .. (url or "") .. "): " .. (resp or "")
end
local data = cjson.decode(resp)
if not data["valid"] then
return false, "Invalid domain: " .. domain
end
return true, nil
end
|
return {'lehmann'} |
-- Create a nested lua_State object
S = State()
S:dostring([[
flag = ...
print(flag)
]], true)
|
includeFile("custom_content/tangible/wearables/boots/wod_nightsister_boots_s01.lua")
|
print("\27[31m SDL crushes with DCHECK. Some tests are commented. After resolving uncomment tests!\27[0m")
---------------------------------------------------------------------------------------------
-- CRQ: APPLINK-25200: [GENIVI] VehicleInfo interface: SDL behavior in case HMI does not
-- respond to IsReady_request or respond with "available" = false
--
-- Requirement(s): APPLINK-25046: [RegisterAppInterface] SDL behavior in case <Interface>
-- is not supported by system
-- APPLINK-25224: [VehicleInfo Interface] Conditions for SDL to respond
-- 'UNSUPPORTED_RESOURCE, success:false' to mobile app
-- => only checked RPC: GetVehicleType
-- APPLINK-25305: [HMI_API] VehicleInfo.IsReady
---------------------------------------------------------------------------------------------
TestedInterface = "VehicleInfo"
Test = require('user_modules/ATF_Interface_IsReady_available_false_RAI_Template')
return Test |
-- premake5.lua
workspace "Minimal GLFW and GLEW" -- Name of sln file
location "project" -- Folder where to put it
configurations { "Debug", "Release" }
platforms { "Win32", "x64" }
--Set architecture
filter { "platforms:Win32" }
system "Windows"
architecture "x86"
filter { "platforms:x64" }
system "Windows"
architecture "x64"
filter { }
project "Minimal Example" -- Name of project
kind "ConsoleApp" -- Uses the console
language "C++"
location "project/Minimal Example" -- location of vcxproj file
targetdir "bin/%{cfg.buildcfg}/%{cfg.architecture}" -- .exe files is in bin/(debug or release)/(x86 or x64)/
--location of source files to include. Here we include All files ending with .h and .cpp
--in the folder Minimal Example even files in subfolders.
files { "./src/Minimal Example/**.h", "./src/Minimal Example/**.cpp" }
--Include directories
includedirs {
"./dependencies/glfw-3.2.1/include",
"./dependencies/glew-2.0.0/include"
}
--libraries and links
--links (the library files)
links {
"glew32",
"opengl32",
"glfw3"
}
--for 32 bit use these library paths
filter "architecture:x86"
libdirs {
"./dependencies/glfw-3.2.1/win32/lib",
"./dependencies/glew-2.0.0/win32/lib"
}
filter { }
--for x64 use these
filter "architecture:x64"
libdirs {
"./dependencies/glfw-3.2.1/x64/lib",
"./dependencies/glew-2.0.0/x64/lib"
}
--Debug and Release configurations
filter "configurations:Debug"
defines { "DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "On"
filter { }
|
describe("GlobalValueKeyValueStore", function()
local eaw_env
local require_utilities
before_each(function()
eaw_env = require("spec.eaw_env")
eaw_env.setup_environment()
require_utilities = require("spec.require_utilities")
require_utilities.replace_require()
require("crossplot.GlobalValueKeyValueStore")
end)
after_each(function()
eaw_env.teardown_environment()
require_utilities.reset_require()
end)
describe("When storing simple value", function()
it("should store value in GlobalValue", function()
local kv_store = GlobalValueKeyValueStore()
local global_value_spy = spy.on(GlobalValue, "Set")
kv_store:store("key", "value")
assert.spy(global_value_spy).was.called()
end)
it("should serialize value before storing it", function()
local kv_store = GlobalValueKeyValueStore()
kv_store:store("key", "value")
local actual = loadstring(GlobalValue.Get("key"))()
assert.are.equal("value", actual)
end)
describe("then retrieving it", function()
it("should return stored value", function()
local kv_store = GlobalValueKeyValueStore()
kv_store:store("key", "value")
assert.are.equal("value", kv_store:get("key"))
end)
end)
end)
describe("When storing table value", function()
it("should serialize and store value in GlobalValue", function()
local kv_store = GlobalValueKeyValueStore()
local value = {value = 5, sub_table = {1, 2}}
kv_store:store("key", value)
local actual = loadstring(GlobalValue.Get("key"))()
assert.are.same(value, actual)
end)
describe("then retrieving it", function()
it("should return stored value", function()
local kv_store = GlobalValueKeyValueStore()
local value = {value = 5, sub_table = {1, 2}}
kv_store:store("key", value)
assert.are.same(value, kv_store:get("key"))
end)
end)
end)
describe("When freeing value", function()
it("should set value to empty string", function()
GlobalValue.Set("key", "value")
local kv_store = GlobalValueKeyValueStore()
kv_store:free("key")
assert.are.equal("", GlobalValue.Get("key"))
end)
end)
describe("When getting non-existing key", function()
it("should return nil", function()
local kv_store = GlobalValueKeyValueStore()
local actual = kv_store:get("NON_EXISTING")
assert.is_nil(actual)
end)
end)
end) |
local serialize = require "serialize"
local factory = {}
function factory.new(host)
return setmetatable({
host = host,
grid = {tiles={}, width=20, height=20},
}, {__index=factory})
end
function factory:setTile(x, y, tile)
if not self.grid.tiles[x] then
self.grid.tiles[x] = {}
end
self.grid.tiles[x][y] = tile
self.host:broadcast(serialize.serialize{type="setTile", x=x, y=y, tile=tile})
end
function factory:getTile(x, y)
if not self.grid.tiles[x] then
return nil
end
return self.grid.tiles[x][y]
end
function factory:send(peer)
peer:send(serialize.serialize{type="factoryGrid", grid=self.grid})
end
return factory
|
solution "Google Code Jam 2013 Round 1A"
configurations { "Debug", "Release" }
startproject "q-unittest"
location "build"
project "techdevguide"
kind "StaticLib"
language "C++"
targetdir "build/bin/%{cfg.buildcfg}"
files { "src/**.h",
"src/**.cpp" }
includedirs { "src" }
filter "configurations:Debug"
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
configuration "gmake"
buildoptions {
"-std=c++14"
}
project "GoogleTest"
kind "StaticLib"
language "C++"
targetdir "build/bin/%{cfg.buildcfg}"
files { "../3rd/gtest-1.7.0/src/gtest_main.cc",
"../3rd/gtest-1.7.0/src/gtest-all.cc" }
libdirs { "../3rd/" }
includedirs {"../3rd/gtest-1.7.0", "../3rd/gtest-1.7.0/include"}
filter "configurations:Debug"
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
configuration "gmake"
buildoptions {
"-std=c++14"
}
project "techdevguide-unittest"
kind "ConsoleApp"
language "C++"
targetdir "build/bin/%{cfg.buildcfg}"
files { "test/**.h",
"test/**.cpp" }
links {"techdevguide", "GoogleTest"}
libdirs { "../3rd/" }
includedirs {"../3rd/gtest-1.7.0", "../3rd/gtest-1.7.0/include", "src" }
filter "configurations:Debug"
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
configuration "gmake"
buildoptions {
"-std=c++14"
}
linkoptions {
"-pthread"
}
--[[
project "GoogleBenchmark"
kind "StaticLib"
language "C++"
targetdir "build/bin/%{cfg.buildcfg}"
files { "../3rd/google-benchmark/src/*" }
libdirs { "../3rd/" }
includedirs {"../3rd/google-benchmark", "../3rd/google-benchmark/include"}
filter "configurations:Debug"
defines {"DEBUG", "HAVE_STD_REGEX" }
symbols "On"
filter "configurations:Release"
defines {"NDEBUG", "HAVE_STD_REGEX" }
optimize "On"
configuration "gmake"
buildoptions {
"-std=c++14"
}
project "techdevguide-benchmark"
kind "ConsoleApp"
language "C++"
targetdir "build/bin/%{cfg.buildcfg}"
files { "benchmark/**.cpp" }
links {"techdevguide", "GoogleBenchmark"}
libdirs { "../3rd/" }
includedirs {"../3rd/google-benchmark", "../3rd/google-benchmark/include", "src" }
filter "configurations:Debug"
defines {"DEBUG"}
symbols "On"
filter "configurations:Release"
defines {"NDEBUG"}
optimize "On"
configuration "gmake"
buildoptions {
"-std=c++14"
}
linkoptions {
"-pthread"
}
]]
|
gl.setup(1680, 945)
json = require("json")
font = resource.load_font("light.ttf")
font2 = resource.load_font("light.ttf")
background = resource.load_image("whitepixel.png")
maxCharWidth = WIDTH/0.6
color = { r = 0.95, g = 0.95, b = 0.0 }
charSize = 82
function alignRight(num)
-- 0 1 2 3 4 5 6 7 8 9
local width = { 5, 30, 7, 5, 7, 15, 8, 5, 5, 5 }
local num1 = num % 10;
local num2 = math.floor(num / 10 % 10);
if num2 >= 1 then
return width[num1 + 1] + width[num2 + 1]
else
return width[num1 + 1] + 44
end
end
function node.render()
local i = 0
local station_json = json.decode(text)
background:draw(0, 0, WIDTH, HEIGHT/10)
background:draw(0, HEIGHT - HEIGHT/10, WIDTH, HEIGHT)
for k, stations in pairs(station_json) do
local station = stations[1]
width = math.floor(maxCharWidth/72/2 + string.len(station)/2)
font2:write(15, HEIGHT - charSize, station:gsub(" %(Berlin%)", ""), 72, 0,0,0, 1)
font2:write(15, 30, "Line Destination Departure", 64, 0,0,0,1)
i = i + 124
j = 0
for k, departures in pairs(stations[2]) do
local remaining = math.floor(departures['remaining']/60)
if j < 9 then
j = j + 1
local timeString = string.format('%2d min', remaining)
font:write(WIDTH-440 + alignRight(remaining), i,
string.format('%14s', timeString),
charSize, color.r, color.g, color.b, 1)
font:write(0, i,
string.format(' %-5s', departures['line']:gsub("Bus ", "")),
charSize, color.r, color.g, color.b, 1)
font:write(250, i,
string.format(' %-32s', departures['end']:gsub("-", '—'):gsub('%(Berlin%)', '')),
charSize, color.r, color.g, color.b, 1)
i = i + charSize + 10
end
end
end
end
util.file_watch("ERP", function(content)
text = content
end)
|
--[[
_
( )
_| | __ _ __ ___ ___ _ _
/'_` | /'__`\( '__)/' _ ` _ `\ /'_` )
( (_| |( ___/| | | ( ) ( ) |( (_| |
`\__,_)`\____)(_) (_) (_) (_)`\__,_)
DColorCube
--]]
local PANEL = {}
AccessorFunc( PANEL, "m_Hue", "Hue" )
AccessorFunc( PANEL, "m_BaseRGB", "BaseRGB" )
AccessorFunc( PANEL, "m_OutRGB", "RGB" )
--[[---------------------------------------------------------
Name: Init
-----------------------------------------------------------]]
function PANEL:Init()
self:SetImage( "vgui/minixhair" )
self.Knob:NoClipping( false )
self.BGSaturation = vgui.Create( "DImage", self )
self.BGSaturation:SetImage( "vgui/gradient-r" )
self.BGValue = vgui.Create( "DImage", self )
self.BGValue:SetImage( "vgui/gradient-d" )
self.BGValue:SetImageColor( Color( 0, 0, 0, 255 ) )
self:SetBaseRGB( Color( 255, 0, 0 ) )
self:SetRGB( Color( 255, 0, 0 ) )
self:SetColor( Color( 255, 0, 0 ) )
self:SetLockX( nil )
self:SetLockY( nil )
end
--[[---------------------------------------------------------
Name: PerformLayout
-----------------------------------------------------------]]
function PANEL:PerformLayout()
DSlider.PerformLayout( self )
self.BGSaturation:StretchToParent( 0,0,0,0 )
self.BGSaturation:SetZPos( -9 )
self.BGValue:StretchToParent( 0,0,0,0 )
self.BGValue:SetZPos( -8 )
end
--[[---------------------------------------------------------
Name: Paint
-----------------------------------------------------------]]
function PANEL:Paint()
surface.SetDrawColor( self.m_BaseRGB.r, self.m_BaseRGB.g, self.m_BaseRGB.b, 255 )
self:DrawFilledRect()
end
--[[---------------------------------------------------------
Name: PaintOver
-----------------------------------------------------------]]
function PANEL:PaintOver()
surface.SetDrawColor( 0, 0, 0, 250 )
self:DrawOutlinedRect()
end
--[[---------------------------------------------------------
Name: TranslateValues
-----------------------------------------------------------]]
function PANEL:TranslateValues( x, y )
self:UpdateColor( x, y )
self:OnUserChanged( self.m_OutRGB )
return x, y
end
--[[---------------------------------------------------------
Name: UpdateColor
-----------------------------------------------------------]]
function PANEL:UpdateColor( x, y )
x = x or self:GetSlideX()
y = y or self:GetSlideY()
local value = 1 - y
local saturation = 1 - x
local h = ColorToHSV( self.m_BaseRGB )
local color = HSVToColor( h, saturation, value )
self:SetRGB( color )
end
--[[---------------------------------------------------------
Name: OnUserChanged
-----------------------------------------------------------]]
function PANEL:OnUserChanged()
-- Override me
end
--[[---------------------------------------------------------
Name: SetColor
-----------------------------------------------------------]]
function PANEL:SetColor( color )
local h, s, v = ColorToHSV( color )
self:SetBaseRGB( HSVToColor( h, 1, 1 ) )
self:SetSlideY( 1 - v )
self:SetSlideX( 1 - s )
self:UpdateColor()
end
--[[---------------------------------------------------------
Name: SetBaseRGB
-----------------------------------------------------------]]
function PANEL:SetBaseRGB( color )
self.m_BaseRGB = color
self:UpdateColor()
end
derma.DefineControl( "DColorCube", "", PANEL, "DSlider" ) |
local remoteImagePlaceHolder
remoteImageQueue = {}
remoteImageDefaultImages = {
unloadedTex = DGSBuiltInTex.transParent_1x1,
loadingTex = DGSBuiltInTex.transParent_1x1,
failedTex = DGSBuiltInTex.transParent_1x1,
}
--[[
loadState:
0 = unloaded
1 = loading
2 = loaded
3 = failed
]]
function dgsCreateRemoteImage(website)
local remoteImage = dxCreateShader(remoteImagePlaceHolder)
dgsSetData(remoteImage,"asPlugin","dgs-dxremoteimage")
addEventHandler("onClientElementDestroy",remoteImage,function()
if isElement(dgsElementData[source].textureRef) then
destroyElement(dgsElementData[source].textureRef)
end
end,false)
dgsSetData(remoteImage,"defaultImages",table.shallowCopy(remoteImageDefaultImages))
dgsSetData(remoteImage,"loadState",0) --unloaded
dgsSetData(remoteImage,"textureRef",false)
dxSetShaderValue(remoteImage,"textureRef",dgsElementData[remoteImage].defaultImages.unloadedTex) --Change image when state changes
if website then
dgsRemoteImageRequest(remoteImage,website)
end
triggerEvent("onDgsPluginCreate",remoteImage,sourceResource)
return remoteImage
end
function dgsRemoteImageRequest(remoteImage,website,forceReload)
if not(dgsGetPluginType(remoteImage) == "dgs-dxremoteimage") then error(dgsGenAsrt(remoteImage,"dgsRemoteImageRequest",1,"plugin dgs-dxremoteimage")) end
if not(type(website) == "string") then error(dgsGenAsrt(remoteImage,"dgsRemoteImageRequest",2,"string")) end
local loadState = dgsElementData[remoteImage].loadState
if loadState == 1 then --make sure it is not loading
if not forceReload then
return false
end
dgsRemoteImageAbort(remoteImage) --if forceReload then aborted automatically
end
dgsSetData(remoteImage,"loadState",1) --loading
dgsSetData(remoteImage,"url",{website})
local index = math.seekEmpty(remoteImageQueue)
remoteImageQueue[index] = remoteImage
dgsSetData(remoteImage,"queueIndex",index)
return triggerServerEvent("DGSI_RequestRemoteImage",resourceRoot,website,index)
end
function dgsRemoteImageAbort(remoteImage)
if not(dgsGetPluginType(remoteImage) == "dgs-dxremoteimage") then error(dgsGenAsrt(remoteImage,"dgsRemoteImageAbort",1,"plugin dgs-dxremoteimage")) end
local queueIndex = dgsElementData[remoteImage].queueIndex
remoteImageQueue[queueIndex] = "aborted"
end
function dgsRemoteImageGetTexture(remoteImage)
return dgsElementData[remoteImage].textureRef
end
function dgsGetRemoteImageLoadState(remoteImage)
if not(dgsGetPluginType(remoteImage) == "dgs-dxremoteimage") then error(dgsGenAsrt(remoteImage,"dgsGetRemoteImageLoadState",1,"plugin dgs-dxremoteimage")) end
return dgsElementData[remoteImage].loadState
end
addEventHandler("DGSI_ReceiveRemoteImage",resourceRoot,function(data,response,index)
local remoteImage = remoteImageQueue[index]
remoteImageQueue[index] = nil
if isElement(remoteImage) then
if response.success then
local texture = dxCreateTexture(data)
dgsSetData(texture,"DGSContainer",remoteImage)
addEventHandler("onClientElementDestroy",texture,function()
local remoteImage = dgsElementData[texture].DGSContainer
if isElement(remoteImage) then
dgsSetData(remoteImage,"textureRef",false)
dgsSetData(remoteImage,"loadState",0) --Unload
if isElement(dgsElementData[remoteImage].defaultImages.unloadedTex) then
dxSetShaderValue(remoteImage,"textureRef",dgsElementData[remoteImage].defaultImages.unloadedTex) --Change image when state changes
end
end
end,false)
dgsSetData(remoteImage,"loadState",2) --Successful
dgsSetData(remoteImage,"textureRef",texture)
dxSetShaderValue(remoteImage,"textureRef",texture)
else
dgsSetData(remoteImage,"loadState",0) --Failed
if isElement(dgsElementData[remoteImage].defaultImages.unloadedTex) then
dxSetShaderValue(remoteImage,"textureRef",dgsElementData[remoteImage].defaultImages.unloadedTex) --Change image when state changes
end
end
triggerEvent("onDgsRemoteImageLoad",remoteImage,response)
end
end)
--------------Shader
remoteImagePlaceHolder = [[
texture textureRef;
technique remoteImage{
Pass P0{
Texture[0] = textureRef;
}
}]] |
fx_version 'adamant'
games { 'gta5' }
client_scripts {
"@_core/libs/utils.lua",
'client.lua',
}
server_scripts {
"@_core/libs/utils.lua",
'server.lua'
} |
return {'cdaer','cda','cdaers'} |
package.path = "?.lua;test/lua/errors/?.lua"
require 'args'
local tostring = tostring
_G.tostring = function(x)
local s = tostring(x)
return type(x)=='number' and #s>4 and (s:sub(1,5)..'...') or s
end
-- arg type tests for math library functions
local somenumber = {1,0.75,'-1','-0.25'}
local somepositive = {1,0.75,'2', '2.5'}
local notanumber = {nil,astring,aboolean,afunction,atable,athread}
local nonnumber = {astring,aboolean,afunction,atable}
local singleargfunctions = {
'abs', 'acos', 'asin', 'atan', 'cos', 'cosh', 'deg', 'exp', 'floor',
'rad', 'randomseed', 'sin', 'sinh', 'tan', 'tanh', 'frexp',
}
local singleargposdomain = {
'log', 'sqrt', 'ceil',
}
local twoargfunctions = {
'atan2',
}
local twoargsposdomain = {
'pow', 'fmod',
}
-- single argument tests
for i,v in ipairs(singleargfunctions) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somenumber})
checkallerrors(funcname,{notanumber},'bad argument')
end
-- single argument, positive domain tests
for i,v in ipairs(singleargposdomain) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somepositive})
checkallerrors(funcname,{notanumber},'bad argument')
end
-- two-argument tests
for i,v in ipairs(twoargfunctions) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somenumber,somenumber})
checkallerrors(funcname,{},'bad argument')
checkallerrors(funcname,{notanumber},'bad argument')
checkallerrors(funcname,{notanumber,somenumber},'bad argument')
checkallerrors(funcname,{somenumber},'bad argument')
checkallerrors(funcname,{somenumber,notanumber},'bad argument')
end
-- two-argument, positive domain tests
for i,v in ipairs(twoargsposdomain) do
local funcname = 'math.'..v
banner(funcname)
checkallpass(funcname,{somepositive,somenumber})
checkallerrors(funcname,{},'bad argument')
checkallerrors(funcname,{notanumber},'bad argument')
checkallerrors(funcname,{notanumber,somenumber},'bad argument')
checkallerrors(funcname,{somenumber},'bad argument')
checkallerrors(funcname,{somenumber,notanumber},'bad argument')
end
-- math.max
banner('math.max')
checkallpass('math.max',{somenumber})
checkallpass('math.max',{somenumber,somenumber})
checkallerrors('math.max',{},'bad argument')
checkallerrors('math.max',{nonnumber},'bad argument')
checkallerrors('math.max',{somenumber,nonnumber},'bad argument')
-- math.min
banner('math.min')
checkallpass('math.min',{somenumber})
checkallpass('math.min',{somenumber,somenumber})
checkallerrors('math.min',{},'bad argument')
checkallerrors('math.min',{nonnumber},'bad argument')
checkallerrors('math.min',{somenumber,nonnumber},'bad argument')
-- math.random
local somem = {3,4.5,'6.7'}
local somen = {8,9.10,'12.34'}
local notamn = {astring,aboolean,atable,afunction}
banner('math.random')
checkallpass('math.random',{},true)
checkallpass('math.random',{somem},true)
checkallpass('math.random',{somem,somen},true)
checkallpass('math.random',{{-4,-5.6,'-7','-8.9'},{-1,100,23.45,'-1.23'}},true)
checkallerrors('math.random',{{-4,-5.6,'-7','-8.9'}},'interval is empty')
checkallerrors('math.random',{somen,somem},'interval is empty')
checkallerrors('math.random',{notamn,somen},'bad argument')
checkallerrors('math.random',{somem,notamn},'bad argument')
-- math.ldexp
local somee = {-3,0,3,9.10,'12.34'}
local notae = {nil,astring,aboolean,atable,afunction}
banner('math.ldexp')
checkallpass('math.ldexp',{somenumber,somee})
checkallerrors('math.ldexp',{},'bad argument')
checkallerrors('math.ldexp',{notanumber},'bad argument')
checkallerrors('math.ldexp',{notanumber,somee},'bad argument')
checkallerrors('math.ldexp',{somenumber},'bad argument')
checkallerrors('math.ldexp',{somenumber,notae},'bad argument') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.