content stringlengths 5 1.05M |
|---|
--!A cross-platform build utility based on Lua
--
-- 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.
--
-- Copyright (C) 2015-present, TBOOX Open Source Group.
--
-- @author ruki
-- @file proxy.lua
--
-- imports
import("core.base.global")
-- get proxy hosts
function _proxy_hosts()
local proxy_hosts = _g._PROXY_HOSTS
if proxy_hosts == nil then
proxy_hosts = global.get("proxy_hosts")
if proxy_hosts then
proxy_hosts = proxy_hosts:split(',', {plain = true})
end
_g._PROXY_HOSTS = proxy_hosts or false
end
return proxy_hosts or nil
end
-- get proxy pac file
--
-- pac.lua
--
-- @code
-- function mirror(url)
-- return url:gsub("github.com", "hub.fastgit.org")
-- end
-- function main(url, host)
-- if host:find("bintray.com") then
-- return true
-- end
-- end
-- @endcode
--
function _proxy_pac()
local proxy_pac = _g._PROXY_PAC
if proxy_pac == nil then
local pac = global.get("proxy_pac")
local pacfile
if pac and pac:endswith(".lua") then
if os.isfile(pac) then
pacfile = pac
end
if not pacfile and not path.is_absolute(pac) then
pacfile = path.join(global.directory(), pac)
if not os.isfile(pacfile) and os.isfile(path.join(os.programdir(), "scripts", "pac", pac)) then
pacfile = path.join(os.programdir(), "scripts", "pac", pac)
end
end
end
if pacfile and os.isfile(pacfile) then
proxy_pac = import(path.basename(pacfile), {rootdir = path.directory(pacfile), try = true, anonymous = true})
end
_g._PROXY_PAC = proxy_pac or false
end
return proxy_pac or nil
end
-- convert host pattern to a lua pattern
function _host_pattern(pattern)
pattern = pattern:gsub("([%+%.%-%^%$%(%)%%])", "%%%1")
pattern = pattern:gsub("%*", "\001")
pattern = pattern:gsub("\001", ".*")
return pattern
end
-- has main entry? it will be callable directly
function _is_callable(func)
if type(func) == "function" then
return true
elseif type(func) == "table" then
local meta = debug.getmetatable(func)
if meta and meta.__call then
return true
end
end
end
-- get proxy mirror url
function mirror(url)
local proxy_pac = _proxy_pac()
if proxy_pac and proxy_pac.mirror then
return proxy_pac.mirror(url)
end
return url
end
-- get proxy configuration from the given url, [protocol://]host[:port]
--
-- @see https://github.com/xmake-io/xmake/issues/854
--
function config(url)
-- enable proxy for the given url and configuration pattern
if url then
-- filter proxy host from the given hosts pattern
local host = url:match("://(.-)/") or url:match("@(.-):")
local proxy_hosts = _proxy_hosts()
if host and proxy_hosts then
host = host:lower()
for _, proxy_host in ipairs(proxy_hosts) do
proxy_host = proxy_host:lower()
if host == proxy_hosts or host:match(_host_pattern(proxy_host)) then
return global.get("proxy")
end
end
end
-- filter proxy host from the pac file
local proxy_pac = _proxy_pac()
if proxy_pac and host and _is_callable(proxy_pac) and proxy_pac(url, host) then
return global.get("proxy")
end
-- use global proxy
if not proxy_pac and not proxy_hosts then
return global.get("proxy")
end
return
end
-- enable global proxy
return global.get("proxy")
end
|
local file = require('pl.file')
local stringx = require('pl.stringx')
function paraseBabiTask( data_path, dict, include_question )
local story = torch.zeros(1000, 1000, 20)
local story_ind = 0
local sentence_ind = 0
local max_words = 0
local max_senteces = 0
local questions = torch.zeros(1000,10)
local question_ind = 0
local is_question = false
local qstory = torch.zeros(1000,20)
local map = {}
for fi=1,#data_path do
local fd = file.read(data_path[fi])
local lines = stringx.splitlines(fd)
for line_ind=1,#lines do
local line = lines[line_ind]
local words = stringx.split(line)
-- words = words[1]
if words[1] == '1' then
story_ind = story_ind + 1
sentence_ind = 0
map = {}
end
is_question = false
if stringx.count(line,'?') == 0 then
is_question = false
sentence_ind = sentence_ind + 1
else
is_question = true
question_ind = question_ind + 1
questions[question_ind][1] = story_ind
questions[question_ind][2] = sentence_ind
if include_question then
sentence_ind = sentence_ind + 1
end
end
-- map[#map] = sentence_ind
table.insert(map,sentence_ind)
for k=2,#words do
w = words[k]
w = string.lower(w)
if w:sub(-1,-1) == '.' or w:sub(-1,-1) == '?' then
w = w:sub(1,-2)
end
if not dict[w] then
dict[w] = #dict + 1
end
max_words = math.max(max_words, k-1)
if is_question == false then
story[story_ind][sentence_ind][k-1] = dict[w]
else
qstory[question_ind][k-1] = dict[w]
if include_question == true then
story[story_ind][sentence_ind][k-1] = dict[w]
end
if words[k]:sub(-1,-1) == '?' then
answer = words[k+1]
answer = string.lower(answer)
if not dict[answer] then
dict[answer] = #dict + 1
end
questions[question_ind][3] = dict[answer]
for h = k+2 ,#words do
questions[question_ind][2+h-k] = map[tonumber(words[h])]
end
questions[question_ind][10] = line_ind
break
end
end
end
max_senteces = math.max(max_senteces, sentence_ind)
end
end
story = story:sub(1,story_ind,1,max_senteces,1,max_words)
questions = questions[{{1,question_ind},{}}]
qstory = qstory:sub(1,question_ind,1,max_words)
story[torch.eq(story,0)] = dict['nil']
qstory[torch.eq(qstory,0)] = dict['nil']
return story, questions, qstory, dict
end |
-- Daneel.lua
-- Contains Daneel's core functionalities.
--
-- Last modified for v1.5.0
-- Copyright © 2013-2014 Florent POUJOL, published under the MIT license.
Daneel = {}
Daneel.modules = { moduleNames = {} }
setmetatable( Daneel.modules, {
__newindex = function( _, moduleName, moduleObject ) -- "_" argument is Daneel.modules object
table.insert( Daneel.modules.moduleNames, moduleName )
rawset( Daneel.modules, moduleName, moduleObject )
end
} )
----------------------------------------------------------------------------------
-- Some Lua functions are overridden here with some Daneel-specific stuffs
function string.split( s, delimiter, delimiterIsPattern )
local chunks = {}
if delimiterIsPattern then
local delimiterStartIndex, delimiterEndIndex = s:find( delimiter )
if delimiterStartIndex ~= nil then
local pattern = delimiter
delimiter = s:sub( delimiterStartIndex, delimiterEndIndex )
if string.startswith( s, delimiter ) then
s = s:sub( #delimiter+1, #s )
end
if not s:endswith( delimiter ) then
s = s .. delimiter
end
if CS.IsWebPlayer then
-- CS Webplayer specific part :
-- in the webplayer, "(.-)"..delimiter is translated into "(.*)"..delimiter which seems to create an infinite loop
-- "(.+)"..delimiter does not work either in the webplayer
for match in s:gmatch( "([^"..pattern.."]+)"..pattern ) do
table.insert( chunks, match )
end
else
for match in s:gmatch( "(.-)"..pattern ) do
table.insert( chunks, match )
end
end
end
else -- plain text delimiter
if s:find( delimiter, 1, true ) ~= nil then
if string.startswith( s, delimiter ) then
s = s:sub( #delimiter+1, #s )
end
if not s:endswith( delimiter ) then
s = s .. delimiter
end
local chunk = ""
local ts = string.totable( s )
local i = 1
while i <= #ts do
local char = ts[i]
if char == delimiter or s:sub( i, i-1 + #delimiter ) == delimiter then
table.insert( chunks, chunk )
chunk = ""
i = i + #delimiter
else
chunk = chunk..char
i = i + 1
end
end
if #chunk > 0 then
table.insert( chunks, chunk )
end
end
end
if #chunks == 0 then
chunks = { s }
end
return chunks
end
function table.print(t)
if t == nil then
print("table.print( t ) : Provided table is nil.")
return
end
local tableString = tostring(t)
local rawTableString = Daneel.Debug.ToRawString(t)
if tableString ~= rawTableString then
tableString = tableString.." / "..rawTableString
end
print("~~~~~ table.print("..tableString..") ~~~~~ Start ~~~~~")
local func = pairs
if table.getlength(t) == 0 then
print("Table is empty.")
elseif table.isarray( t ) then
func = ipairs -- just to be sure that the entries are printed in order
end
for key, value in func(t) do
print(key, value)
end
print("~~~~~ table.print("..tableString..") ~~~~~ End ~~~~~")
end
function table.getlength( t, keyType )
local length = 0
if keyType ~= nil then
keyType = keyType:lower()
end
for key, value in pairs( t ) do
if
keyType == nil or
type( key ) == keyType or
Daneel.Debug.GetType( key ):lower() == keyType
then
length = length + 1
end
end
return length
end
----------------------------------------------------------------------------------
-- Utilities
Daneel.Utilities = {}
-- Deprecated since v1.5.0
Daneel.Utilities.CaseProof = string.fixcase
--- Replace placeholders in the provided string with their corresponding provided replacements.
-- The placeholders are any piece of string prefixed by a semicolon.
-- @param string (string) The string.
-- @param replacements (table) The placeholders and their replacements ( { placeholder = "replacement", ... } ).
-- @return (string) The string.
function Daneel.Utilities.ReplaceInString( string, replacements )
for placeholder, replacement in pairs( replacements ) do
string = string:gsub( ":"..placeholder, replacement )
end
return string
end
--- Allow to call getters and setters as if they were variable on the instance of the provided object.
-- The instances are tables that have the provided object as metatable.
-- Optionally allow to search in a ancestry of objects.
-- @param Object (mixed) The object.
-- @param ancestors (table) [optional] A table with one or several objects the Object "inherits" from.
function Daneel.Utilities.AllowDynamicGettersAndSetters( Object, ancestors )
function Object.__index( instance, key )
local ucKey = key
if type( key ) == "string" then
ucKey = string.ucfirst( key )
end
if key == ucKey then
-- first letter was already uppercase or key is not if type string
if Object[ key ] ~= nil then
return Object[ key ]
end
if ancestors ~= nil then
for i, Ancestor in ipairs( ancestors ) do
if Ancestor[ key ] ~= nil then
return Ancestor[ key ]
end
end
end
else
-- first letter lowercase, search for the corresponding getter
local funcName = "Get"..ucKey
if Object[ funcName ] ~= nil then
return Object[ funcName ]( instance )
elseif Object[ key ] ~= nil then
return Object[ key ]
end
if ancestors ~= nil then
for i, Ancestor in ipairs( ancestors ) do
if Ancestor[ funcName ] ~= nil then
return Ancestor[ funcName ]( instance )
elseif Ancestor[ key ] ~= nil then
return Ancestor[ key ]
end
end
end
end
return nil
end
function Object.__newindex( instance, key, value )
local ucKey = key
if type( key ) == "string" then
ucKey = string.ucfirst( key )
end
if key ~= ucKey then -- first letter lowercase
local funcName = "Set"..ucKey
if Object[ funcName ] ~= nil then
return Object[ funcName ]( instance, value )
end
end
-- first letter was already uppercase or key not of type string
return rawset( instance, key, value )
end
end
-- Deprecated since v1.5.0
Daneel.Utilities.ToNumber = tonumber2
local buttonExists = {} -- Button names are keys, existence (false or true) is value
--- Tell whether the provided button name exists amongst the Game Controls, or not.
-- If the button name does not exists, it will print an error in the Runtime Report but it won't kill the script that called the function.
-- CS.Input.ButtonExists is an alias of Daneel.Utilities.ButtonExists.
-- @param buttonName (string) The button name.
-- @return (boolean) True if the button name exists, false otherwise.
function Daneel.Utilities.ButtonExists( buttonName )
if buttonExists[ buttonName ] == nil then
buttonExists[ buttonName ] = Daneel.Debug.Try( function()
CS.Input.WasButtonJustPressed( buttonName )
end )
end
return buttonExists[ buttonName ]
end
Daneel.Utilities.id = 0
--- Returns an integer greater than 0 and incremented by 1 from the last time the function was called.
-- If an object is provided, returns the object's id (if no id is found, it is set).
-- @param object (table) [optional] An object.
-- @return (number) The id.
function Daneel.Utilities.GetId( object )
if object ~= nil and type( object ) == "table" then
local id = rawget( object, "id" )
if id ~= nil then
return id
end
id = Daneel.Utilities.GetId()
if object.inner ~= nil and not CS.IsWebPlayer then -- in the webplayer, tostring(object.inner) will just be table, so id will be nil
-- object.inner :
-- "CraftStudioRuntime.InGame.GameObject: 4620049" (of type userdata)
-- "CraftStudioCommon.ProjectData.[AssetType]: [some ID]"
id = tonumber( tostring( object.inner ):match( "%d+" ) )
end
if id == nil then
id = "[no id]"
end
rawset( object, "id", id )
return id
else
Daneel.Utilities.id = Daneel.Utilities.id + 1
return Daneel.Utilities.id
end
end
-- for backward compatibility, Cache object is deprecated since v1.5.0
Daneel.Cache = {
GetId = Daneel.Utilities.GetId
}
----------------------------------------------------------------------------------
-- Debug
Daneel.Debug = {}
-- error reporting info
local s = "string"
local b = "boolean"
local n = "number"
local t = "table"
local f = "function"
local u = "userdata"
local v3 = "Vector3"
local _s = { "s", s }
local _t = { "t", t }
Daneel.Debug.functionArgumentsInfo = {
["math.isinteger"] = { { "number" } },
["math.lerp"] = {
{ "a", n },
{ "b", n },
{ "factor", n },
{ "easing", s, isOptional = true }
},
["math.warpangle"] = { { "angle", n } },
["math.round"] = { { "value", n }, { "decimal", n, isOptional = true } },
["math.truncate"] = { { "value", n }, { "decimal", n, isOptional = true } },
["tonumber2"] = { { "data" } },
["math.clamp"] = { { "value", n }, { "min", n }, { "max", n } },
["string.totable"] = { _s },
["string.ucfirst"] = { _s },
["string.lcfirst"] = { _s },
["string.trimstart"] = { _s },
["string.trimend"] = { _s },
["string.trim"] = { _s },
["string.endswith"] = { _s, { "chunk", s } },
["string.startswith"] = { _s, { "chunk", s } },
["string.split"] = { _s,
{ "delimiter", s },
{ "delimiterIsPattern", b, isOptional = true },
},
["string.reverse"] = { _s },
["string.fixcase"] = { _s, { "set", { s, t } } },
["table.print"] = {}, -- just for the stacktrace
["table.merge"] = {},
["table.mergein"] = {},
["table.getkeys"] = { _t },
["table.getvalues"] = { _t },
["table.reverse"] = { _t },
["table.reindex"] = { _t },
["table.getvalue"] = { _t, { "keys", s } },
["table.setvalue"] = { _t, { "keys", s } },
["table.getkey"] = { _t, { "value" } },
["table.copy"] = { _t, { "recursive", b, isOptional = true } },
["table.containsvalue"] = { _t, { "value" }, { "ignoreCase", b, isOptional = true } },
["table.isarray"] = { _t, { "strict", b, isOptional = true } },
["table.shift"] = { _t, { "returnKey", b, isOptional = true } },
["table.getlength"] = { _t, { "keyType", s, isOptional = true } },
["table.havesamecontent"] = { { "table1", t }, { "table2", t } },
["table.combine"] = { _t,
{ "values", "table" },
{ "returnFalseIfNotSameLength", b, isOptional = true }
},
["table.removevalue"] = { _t,
{ "value" },
{ "maxRemoveCount", n, isOptional = true }
},
["table.sortby"] = { _t,
{ "property", s },
{ "orderBy", s, isOptional = true },
},
}
local _transform = { "transform", "Transform" }
table.mergein( Daneel.Debug.functionArgumentsInfo, {
["Daneel.Utilities.ReplaceInString"] = { { "string", s }, { "replacements", t } },
["Daneel.Utilities.ButtonExists"] = { { "buttonName", s } },
["Transform.SetPosition"] = { _transform, { "position", v3 } },
["Transform.SetLocalPosition"] = { _transform, { "position", v3 } },
["Transform.SetEulerAngles"] = { _transform, { "angles", v3 } },
["Transform.SetLocalEulerAngles"] = { _transform, { "angles", v3 } },
["Transform.RotateEulerAngles"] = { _transform, { "angles", v3 } },
["Transform.RotateLocalEulerAngles"] = { _transform, { "angles", v3 } },
["Transform.Move"] = { _transform, { "offset", v3 } },
["Transform.MoveLocal"] = { _transform, { "offset", v3 } },
["Transform.MoveOriented"] = { _transform, { "offset", v3 } },
["Transform.LookAt"] = { _transform, { "target", v3 } },
["Transform.SetOrientation"] = { _transform, { "orientation", "Quaternion" } },
["Transform.SetLocalOrientation"] = { _transform, { "orientation", "Quaternion" } },
["Transform.Rotate"] = { _transform, { "orientation", "Quaternion" } },
["Transform.RotateLocal"] = { _transform, { "orientation", "Quaternion" } },
} )
--- Check the provided argument's type against the provided type(s) and display error if they don't match.
-- @param argument (mixed) The argument to check.
-- @param argumentName (string) The argument name.
-- @param expectedArgumentTypes (string or table) The expected argument type(s).
-- @param p_errorHead [optional] (string) The beginning of the error message.
-- @return (mixed) The argument's type.
function Daneel.Debug.CheckArgType( argument, argumentName, expectedArgumentTypes, p_errorHead )
if type( argument ) == "table" and getmetatable( argument ) == GameObject and argument.inner == nil then
error( p_errorHead .. "Provided argument '" .. argumentName .. "' is a destroyed game object '" .. tostring(argument) )
-- should do that for destroyed components too
end
if not Daneel.Config.debug.enableDebug then
return Daneel.Debug.GetType( argument )
end
local errorHead = "Daneel.Debug.CheckArgType(argument, argumentName, expectedArgumentTypes[, p_errorHead]) : "
local argType = type(argumentName)
if argType ~= "string" then
error(errorHead.."Argument 'argumentName' is of type '"..argType.."' with value '"..tostring(argumentName).."' instead of 'string'.")
end
argType = type(expectedArgumentTypes)
if argType ~= "string" and argType ~= "table" then
error(errorHead.."Argument 'expectedArgumentTypes' is of type '"..argType.."' with value '"..tostring(expectedArgumentTypes).."' instead of 'string' or 'table'.")
end
if argType == "string" then
expectedArgumentTypes = {expectedArgumentTypes}
elseif #expectedArgumentTypes <= 0 then
error(errorHead.."Argument 'expectedArgumentTypes' is an empty table.")
end
argType = type(p_errorHead)
if argType ~= "nil" and argType ~= "string" then
error(errorHead.."Argument 'p_errorHead' is of type '"..argType.."' with value '"..tostring(p_errorHead).."' instead of 'string'.")
end
if p_errorHead == nil then p_errorHead = "" end
argType = Daneel.Debug.GetType(argument)
local luaArgType = type(argument) -- any object (that are tables) will now pass the test even when Daneel.Debug.GetType(argument) does not return "table"
for i, expectedType in ipairs(expectedArgumentTypes) do
if argType == expectedType or luaArgType == expectedType then
return expectedType
end
end
error(p_errorHead.."Argument '"..argumentName.."' is of type '"..argType.."' with value '"..tostring(argument).."' instead of '"..table.concat(expectedArgumentTypes, "', '").."'.")
end
--- If the provided argument is not nil, check the provided argument's type against the provided type(s) and display error if they don't match.
-- @param argument (mixed) The argument to check.
-- @param argumentName (string) The argument name.
-- @param expectedArgumentTypes (string or table) The expected argument type(s).
-- @param p_errorHead [optional] (string) The beginning of the error message.
-- @param defaultValue [optional] (mixed) The default value to return if 'argument' is nil.
-- @return (mixed) The value of 'argument' if it's non-nil, or the value of 'defaultValue'.
function Daneel.Debug.CheckOptionalArgType(argument, argumentName, expectedArgumentTypes, p_errorHead, defaultValue)
if argument == nil then return defaultValue end
if not Daneel.Config.debug.enableDebug then return argument end
local errorHead = "Daneel.Debug.CheckOptionalArgType(argument, argumentName, expectedArgumentTypes[, p_errorHead, defaultValue]) : "
local argType = type(argumentName)
if argType ~= "string" then
error(errorHead.."Argument 'argumentName' is of type '"..argType.."' with value '"..tostring(argumentName).."' instead of 'string'.")
end
argType = type(expectedArgumentTypes)
if argType ~= "string" and argType ~= "table" then
error(errorHead.."Argument 'expectedArgumentTypes' is of type '"..argType.."' with value '"..tostring(expectedArgumentTypes).."' instead of 'string' or 'table'.")
end
if argType == "string" then
expectedArgumentTypes = {expectedArgumentTypes}
elseif #expectedArgumentTypes <= 0 then
error(errorHead.."Argument 'expectedArgumentTypes' is an empty table.")
end
argType = type(p_errorHead)
if argType ~= "nil" and argType ~= "string" then
error(errorHead.."Argument 'p_errorHead' is of type '"..argType.."' with value '"..tostring(p_errorHead).."' instead of 'string'.")
end
if p_errorHead == nil then errorHead = "" end
argType = Daneel.Debug.GetType(argument)
local luaArgType = type(argument)
for i, expectedType in ipairs(expectedArgumentTypes) do
if argType == expectedType or luaArgType == expectedType then
return argument
end
end
error(p_errorHead.."Optional argument '"..argumentName.."' is of type '"..argType.."' with value '"..tostring(argument).."' instead of '"..table.concat(expectedArgumentTypes, "', '").."'.")
end
-- For instances of objects, the type is the name of the metatable of the provided object, if the metatable is a first-level global variable.
-- Will return "ScriptedBehavior" when the provided object is a scripted behavior instance (yet ScriptedBehavior is not its metatable).
-- @param object (mixed) The argument to get the type of.
-- @param luaTypeOnly (boolean) [optional default=false] Tell whether to return only Lua's built-in types (string, number, boolean, table, function, userdata or thread).
-- @return (string) The type.
function Daneel.Debug.GetType( object, luaTypeOnly )
local errorHead = "Daneel.Debug.GetType( object[, luaTypeOnly] ) : "
-- DO NOT use CheckArgType here since it uses itself GetType() => overflow
local argType = type( luaTypeOnly )
if argType ~= "nil" and argType ~= "boolean" then
error(errorHead.."Argument 'luaTypeOnly' is of type '"..argType.."' with value '"..tostring(luaTypeOnly).."' instead of 'boolean'.")
end
if luaTypeOnly == nil then luaTypeOnly = false end
argType = type( object )
if not luaTypeOnly and argType == "table" then
-- the type is defined by the object's metatable
local mt = getmetatable( object )
if mt ~= nil then
-- the metatable of the scripted behaviors is the corresponding script asset ('Behavior' in the script)
-- the metatable of all script assets is the Script object
if getmetatable( mt ) == Script then
return "ScriptedBehavior"
end
if Daneel.Config.objectsByType ~= nil then
for type, object in pairs( Daneel.Config.objectsByType ) do
if mt == object then
return type
end
end
end
for type, object in pairs( _G ) do
if mt == object then
return type
end
end
end
end
return argType
end
oerror = error
-- prevent to set the new version of error() when DEBUG is false or before the StackTrace is enabled when DEBUG is true.
function Daneel.Debug.SetNewError()
--- Print the stackTrace unless told otherwise then the provided error in the console.
-- Only exists when debug is enabled. When debug in disabled the built-in 'error(message)'' function exists instead.
-- @param message (string) The error message.
-- @param doNotPrintStacktrace [optional default=false] (boolean) Set to true to prevent the stacktrace to be printed before the error message.
function error(message, doNotPrintStacktrace)
if Daneel.Config.debug.enableDebug and doNotPrintStacktrace ~= true then
Daneel.Debug.StackTrace.Print()
end
oerror(message)
end
end
--- Disable the debug from this point onward.
-- @param info [optional] (string) Some info about why or where you disabled the debug. Will be printed in the Runtime Report.
function Daneel.Debug.Disable(info)
if info ~= nil then
info = " : "..tostring(info)
end
print("Daneel.Debug.Disable()"..info)
error = oerror
Daneel.Config.debug.enableDebug = false
end
--- Bypass the __tostring() function that may exists on the data's metatable.
-- @param data (mixed) The data to be converted to string.
-- @return (string) The string.
function Daneel.Debug.ToRawString( data )
-- 18/10/2013 removed the stacktrace as it caused a stack overflow when printing out destroyed game objects
if data == nil and Daneel.Config.debug.enableDebug then
print( "WARNING : Daneel.Debug.ToRawString( data ) : Argument 'data' is nil.")
return nil
end
local text = nil
local mt = getmetatable( data )
if mt ~= nil then
if mt.__tostring ~= nil then
local mttostring = mt.__tostring
mt.__tostring = nil
text = tostring( data )
mt.__tostring = mttostring
end
end
if text == nil then
text = tostring( data )
end
return text
end
--- Returns the name as a string of the global variable (including nested tables) whose value is provided.
-- This only works if the value of the variable is a table or a function.
-- When the variable is nested in one or several tables (like GUI.Hud), it must have been set in the 'objects' table in the config.
-- @param value (table or function) Any global variable, any object from CraftStudio or Daneel or objects whose name is set in 'userObjects' in the Daneel.Config.
-- @return (string) The name, or nil.
function Daneel.Debug.GetNameFromValue(value)
Daneel.Debug.StackTrace.BeginFunction("Daneel.Debug.GetNameFromValue", value)
local errorHead = "Daneel.Debug.GetNameFromValue(value) : "
if value == nil then
error(errorHead.." Argument 'value' is nil.")
end
local result = table.getkey(Daneel.Config.objectsByType, value)
if result == nil then
result = table.getkey(_G, value)
end
Daneel.Debug.StackTrace.EndFunction()
return result
end
--- Check if the provided argument's value is in the provided expected value(s).
-- When that's not the case, return the value of the 'defaultValue' argument, or throws an error when it is nil.
-- Arguments of type string are considered case-insensitive. The case will be corrected but no error will be thrown.
-- When 'expectedArgumentValues' is of type table, it is always considered as a table of several expected values.
-- @param argument (mixed) The argument to check.
-- @param argumentName (string) The argument name.
-- @param expectedArgumentValues (mixed) The expected argument values(s).
-- @param p_errorHead [optional] (string) The beginning of the error message.
-- @param defaultValue [optional] (mixed) The optional default value.
-- @return (mixed) The argument's value (one of the expected argument values or default value)
function Daneel.Debug.CheckArgValue(argument, argumentName, expectedArgumentValues, p_errorHead, defaultValue)
Daneel.Debug.StackTrace.BeginFunction("Daneel.Debug.CheckArgValue", argument, argumentName, expectedArgumentValues, p_errorHead)
local errorHead = "Daneel.Debug.CheckArgValue(argument, argumentName, expectedArgumentValues[, p_errorHead, defaultValue]) : "
Daneel.Debug.CheckArgType(argumentName, "argumentName", "string", errorHead)
if expectedArgumentValues == nil then
error(errorHead.."Argument 'expectedArgumentValues' is nil.")
end
Daneel.Debug.CheckOptionalArgType(p_errorHead, "p_errorHead", "string", errorHead)
if type(expectedArgumentValues) ~= "table" then
expectedArgumentValues = { expectedArgumentValues }
elseif #expectedArgumentValues == 0 then
error(errorHead.."Argument 'expectedArgumentValues' is an empty table.")
end
local correctValue = false
if type(argument) == "string" then
for i, expectedValue in ipairs(expectedArgumentValues) do
if argument:lower() == expectedValue:lower() then
argument = expectedValue
correctValue = true
break
end
end
else
for i, expectedValue in ipairs(expectedArgumentValues) do
if argument == expectedValue then
correctValue = true
break
end
end
end
if not correctValue then
if defaultValue ~= nil then
argument = defaultValue
else
for i, value in ipairs(expectedArgumentValues) do
expectedArgumentValues[i] = tostring(value)
end
error(p_errorHead.."The value '"..tostring(argument).."' of argument '"..argumentName.."' is not one of '"..table.concat(expectedArgumentValues, "', '").."'.")
end
end
Daneel.Debug.StackTrace.EndFunction()
return argument
end
local DaneelScriptAsset = Behavior
Daneel.Debug.tryGameObject = nil -- The game object Daneel.Debug.Try() works with
--- Allow to test out a piece of code without killing the script if the code throws an error.
-- If the code throw an error, it will be printed in the Runtime Report but it won't kill the script that calls Daneel.Debug.Try().
-- Does not protect against exceptions thrown by CraftStudio.
-- @param _function (function or userdata) The function containing the code to try out.
-- @return (boolean) True if the code runs without errors, false otherwise.
function Daneel.Debug.Try( _function )
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Debug.Try", _function )
local errorHead = "Daneel.Debug.Try( _function ) : "
Daneel.Debug.CheckArgType( _function, "_function", {"function", "userdata"}, errorHead )
local gameObject = Daneel.Debug.tryGameObject
if gameObject == nil or gameObject.inner == nil then
gameObject = CraftStudio.CreateGameObject( "Daneel_Debug_Try" )
Daneel.Debug.tryGameObject = gameObject
end
local success = false
gameObject:CreateScriptedBehavior( DaneelScriptAsset, {
debugTry = true,
testFunction = _function,
successCallback = function() success = true end
} )
Daneel.Debug.StackTrace.EndFunction()
return success
end
--- Overload a function to call debug functions before and after it is itself called.
-- Do not call before Daneel is loaded as it won't run even if debug is enabled in the user config.
-- @param name (string) The function name
-- @param argsData (table) The parameters of the functions.
function Daneel.Debug.RegisterFunction( name, argsData )
if not Daneel.Config.debug.enableDebug then return end
local originalFunction = table.getvalue( _G, name )
local originalFunctionName = name
local script = argsData.script -- script asset. If set, the function is a public behavior function
if script ~= nil then
-- name is "Folder/ScriptName.FunctionName"
local nameChunks = string.split( name, "." )
local scriptPath = nameChunks[1]
local funcName = nameChunks[2]
originalFunctionName = funcName
originalFunction = script[ funcName ]
if not script.toStringIsSet then
script.__tostring = function( sb )
local id = Daneel.Utilities.GetId( sb ) or "[no id]"
return "ScriptedBehavior: "..id..": '"..scriptPath.."'"
end
script.toStringIsSet = true
-- __tostring() already exists on each scripted behavior but does not seems to do much
end
-- make sure that the first argument is the ScriptedBehavior instance
local firstArg = argsData[1]
if firstArg == nil or firstArg[2] ~= "ScriptedBehavior" then
table.insert( argsData, 1, { name = "self", type = "ScriptedBehavior" } )
end
end
if originalFunction ~= nil then
local includeInStackTrace = argsData.includeInStackTrace or Daneel.Config.debug.enableStackTrace
local errorHead = name.."( "
for i, arg in ipairs( argsData ) do
if arg.name == nil then arg.name = arg[1] end
errorHead = errorHead..arg.name..", "
end
errorHead = errorHead:sub( 1, #errorHead-2 ) -- removes the last coma+space
errorHead = errorHead.." ) : "
local newFunction = function( ... )
local funcArgs = { ... }
if includeInStackTrace then
Daneel.Debug.StackTrace.BeginFunction( name, ... )
end
for i, arg in ipairs( argsData ) do
arg.type = arg.type or arg[2]
if arg.type ~= nil then
if arg.isOptional == true then
Daneel.Debug.CheckOptionalArgType( funcArgs[ i ], arg.name, arg.type, errorHead )
else
Daneel.Debug.CheckArgType( funcArgs[ i ], arg.name, arg.type, errorHead )
end
elseif funcArgs[ i ] == nil and not arg.isOptional then
error( errorHead.."Argument '"..arg.name.."' is nil." )
end
end
local returnValues = { originalFunction( ... ) }
if includeInStackTrace then
Daneel.Debug.StackTrace.EndFunction()
end
return unpack( returnValues )
end
if script ~= nil then
script[ originalFunctionName ] = newFunction
else
table.setvalue( _G, name, newFunction )
end
else
print( "Daneel.Debug.RegisterFunction(): Function with name '"..name.."' was not found." )
end
end
--- Register all functions of a scripted behavior to be included in the stacktrace.
-- Within a script, the 'Behavior' variable is the script asset.
-- @param script (Script) The script asset.
function Daneel.Debug.RegisterScript( script )
if type( script ) ~= "table" or getmetatable( script ) ~= Script then
error("Daneel.Debug.SetupScript(script): Provided argument is not a script asset. Within a script, the 'Behavior' variable is the script asset.")
end
local infos = Daneel.Debug.functionArgumentsInfo
local forbiddenNames = { "Update", "inner" }
-- Awake, is never included in the stacktrace anyway because CraftStudio
-- keeps the reference to the function first set in the script.
-- Overloading it at runtime has no effect.
-- 05/12/2014 It isn't the case for Start()
local scriptPath = Map.GetPathInPackage( script )
for name, func in pairs( script ) do
local fullName = scriptPath.."."..name
if
not name:startswith("__") and
not table.containsvalue( forbiddenNames, name ) and
infos[fullName] == nil
then
infos[fullName] = { script = script }
end
end
end
--- Register all functions of an object to be included in the stacktrace.
-- The following function name are always excluded from the stacktrace and debug :
-- "Load", "DefaultConfig", "UserConfig", "Awake", "Start", "Update", "New", "inner", "GetId", "GetName"
-- Plus function names that begins by "__" or "o".
-- @param object (table or string) The object, or object's name.
function Daneel.Debug.RegisterObject( object )
local originalArgument = object
local objectName = nil
if type(object) == "string" then
objectName = object
object = table.getvalue( Daneel.Config.objectsByType, objectName )
if object == nil then
object = table.getvalue( _G, objectName )
end
else
objectName = Daneel.Debug.GetNameFromValue( object )
end
if object == nil or objectName == nil then
print("Daneel.Debug.RegisterObject(): object or name not found", originalArgument, object, objectName)
return
end
local infos = Daneel.Debug.functionArgumentsInfo
local forbiddenNames = { "Load", "DefaultConfig", "UserConfig", "Awake", "Start", "Update", "New", "inner", "GetId", "GetName" }
for name, func in pairs( object ) do
if type( func ) == "function" or type( func ) == "userdata" then
local fullName = objectName.."."..name
if
not name:startswith("__") and
not name:startswith("o") and
not table.containsvalue( forbiddenNames, name ) and
infos[fullName] == nil
then
infos[fullName] = {}
end
end
end
end
----------------------------------------------------------------------------------
-- StackTrace
Daneel.Debug.StackTrace = { messages = {} }
--- Register a function call in the stack trace.
-- @param functionName (string) The function name.
-- @param ... [optional] (mixed) Arguments received by the function.
function Daneel.Debug.StackTrace.BeginFunction( functionName, ... )
if
not Daneel.Config.debug.enableDebug or
not Daneel.Config.debug.enableStackTrace
then
return
end
if #Daneel.Debug.StackTrace.messages > 200 then
print( "WARNING : your StackTrace is more than 200 items long ! Emptying the StackTrace now. Did you forget to write a 'EndFunction()' somewhere ?" )
Daneel.Debug.StackTrace.messages = {}
end
local errorHead = "Daneel.Debug.StackTrace.BeginFunction( functionName[, ...] ) : "
Daneel.Debug.CheckArgType( functionName, "functionName", "string", errorHead )
local msg = functionName .. "( "
local arg = {...}
if #arg > 0 then
for i, argument in ipairs( arg ) do
if type( argument) == "string" then
msg = msg .. '"' .. tostring( argument ) .. '", '
else
msg = msg .. tostring( argument ) .. ", "
end
end
msg = msg:sub( 1, #msg-2 ) -- removes the last coma+space
end
msg = msg .. " )"
table.insert( Daneel.Debug.StackTrace.messages, msg )
end
--- Closes a successful function call, removing it from the stacktrace.
function Daneel.Debug.StackTrace.EndFunction()
if
not Daneel.Config.debug.enableDebug or
not Daneel.Config.debug.enableStackTrace
then
return
end
-- since 16/05/2013 no arguments is needed anymore, since the StackTrace only keeps open functions calls and never keep returned values
-- I didn't rewrote all the calls to EndFunction()
table.remove( Daneel.Debug.StackTrace.messages )
end
--- Prints the StackTrace.
function Daneel.Debug.StackTrace.Print()
if
not Daneel.Config.debug.enableDebug or
not Daneel.Config.debug.enableStackTrace
then
return
end
local messages = Daneel.Debug.StackTrace.messages
Daneel.Debug.StackTrace.messages = {}
print( "~~~~~ Daneel.Debug.StackTrace ~~~~~" )
if #messages <= 0 then
print( "No message in the StackTrace." )
else
for i, msg in ipairs( messages ) do
if i < 10 then
i = "0"..i
end
print( "#" .. i .. " " .. msg )
end
end
end
----------------------------------------------------------------------------------
-- Event
Daneel.Event = {
events = {}, -- listeners by events - emptied when a new scene is loaded in CraftStudio.LoadScene()
persistentEvents = {}, -- not emptied
}
--- Make the provided function or object listen to the provided event(s).
-- The function will be called whenever the provided event will be fired.
-- @param eventName (string or table) The event name (or names in a table).
-- @param functionOrObject (function or table) The function (not the function name) or the object.
-- @param isPersistent (boolean) [default=false] Tell whether the listener automatically stops to listen to any event when a new scene is loaded. Always false when the listener is a game object or a component.
function Daneel.Event.Listen( eventName, functionOrObject, isPersistent )
local errorHead = "Daneel.Event.Listen( eventName, functionOrObject[, isPersistent] ) : "
local listenerType = type( functionOrObject )
local eventNames = eventName
if type( eventName ) == "string" then
eventNames = { eventName }
end
for i, eventName in pairs( eventNames ) do
if Daneel.Event.events[ eventName ] == nil then
Daneel.Event.events[ eventName ] = {}
end
if Daneel.Event.persistentEvents[ eventName ] == nil then
Daneel.Event.persistentEvents[ eventName ] = {}
end
if
not table.containsvalue( Daneel.Event.events[ eventName ], functionOrObject ) and
not table.containsvalue( Daneel.Event.persistentEvents[ eventName ], functionOrObject )
then
-- check that the persistent listener is not a game object or a component (that are always destroyed when the scene loads)
if isPersistent == true and listenerType == "table" then
local mt = getmetatable( functionOrObject )
if mt ~= nil and mt == GameObject or table.containsvalue( Daneel.Config.componentObjectsByType, mt ) then
if Daneel.Config.debug.enableDebug then
print( errorHead.."Game objects and components can't be persistent listeners", functionOrObject )
end
isPersistent = false
end
end
local eventList = Daneel.Event.events
if isPersistent == true then
eventList = Daneel.Event.persistentEvents
end
table.insert( eventList[ eventName ], functionOrObject )
end
end
end
--- Make the provided function or object to stop listen to the provided event(s).
-- @param eventName (string or table) [optional] The event name or names in a table or nil to stop listen to every events.
-- @param functionOrObject (function, string or GameObject) The function, or the game object name or instance.
function Daneel.Event.StopListen( eventName, functionOrObject )
if type( eventName ) ~= "string" then
functionOrObject = eventName
eventName = nil
end
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Event.StopListen", eventName, functionOrObject )
local errorHead = "Daneel.Event.StopListen( eventName, functionOrObject ) : "
Daneel.Debug.CheckOptionalArgType( eventName, "eventName", "string", errorHead )
Daneel.Debug.CheckArgType( functionOrObject, "functionOrObject", {"table", "function"}, errorHead )
local eventNames = eventName
if type( eventName ) == "string" then
eventNames = { eventName }
end
if eventNames == nil then
eventNames = table.merge( table.getkeys( Daneel.Event.events ), table.getkeys( Daneel.Event.persistentEvents ) )
end
for i, eventName in pairs( eventNames ) do
local listeners = Daneel.Event.events[ eventName ]
if listeners ~= nil then
table.removevalue( listeners, functionOrObject )
end
listeners = Daneel.Event.persistentEvents[ eventName ]
if listeners ~= nil then
table.removevalue( listeners, functionOrObject )
end
end
Daneel.Debug.StackTrace.EndFunction()
end
--- Fire the provided event at the provided object or the one that listen to it,
-- transmitting along all subsequent arguments if some exists. <br>
-- Allowed set of arguments are : <br>
-- (eventName[, ...]) <br>
-- (object, eventName[, ...]) <br>
-- @param object [optional] (table) The object to which fire the event at. If nil or abscent, will send the event to its listeners.
-- @param eventName (string) The event name.
-- @param ... [optional] Some arguments to pass along.
function Daneel.Event.Fire( object, eventName, ... )
local arg = {...}
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Event.Fire", object, eventName, ... )
local errorHead = "Daneel.Event.Fire( [object, ]eventName[, ...] ) : "
local argType = type( object )
if argType == "string" then
-- no object provided, fire on the listeners
if eventName ~= nil then
table.insert( arg, 1, eventName )
end
eventName = object
object = nil
elseif argType ~= "nil" then
Daneel.Debug.CheckArgType( object, "object", "table", errorHead )
Daneel.Debug.CheckArgType( eventName, "eventName", "string", errorHead )
end
local listeners = { object }
if object == nil then
if Daneel.Event.events[ eventName ] ~= nil then
listeners = Daneel.Event.events[ eventName ]
end
if Daneel.Event.persistentEvents[ eventName ] ~= nil then
listeners = table.merge( listeners, Daneel.Event.persistentEvents[ eventName ] )
end
end
local listenersToBeRemoved = {}
for i=1, #listeners do
local listener = listeners[i]
local listenerType = type( listener )
if listenerType == "function" or listenerType == "userdata" then
if listener( unpack( arg ) ) == false then
table.insert( listenersToBeRemoved, listener )
end
else -- an object
local mt = getmetatable( listener )
local listenerIsAlive = not listener.isDestroyed
if mt == GameObject and listener.inner == nil then
listenerIsAlive = false
end
if listenerIsAlive then -- ensure that the event is not fired on a dead game object or component
local functions = {} -- list of listener functions attached to this object
if listener.listenersByEvent ~= nil and listener.listenersByEvent[ eventName ] ~= nil then
functions = listener.listenersByEvent[ eventName ]
end
-- Look for the value of the EventName property on the object
local func = rawget( listener, eventName )
-- Using rawget() prevent a 'Behavior function' to be called as a regular function when the listener is a ScriptedBehavior
-- because the function exists on the Script object and not on the ScriptedBehavior (the listener),
-- in which case rawget() returns nil
if func ~= nil then
table.insert( functions, func )
end
-- call all listener functions
for j=1, #functions do
functions[j]( ... )
end
-- always try to send the message if the object is a game object
if mt == GameObject then
local go = arg[1]
if go == listener then
-- don't send the first argument when it is the listener game
table.remove( arg, 1 )
end
if #arg == 1 and type( arg[1] ) == "table" then
-- directly send the table if there is no other argument
arg = arg[1]
end
listener:SendMessage( eventName, arg )
end
end
end
end -- end for listeners
for i=1, #listenersToBeRemoved do
Daneel.Event.StopListen( eventName, listenersToBeRemoved[i] )
end
Daneel.Debug.StackTrace.EndFunction()
end
--- Fire an event at the provided game object.
-- @param gameObject (GameObject) The game object.
-- @param eventName (string) The event name.
-- @param ... [optional] Some arguments to pass along.
function GameObject.FireEvent( gameObject, eventName, ... )
Daneel.Event.Fire( gameObject, eventName, ... )
end
--- Add a listener function for the specified local event on this object.
-- @param object (table) The object.
-- @param eventName (string) The name of the event to listen to.
-- @param listener (function or userdata) The listener function.
function Daneel.Event.AddEventListener( object, eventName, listener )
if object.listenersByEvent == nil then
object.listenersByEvent = {}
end
if object.listenersByEvent[ eventName ] == nil then
object.listenersByEvent[ eventName ] = {}
end
if not table.containsvalue( object.listenersByEvent[ eventName ], listener ) then
table.insert( object.listenersByEvent[ eventName ], listener )
elseif Daneel.Debug.enableDebug == true then
print("Daneel.Event.AddEventListener(): "..tostring(listener).." already listen for event '"..eventName.."' on object: ", object)
end
end
--- Add a listener function for the specified local event on this game object.
-- Alias of Daneel.Event.AddEventListener().
-- @param gameObject (GameObject) The game object.
-- @param eventName (string) The name of the event to listen to.
-- @param listener (function or userdata) The listener function.
function GameObject.AddEventListener( gameObject, eventName, listener )
Daneel.Event.AddEventListener( gameObject, eventName, listener )
end
--- Remove the specified listener for the specified local event on this object
-- @param object (table) The object.
-- @param eventName (string) The name of the event.
-- @param listener (function or userdata) [optional] The listener function to remove. If nil, all listeners will be removed for the specified event.
function Daneel.Event.RemoveEventListener( object, eventName, listener )
if object.listenersByEvent ~= nil and object.listenersByEvent[ eventName ] ~= nil then
if listener ~= nil then
table.removevalue( object.listenersByEvent[ eventName ], listener )
else
object.listenersByEvent[ eventName ] = nil
end
end
end
--- Remove the specified listener for the specified local event on this game object
-- @param gameObject (table) The game object.
-- @param eventName (string) The name of the event.
-- @param listener (function or userdata) [optional] The listener function to remove. If nil, all listeners will be removed for the specified event.
function GameObject.RemoveEventListener( gameObject, eventName, listener )
Daneel.Event.RemoveEventListener( gameObject, eventName, listener )
end
local _go = { "gameObject", "GameObject" }
table.mergein( Daneel.Debug.functionArgumentsInfo, {
["Daneel.Event.Listen"] = { { "eventName", { s, t } }, { "functionOrObject", {t, f, u} }, { "isPersistent", b, isOptional = true } },
["GameObject.FireEvent"] = { _go, { "eventName", s } },
["Daneel.Event.AddEventListener"] = { { "object", "table" }, { "eventName", s }, { "listener", { f, u } } },
["GameObject.AddEventListener"] = { _go, { "eventName", s }, { "listener", { f, u } } },
["Daneel.Event.RemoveEventListener"] = { { "object", "table" }, { "eventName", s }, { "listener", { f, u }, isOptional = true } },
["GameObject.RemoveEventListener"] = { _go, { "eventName", s }, { "listener", { f, u }, isOptional = true } },
} )
----------------------------------------------------------------------------------
-- Time
Daneel.Time = {
realTime = 0.0,
realDeltaTime = 0.0,
time = 0.0,
deltaTime = 0.0,
timeScale = 1.0,
frameCount = 0,
}
----------------------------------------------------------------------------------
-- Config, loading
function Daneel.DefaultConfig()
local config = {
debug = {
enableDebug = false, -- Enable/disable Daneel's global debugging features (error reporting + stacktrace).
enableStackTrace = false, -- Enable/disable the Stack Trace.
},
-- this table define the object's type names, returned by Daneel.Debug.GetType()
objectsByType = {
GameObject = GameObject,
Vector3 = Vector3,
Quaternion = Quaternion,
Plane = Plane,
Ray = Ray,
},
componentObjectsByType = {
ScriptedBehavior = ScriptedBehavior,
ModelRenderer = ModelRenderer,
MapRenderer = MapRenderer,
Camera = Camera,
Transform = Transform,
Physics = Physics,
TextRenderer = TextRenderer,
NetworkSync = NetworkSync,
},
componentTypes = {},
assetObjectsByType = {
Script = Script,
Model = Model,
ModelAnimation = ModelAnimation,
Map = Map,
TileSet = TileSet,
Sound = Sound,
Scene = Scene,
--Document = Document,
Font = Font,
},
assetTypes = {},
}
return config
end
Daneel.Config = Daneel.DefaultConfig()
Daneel.Config.assetTypes = table.getkeys( Daneel.Config.assetObjectsByType ) -- needed in the CraftStudio script before Daneel is loaded
-- load Daneel at the start of the game
function Daneel.Load()
if Daneel.isLoaded then return end
Daneel.isLoading = true
-- load Daneel config
local userConfig = nil
if Daneel.UserConfig ~= nil then
table.mergein( Daneel.Config, Daneel.UserConfig(), true )
end
-- load modules config
for i, name in ipairs( Daneel.modules.moduleNames ) do
local module = Daneel.modules[ name ]
if module.isConfigLoaded ~= true then
module.isConfigLoaded = true
if module.Config == nil then
if module.DefaultConfig ~= nil then
module.Config = module.DefaultConfig()
else
module.Config = {}
end
end
if module.UserConfig ~= nil then
table.mergein( module.Config, module.UserConfig(), true )
end
if module.Config.objectsByType ~= nil then
table.mergein( Daneel.Config.objectsByType, module.Config.objectsByType )
end
if module.Config.componentObjectsByType ~= nil then
table.mergein( Daneel.Config.componentObjectsByType, module.Config.componentObjectsByType )
table.mergein( Daneel.Config.objectsByType, module.Config.componentObjectsByType )
end
end
end
table.mergein( Daneel.Config.objectsByType, Daneel.Config.componentObjectsByType, Daneel.Config.assetObjectsByType )
-- Enable nice printing + dynamic access of getters/setters on components
for componentType, componentObject in pairs( Daneel.Config.componentObjectsByType ) do
Daneel.Utilities.AllowDynamicGettersAndSetters( componentObject, { Component } )
if componentType ~= "ScriptedBehavior" then
componentObject["__tostring"] = function( component )
return componentType .. ": " .. component:GetId()
end
end
end
table.mergein( Daneel.Config.componentTypes, table.getkeys( Daneel.Config.componentObjectsByType ) )
-- Enable nice printing + dynamic access of getters/setters on assets
for assetType, assetObject in pairs( Daneel.Config.assetObjectsByType ) do
Daneel.Utilities.AllowDynamicGettersAndSetters( assetObject, { Asset } )
assetObject["__tostring"] = function( asset )
return assetType .. ": " .. Daneel.Utilities.GetId( asset ) .. ": '" .. Map.GetPathInPackage( asset ) .. "'"
end
end
-- setup error reporting + stack trace
if Daneel.Config.debug.enableDebug then
if Daneel.Config.debug.enableStackTrace then
Daneel.Debug.SetNewError()
end
-- overload functions with debug (error reporting + stacktrace)
for funcName, data in pairs( Daneel.Debug.functionArgumentsInfo ) do
Daneel.Debug.RegisterFunction( funcName, data )
end
end
CS.IsWebPlayer = type( Camera.ProjectionMode.Orthographic ) == "number" -- "userdata" in native runtimes
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Load" )
-- Load modules
for i, name in ipairs( Daneel.modules.moduleNames ) do
local module = Daneel.modules[ name ]
if module.isLoaded ~= true then
module.isLoaded = true
if type( module.Load ) == "function" then
module.Load()
end
end
end
Daneel.isLoaded = true
Daneel.isLoading = false
if Daneel.Config.debug.enableDebug then
print( "~~~~~ Daneel loaded ~~~~~" )
end
-- check for module update functions
Daneel.moduleUpdateFunctions = {}
for i, name in ipairs( Daneel.modules.moduleNames ) do
local module = Daneel.modules[ name ]
if module.doNotCallUpdate ~= true then
if type( module.Update ) == "function" and not table.containsvalue( Daneel.moduleUpdateFunctions, module.Update ) then
table.insert( Daneel.moduleUpdateFunctions, module.Update )
end
end
end
Daneel.Debug.StackTrace.EndFunction()
end -- end Daneel.Load()
----------------------------------------------------------------------------------
-- Runtime
-- luadoc stop
function Behavior.Awake( self )
if self.debugTry == true then
CraftStudio.Destroy( self )
self.testFunction()
-- testFunction() may throw an error, kill the scripted behavior and not call the success callback
-- but it won't kill the script that created the scripted behavior (the one that called Daneel.Debug.Try())
self.successCallback()
return
end
if table.getvalue( _G, "LOAD_DANEEL" ) ~= nil and LOAD_DANEEL == false then -- just for tests purposes
return
end
if Daneel.isAwake then
if Daneel.Config.debug.enableDebug then
print( "Daneel:Awake() : You tried to load Daneel twice ! The 'Daneel' scripted behavior is on two game objects inside the same scene. This time, it was on " .. tostring( self.gameObject ) )
end
CS.Destroy( self )
return
end
Daneel.isAwake = true
Daneel.Event.Listen( "OnNewSceneWillLoad", function() Daneel.isAwake = false end )
Daneel.Load()
Daneel.Debug.StackTrace.messages = {}
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Awake" )
-- Awake modules
for i, name in ipairs( Daneel.modules.moduleNames ) do
local module = Daneel.modules[ name ]
if type( module.Awake ) == "function" then
module.Awake()
end
end
if Daneel.Config.debug.enableDebug then
print("~~~~~ Daneel awake ~~~~~")
end
Daneel.Event.Fire( "OnAwake" )
Daneel.Debug.StackTrace.EndFunction()
end
function Behavior.Start( self )
if self.debugTry then
return
end
Daneel.Debug.StackTrace.BeginFunction( "Daneel.Start" )
-- Start modules
for i, name in ipairs( Daneel.modules.moduleNames ) do
local module = Daneel.modules[ name ]
if type( module.Start ) == "function" then
module.Start()
end
end
if Daneel.Config.debug.enableDebug then
print("~~~~~ Daneel started ~~~~~")
end
Daneel.Event.Fire( "OnStart" )
Daneel.Debug.StackTrace.EndFunction()
end
function Behavior.Update( self )
if self.debugTry then
return
end
-- Time
local currentTime = os.clock()
Daneel.Time.realDeltaTime = currentTime - Daneel.Time.realTime
Daneel.Time.realTime = currentTime
Daneel.Time.deltaTime = Daneel.Time.realDeltaTime * Daneel.Time.timeScale
Daneel.Time.time = Daneel.Time.time + Daneel.Time.deltaTime
Daneel.Time.frameCount = Daneel.Time.frameCount + 1
-- Update modules
for i=1, #Daneel.moduleUpdateFunctions do
Daneel.moduleUpdateFunctions[i]()
end
end
--------------------------------------------------------------------------------
-- Mouse Input component
-- Enable mouse interactions with game objects when added to a game object with a camera component.
MouseInput = {
buttonExists = { LeftMouse = false, RightMouse = false, WheelUp = false, WheelDown = false },
lastLeftClickFrame = 0,
components = {}, -- array of mouse input components
}
Daneel.modules.MouseInput = MouseInput
function MouseInput.DefaultConfig()
return {
doubleClickDelay = 20, -- Maximum number of frames between two clicks of the left mouse button to be considered as a double click
componentObjectsByType = {
MouseInput = MouseInput,
},
}
end
MouseInput.Config = MouseInput.DefaultConfig()
function MouseInput.Load()
for buttonName, _ in pairs( MouseInput.buttonExists ) do
MouseInput.buttonExists[ buttonName ] = Daneel.Utilities.ButtonExists( buttonName )
end
end
function MouseInput.Awake()
MouseInput.components = {}
end
--- Update the specified MouseInput component or update all components when no argument is passed.
-- When the component is specified, the update is forced. It happens even if the mouse doesn't move and no button input happens.
-- @param mouseInput (MouseInput) [optional] The MouseInput component to update.
function MouseInput.Update( mouseInput )
local forceUpdate = false
local components = MouseInput.components
if mouseInput ~= nil then
forceUpdate = true
components = { mouseInput }
end
if #components == 0 then
return
end
local mouseDelta = CS.Input.GetMouseDelta()
local mouseIsMoving = false
if mouseDelta.x ~= 0 or mouseDelta.y ~= 0 then
mouseIsMoving = true
end
local leftMouseJustPressed = false
local leftMouseDown = false
local leftMouseJustReleased = false
if MouseInput.buttonExists.LeftMouse then
leftMouseJustPressed = CS.Input.WasButtonJustPressed( "LeftMouse" )
leftMouseDown = CS.Input.IsButtonDown( "LeftMouse" )
leftMouseJustReleased = CS.Input.WasButtonJustReleased( "LeftMouse" )
end
local rightMouseJustPressed = false
if MouseInput.buttonExists.RightMouse then
rightMouseJustPressed = CS.Input.WasButtonJustPressed( "RightMouse" )
end
local wheelUpJustPressed = false
if MouseInput.buttonExists.WheelUp then
wheelUpJustPressed = CS.Input.WasButtonJustPressed( "WheelUp" )
end
local wheelDownJustPressed = false
if MouseInput.buttonExists.WheelDown then
wheelDownJustPressed = CS.Input.WasButtonJustPressed( "WheelDown" )
end
if
forceUpdate == true or
mouseIsMoving == true or
leftMouseJustPressed == true or
leftMouseDown == true or
leftMouseJustReleased == true or
rightMouseJustPressed == true or
wheelUpJustPressed == true or
wheelDownJustPressed == true
then
local doubleClick = false
if leftMouseJustPressed then
doubleClick = ( Daneel.Time.frameCount <= MouseInput.lastLeftClickFrame + MouseInput.Config.doubleClickDelay )
MouseInput.lastLeftClickFrame = Daneel.Time.frameCount
end
local reindexComponents = false
for i=1, #components do
local component = components[i]
local mi_gameObject = component.gameObject -- mouse input game object
if mi_gameObject.inner ~= nil and not mi_gameObject.isDestroyed and mi_gameObject.camera ~= nil then
local ray = mi_gameObject.camera:CreateRay( CS.Input.GetMousePosition() )
for j=1, #component._tags do
local tag = component._tags[j]
local gameObjects = GameObject.GetWithTag( tag )
for k=1, #gameObjects do
local gameObject = gameObjects[k]
-- gameObject is the game object whose position is checked against the raycasthit
local raycastHit = ray:IntersectsGameObject( gameObject )
if raycastHit ~= nil then
-- the mouse pointer is over the gameObject
if not gameObject.isMouseOver then
gameObject.isMouseOver = true
Daneel.Event.Fire( gameObject, "OnMouseEnter", gameObject )
end
elseif gameObject.isMouseOver == true then
-- the gameObject was still hovered the last frame
gameObject.isMouseOver = false
Daneel.Event.Fire( gameObject, "OnMouseExit", gameObject )
end
if gameObject.isMouseOver == true then
Daneel.Event.Fire( gameObject, "OnMouseOver", gameObject, raycastHit )
if leftMouseJustPressed == true then
Daneel.Event.Fire( gameObject, "OnClick", gameObject )
if doubleClick == true then
Daneel.Event.Fire( gameObject, "OnDoubleClick", gameObject )
end
end
if leftMouseDown == true and mouseIsMoving == true then
Daneel.Event.Fire( gameObject, "OnDrag", gameObject )
end
if leftMouseJustReleased == true then
Daneel.Event.Fire( gameObject, "OnLeftClickReleased", gameObject )
end
if rightMouseJustPressed == true then
Daneel.Event.Fire( gameObject, "OnRightClick", gameObject )
end
if wheelUpJustPressed == true then
Daneel.Event.Fire( gameObject, "OnWheelUp", gameObject )
end
if wheelDownJustPressed == true then
Daneel.Event.Fire( gameObject, "OnWheelDown", gameObject )
end
end
end -- for gameObjects with current tag
end -- for component._tags
else
-- this component's game object is dead or has no camera component
components[i] = nil
reindexComponents = true
end -- gameObject is alive
end -- for components
if reindexComponents == true and mouseInput == nil then
MouseInput.components = table.reindex( components )
end
end -- if mouseIsMoving, ...
end -- end MouseInput.Update()
--- Create a new MouseInput component.
-- @param gameObject (GameObject) The game object.
-- @param params (table) [optional] A table of parameters.
-- @return (MouseInput) The new component.
function MouseInput.New( gameObject, params )
if gameObject.camera == nil then
error( "MouseInput.New(gameObject, params) : "..tostring(gameObject).." has no Camera component." )
return
end
local component = { _tags = {} }
component.gameObject = gameObject
gameObject.mouseInput = component
setmetatable( component, MouseInput )
if params ~= nil then
component:Set( params )
end
table.insert( MouseInput.components, component )
return component
end
--- Set tag(s) of the game objects the component works with.
-- @param mouseInput (MouseInput) The mouse input component.
-- @param tags (string or table) The tag(s) of the game objects the component works with.
function MouseInput.SetTags( mouseInput, tags )
if type( tags ) == "string" then
tags = {tags}
end
mouseInput._tags = tags
end
--- Return the tag(s) of the game objects the component works with.
-- @param mouseInput (MouseInput) The mouse input component.
-- @return (table) The tag(s) of the game objects the component works with.
function MouseInput.GetTags( mouseInput )
return mouseInput._tags
end
local _mo = { "mouseInput", "MouseInput" }
table.mergein( Daneel.Debug.functionArgumentsInfo, {
["MouseInput.New"] = { _go, { "params", "table", isOptional = true } },
["MouseInput.SetTags"] = { _mo, { "tags", { s, t } } },
["MouseInput.GetTags"] = { _mo },
} )
--------------------------------------------------------------------------------
-- Trigger component
Trigger = {
components = {},
}
Daneel.modules.Trigger = Trigger
function Trigger.DefaultConfig()
return {
componentObjectsByType = {
Trigger = Trigger,
},
}
end
Trigger.Config = Trigger.DefaultConfig()
function Trigger.Awake()
Trigger.components = {}
end
function Trigger.Update()
local reindexComponents = false
for i=1, #Trigger.components do
local trigger = Trigger.components[i]
local triggerGameObject = trigger.gameObject
if triggerGameObject.inner ~= nil and not triggerGameObject.isDestroyed then
if trigger._updateInterval > 1 and Daneel.Time.frameCount % trigger._updateInterval == 0 then
local triggerPosition = triggerGameObject.transform:GetPosition()
for j=1, #trigger._tags do
local tag = trigger._tags[j]
local gameObjects = GameObject.GetWithTag( tag )
for k=1, #gameObjects do
local gameObject = gameObjects[k]
-- gameObject is the game object whose position is checked against the trigger's
if gameObject ~= triggerGameObject then
local gameObjectIsInRange = trigger:IsGameObjectInRange( gameObject, triggerPosition )
local gameObjectWasInRange = table.containsvalue( trigger.gameObjectsInRangeLastUpdate, gameObject )
if gameObjectIsInRange then
if gameObjectWasInRange then
-- already in this trigger
Daneel.Event.Fire( gameObject, "OnTriggerStay", gameObject, triggerGameObject )
Daneel.Event.Fire( triggerGameObject, "OnTriggerStay", triggerGameObject, gameObject )
else
-- just entered the trigger
table.insert( trigger.gameObjectsInRangeLastUpdate, gameObject )
Daneel.Event.Fire( gameObject, "OnTriggerEnter", gameObject, triggerGameObject )
Daneel.Event.Fire( triggerGameObject, "OnTriggerEnter", triggerGameObject, gameObject )
end
elseif gameObjectWasInRange then
-- was in the trigger, but not anymore
table.removevalue( trigger.gameObjectsInRangeLastUpdate, gameObject )
Daneel.Event.Fire( gameObject, "OnTriggerExit", gameObject, triggerGameObject )
Daneel.Event.Fire( triggerGameObject, "OnTriggerExit", triggerGameObject, gameObject )
end
end
end -- for gameObjects with current tag
end -- for component._tags
end -- it's time to update this trigger
else
-- this component's game object is dead
Trigger.components[i] = nil
reindexComponents = true
end -- game object is alive
end -- for Trigger.components
if reindexComponents == true then
Trigger.components = table.reindex( Trigger.components )
end
end
--- Create a new Trigger component.
-- @param gameObject (GameObject) The game object.
-- @param params (table) [optional] A table of parameters.
-- @return (Trigger) The new component.
function Trigger.New( gameObject, params )
local trigger = {
_range = 1,
_updateInterval = 5,
_tags = {},
gameObjectsInRangeLastUpdate = {},
}
trigger.gameObject = gameObject
gameObject.trigger = trigger
setmetatable( trigger, Trigger )
if params ~= nil then
trigger:Set( params )
end
table.insert( Trigger.components, trigger )
return trigger
end
--- Set tag(s) of the game objects the component works with.
-- @param trigger (Trigger) The trigger component.
-- @param tags (string or table) The tag(s) of the game objects the component works with.
function Trigger.SetTags( trigger, tags )
if type( tags ) == "string" then
tags = {tags}
end
trigger._tags = tags
end
--- Return the tag(s) of the game objects the component works with.
-- @param trigger (Trigger) The trigger component.
-- @return (table) The tag(s) of the game objects the component works with.
function Trigger.GetTags( trigger )
return trigger._tags
end
--- Set the range of the trigger.
-- @param trigger (Trigger) The trigger component.
-- @param range (number) The range of the trigger. Must be >= 0. Set to 0 to use the trigger's map or model as area.
function Trigger.SetRange( trigger, range )
trigger._range = math.clamp( range, 0, 9999 )
end
--- Get the range of the trigger.
-- @param trigger (Trigger) The trigger component.
-- @return (number) The range of the trigger.
function Trigger.GetRange( trigger )
return trigger._range
end
--- Set the interval (in frames) at which the trigger is automatically updated.
-- A value < 1 will prevent the trigger to be automatically updated.
-- @param trigger (Trigger) The trigger component.
-- @param updateInterval (number) The update interval in frames. Must be >= 0
function Trigger.SetUpdateInterval( trigger, updateInterval )
trigger._updateInterval = math.clamp( updateInterval, 0, 9999 )
end
--- Get the interval (in frames) at which the trigger is automatically updated.
-- @param trigger (Trigger) The trigger component.
-- @return (number) The update interval (in frames) of the trigger.
function Trigger.GetUpdateInterval( trigger )
return trigger._updateInterval
end
--- Get the gameObjects that are within range of that trigger.
-- @param trigger (Trigger) The trigger component.
-- @return (table) The list of the gameObjects in range (empty if none in range).
function Trigger.GetGameObjectsInRange( trigger )
local triggerPosition = trigger.gameObject.transform:GetPosition()
local gameObjectsInRange = {}
for i=1, #trigger._tags do
local gameObjects = GameObject.GetWithTag( trigger._tags[i] )
for j=1, #gameObjects do
local gameObject = gameObjects[j]
if
gameObject ~= trigger.gameObject and
trigger:IsGameObjectInRange( gameObject, triggerPosition )
then
table.insertonce( gameObjectsInRange, gameObject )
end
end
end
return gameObjectsInRange
end
--- Tell whether the provided game object is in range of the trigger.
-- @param trigger (Trigger) The trigger component.
-- @param gameObject (GameObject) The gameObject.
-- @param triggerPosition (Vector3) [optional] The trigger's current position.
-- @return (boolean) True or false.
function Trigger.IsGameObjectInRange( trigger, gameObject, triggerPosition )
local errorHead = "Behavior:IsGameObjectInRange( gameObject[, triggerPosition] )"
local triggerGameObject = trigger.gameObject
if triggerPosition == nil then
triggerPosition = triggerGameObject.transform:GetPosition()
end
local gameObjectIsInTrigger = false
local directionToGameObject = gameObject.transform:GetPosition() - triggerPosition
local sqrDistanceToGameObject = directionToGameObject:SqrLength()
if trigger._range > 0 and sqrDistanceToGameObject <= trigger._range ^ 2 then
gameObjectIsInTrigger = true
elseif trigger._range <= 0 then
if trigger.ray == nil then
trigger.ray = Ray.New( Vector3.New(0), Vector3.New(0) )
end
local ray = trigger.ray
ray.position = triggerPosition
ray.direction = directionToGameObject -- ray from the trigger to the game object
local distanceToTriggerAsset = nil -- distance to trigger model or map
if triggerGameObject.modelRenderer ~= nil then
distanceToTriggerAsset = ray:IntersectsModelRenderer( triggerGameObject.modelRenderer )
elseif triggerGameObject.mapRenderer ~= nil then
distanceToTriggerAsset = ray:IntersectsMapRenderer( triggerGameObject.mapRenderer )
end
-- if the gameObject has a model or map, replace the distance to the game object with the distance to the asset
if gameObject.modelRenderer ~= nil then
sqrDistanceToGameObject = ray:IntersectsModelRenderer( gameObject.modelRenderer ) ^ 2
elseif gameObject.mapRenderer ~= nil then
sqrDistanceToGameObject = ray:IntersectsMapRenderer( gameObject.mapRenderer ) ^ 2
end
if distanceToTriggerAsset ~= nil and sqrDistanceToGameObject <= distanceToTriggerAsset ^ 2 then
-- distance from the trigger to the game object is inferior to the distance from the trigger to the trigger's model or map
-- that means the GO is inside of the model/map
-- the ray goes through the GO origin before intersecting the asset
gameObjectIsInTrigger = true
end
end
return gameObjectIsInTrigger
end
local _trigger = { "trigger", "Trigger" }
table.mergein( Daneel.Debug.functionArgumentsInfo, {
["Trigger.New"] = { _go, { "params", "table", isOptional = true } },
["Trigger.SetTags"] = { _trigger, { "tags", { s, t } } },
["Trigger.GetTags"] = { _trigger },
["Trigger.SetRange"] = { _trigger, { "range", n } },
["Trigger.GetRange"] = { _trigger },
["Trigger.SetUpdateInterval"] = { _trigger, { "updateInterval", n } },
["Trigger.GetUpdateInterval"] = { _trigger },
["Trigger.GetGameObjectsInRange"] = { _trigger },
["Trigger.IsGameObjectInRange"] = { _trigger, _go, { "triggerPosition", "Vector3", isOptional = true } },
} )
--------------------------------------------------------------------------------
-- Language - Localization
Lang = {
dictionariesByLanguage = { english = {} },
cache = {},
gameObjectsToUpdate = {},
doNotCallUpdate = true, -- let that here ! It's read in Daneel.Load() to not include Lang.Update() to the list of functions to be called every frames.
}
Daneel.modules.Lang = Lang
function Lang.DefaultConfig()
return {
default = nil, -- Default language
current = nil, -- Current language
searchInDefault = true, -- Tell whether Lang.Get() search a line key in the default language
-- when it is not found in the current language before returning the value of keyNotFound
keyNotFound = "langkeynotfound", -- Value returned when a language key is not found
}
end
Lang.Config = Lang.DefaultConfig()
function Lang.Load()
local defaultLanguage = nil
for lang, dico in pairs( Lang.dictionariesByLanguage ) do
local llang = lang:lower()
if llang ~= lang then
Lang.dictionariesByLanguage[ llang ] = dico
Lang.dictionariesByLanguage[ lang ] = nil
end
if defaultLanguage == nil then
defaultLanguage = llang
end
end
if defaultLanguage == nil then -- no dictionary found
if Daneel.Config.debug.enableDebug == true then
error("Lang.Load(): No dictionary found in Lang.dictionariesByLanguage !")
end
return
end
if Lang.Config.default == nil then
Lang.Config.default = defaultLanguage
end
Lang.Config.default = Lang.Config.default:lower()
if Lang.Config.current == nil then
Lang.Config.current = Lang.Config.default
end
Lang.Config.current = Lang.Config.current:lower()
end
function Lang.Start()
if Lang.Config.current ~= nil then
Lang.Update( Lang.Config.current )
end
end
--- Get the localized line identified by the provided key.
-- @param key (string) The language key.
-- @param replacements (table) [optional] The placeholders and their replacements.
-- @return (string) The line.
function Lang.Get( key, replacements )
if replacements == nil and Lang.cache[ key ] ~= nil then
return Lang.cache[ key ]
end
local currentLanguage = Lang.Config.current
local defaultLanguage = Lang.Config.default
local searchInDefault = Lang.Config.searchInDefault
local cache = true
local keys = string.split( key, "." )
local language = currentLanguage
if Lang.dictionariesByLanguage[ keys[1] ] ~= nil then
language = table.remove( keys, 1 )
end
local noLangKey = table.concat( keys, "." ) -- rebuilt the key, but without the language
local fullKey = language .. "." .. noLangKey
if replacements == nil and Lang.cache[ fullKey ] ~= nil then
return Lang.cache[ fullKey ]
end
local dico = Lang.dictionariesByLanguage[ language ]
local errorHead = "Lang.Get(key[, replacements]): "
if dico == nil then
error( errorHead.."Language '"..language.."' does not exists", key, fullKey )
end
for i=1, #keys do
local _key = keys[i]
if dico[_key] == nil then
-- key was not found in this language
-- search for it in the default language
if searchInDefault == true and language ~= defaultLanguage then
cache = false
dico = Lang.Get( defaultLanguage.."."..noLangKey, replacements )
else -- already default language or don't want to search in
dico = Lang.Config.keyNotFound or "keynotfound"
end
break
end
dico = dico[ _key ]
-- dico is now a nested table in the dictionary, or a searched string (or the keynotfound string)
end
-- dico should be the searched (or keynotfound) string by now
local line = dico
if type( line ) ~= "string" then
error( errorHead.."Localization key '"..key.."' does not lead to a string but to : '"..tostring(line).."'.", key, fullKey )
end
-- process replacements
if replacements ~= nil then
line = Daneel.Utilities.ReplaceInString( line, replacements )
elseif cache == true and line ~= Lang.Config.keyNotFound then
Lang.cache[ key ] = line -- ie: "greetings.welcome"
Lang.cache[ fullKey ] = line -- ie: "english.greetings.welcome"
end
return line
end
--- Register a game object to update its text renderer whenever the language will be updated by Lang.Update().
-- @param gameObject (GameObject) The gameObject.
-- @param key (string) The language key.
-- @param replacements (table) [optional] The placeholders and their replacements.
function Lang.RegisterForUpdate( gameObject, key, replacements )
Lang.gameObjectsToUpdate[gameObject] = {
key = key,
replacements = replacements,
}
end
--- Update the current language and the text of all game objects that have registered via Lang.RegisterForUpdate(). <br>
-- Fire the OnLangUpdate event.
-- @param language (string) The new current language.
function Lang.Update( language )
language = Daneel.Debug.CheckArgValue( language, "language", table.getkeys( Lang.dictionariesByLanguage ), "Lang.Update(language): " )
Lang.cache = {} -- ideally only the items that do not begins by a language name should be deleted
Lang.Config.current = language
for gameObject, data in pairs( Lang.gameObjectsToUpdate ) do
if gameObject.inner == nil or gameObject.isDestroyed == true then
Lang.gameObjectsToUpdate[ gameObject ] = nil
else
local text = Lang.Get( data.key, data.replacements )
if gameObject.textArea ~= nil then
gameObject.textArea:SetText( text )
elseif gameObject.textRenderer ~= nil then
gameObject.textRenderer:SetText( text )
elseif Daneel.Config.debug.enableDebug then
print( "Lang.Update(language): WARNING : "..tostring( gameObject ).." has no TextRenderer or GUI.TextArea component." )
end
end
end
Daneel.Event.Fire( "OnLangUpdate" )
end
table.mergein( Daneel.Debug.functionArgumentsInfo, {
["Lang.Get"] = { { "key", "string" }, { "replacements", "table", isOptional = true } },
["Lang.RegisterForUpdate"] = { _go, { "key", "string" }, { "replacements", "table", isOptional = true } },
["Lang.Update"] = { { "language", "string" } },
} )
|
local parser = require('cmp_nvim_ultisnips.parser')
describe('parser for grammar', function()
describe('with terminal symbol', function()
it('should match second rule if first one failed', function()
local productions = {
S = {
rhs = { '^%a+', '^%d+'}
}
}
local grammar = { start_symbol = 'S', productions = productions }
local result = parser.parse('123 test', grammar, false)
assert.is_not_nil(result)
local expected = { matches = { '123' }, remaining = ' test' }
assert.are_same(expected, result)
end)
it('should match description regex', function()
local productions = {
S = {
rhs = { '^"[^"]+"' }
}
}
local grammar = { start_symbol = 'S', productions = productions }
local result = parser.parse('"some description"', grammar, false)
assert.is_not_nil(result)
local expected = { matches = { '"some description"' }, remaining = '' }
assert.are_same(expected, result)
end)
it('should not match', function()
local productions = {
S = {
rhs = { '^%d+'}
}
}
local grammar = { start_symbol = 'S', productions = productions }
assert.is_nil(parser.parse('test 123', grammar))
end)
it('should match based on result of verify function', function()
local productions = {
S = {
rhs = { '^%S+' },
verify_matches = function(_, matches)
-- only match when first char is 'x'
return matches[1]:sub(1, 1) == 'x'
end
}
}
local grammar = { start_symbol = 'S', productions = productions }
local actual = parser.parse('xyz', grammar)
assert.is_not_nil(actual)
local expected = { matches = { 'xyz' }, remaining = '' }
assert.are_same(expected, actual)
-- failure case
assert.is_nil(parser.parse('zyx', grammar))
end)
it('should provide captured values in verify function and result table', function()
local captured_rules = {}
local captured_matches = {}
local productions = {
S = {
rhs = { '^X(.*)X', '^M(.*)M A' },
verify_matches = function(rule, matches)
table.insert(captured_rules, rule)
table.insert(captured_matches, matches)
return true
end
},
A = {
rhs = { 'a' }
}
}
local grammar = { start_symbol = 'S', productions = productions }
local actual = parser.parse('Msome str1ngsM arest', grammar, false)
-- one call to verify for the applied rule
assert.are_same({ '^M(.*)M A' }, captured_rules)
assert.are_same({ { 'some str1ngs', 'a' } }, captured_matches)
assert.is_not_nil(actual)
local expected = { matches = { 'some str1ngs', 'a' }, remaining = 'rest' }
assert.are_same(expected, actual)
end)
it('should match based on result of verify function (more complex test)', function()
local productions = {
S = {
rhs = { '^.*' },
verify_matches = function(_, matches)
-- only match when surrounding chars are '!'
local valid = matches[1]:sub(1, 1) == '!' and matches[1]:sub(-1, -1) == '!'
-- it is possible to change the captured value since captures are passed by reference
if valid == true then
matches[1] = matches[1]:sub(2, -2)
end
return valid
end
}
}
local grammar = { start_symbol = 'S', productions = productions }
local actual = parser.parse('!test!', grammar)
assert.is_not_nil(actual)
local expected = { matches = { 'test' }, remaining = '' }
assert.are_same(expected, actual)
end)
it('should provide matches in on_store_matches when verify succeeded', function()
local captured_symbols = {}
local captured_matches = {}
local productions = {
S = {
rhs = { 'A C', 'B C' },
verify_matches = function(rule, _)
-- only allow second rule
return rule == 'B C'
end,
on_store_matches = function(symbols, matches)
table.insert(captured_symbols, symbols)
table.insert(captured_matches, matches)
end
},
A = {
rhs = { 'a' }
},
B = {
rhs = { 'a' }
},
C = {
rhs = { 'c' }
}
}
local grammar = { start_symbol = 'S', productions = productions }
local actual = parser.parse('ac', grammar)
assert.are_same({ { 'B', 'C' } }, captured_symbols)
assert.are_same({ { 'a', 'c' } }, captured_matches)
assert.is_not_nil(actual)
local expected = { matches = { 'a', 'c' }, remaining = '' }
assert.are_same(expected, actual)
end)
end)
describe('with non-terminal symbol', function()
it('should match', function()
local productions = {
S = { rhs = { 'A D' } },
A = { rhs = { 'B C' } },
B = { rhs = { '^b' } },
C = { rhs = { '^c' } },
D = { rhs = { '^d' } }
}
local grammar = { start_symbol = 'S', productions = productions }
local expected = {
matches = {
{ 'b', 'c' }, -- matched by non-terminal A
'd' -- matched by non-terminal D
},
remaining = 'rest'
}
local actual = parser.parse('bcdrest', grammar)
assert.is_not_nil(actual)
assert.are_same(expected, actual)
end)
it('should not match when last non-terminal fails', function()
local productions = {
S = { rhs = { 'A D' } },
A = { rhs = { 'B C' } },
B = { rhs = { '^b' } },
C = { rhs = { '^c' } },
D = { rhs = { '^d' } }
}
local grammar = { start_symbol = 'S', productions = productions }
assert.is_nil(parser.parse('bc!rest', grammar))
end)
end)
end)
describe('parser for', function()
describe('snippet header', function()
it('should match tab_trigger including quotes when no r option or multiword trigger', function()
local result = parser.parse_snippet_header('"snip"')
local expected = {
tab_trigger = '"snip"'
}
assert.are_same(expected, result)
end)
it('should match multiword tab-trigger surrounded with "!"', function()
local result = parser.parse_snippet_header('!"some" trigger! "a description"')
local expected = {
description = 'a description',
tab_trigger = '"some" trigger'
}
assert.are_same(expected, result)
end)
it('should match quoted tab_trigger, description, options', function()
local result = parser.parse_snippet_header('"tab - trigger" "some description" options')
local expected = {
options = 'options',
description = 'some description',
tab_trigger = 'tab - trigger'
}
assert.are_same(expected, result)
end)
it('should remove surrounding from tab_trigger when regex option is provided', function()
local result = parser.parse_snippet_header('|^(foo|bar)$| "" r')
local expected = {
options = 'r',
description = '',
tab_trigger = '^(foo|bar)$'
}
assert.are_same(expected, result)
end)
it('should not remove surrounding from tab_trigger when regex option is not provided', function()
local result = parser.parse_snippet_header('|^(foo|bar)$| "" ba')
local expected = {
options = 'ba',
description = '',
-- keep surrounding '|'
tab_trigger = '|^(foo|bar)$|'
}
assert.are_same(expected, result)
end)
it('should match options with "!"', function()
local result = parser.parse_snippet_header('test "description" b!')
local expected = {
options = 'b!',
description = 'description',
tab_trigger = 'test'
}
assert.are_same(expected, result)
end)
it('should match options with expression', function()
local result = parser.parse_snippet_header('trigger "d" "expr" be')
local expected = {
options = 'be',
expression = 'expr',
description = 'd',
tab_trigger = 'trigger'
}
assert.are_same(expected, result)
-- failure case
assert.are_same({}, parser.parse_snippet_header('trigger "d" "expr" br'))
end)
it('should not match invalid multiword tab-trigger', function()
local result = parser.parse_snippet_header('invalid multiword-trigger "description"')
assert.are_same({}, result)
end)
it('should not cause exception for snippet with trailing spaces (#23)', function()
local result = parser.parse_snippet_header('func "Function Header" ')
assert.are_same({}, result)
end)
it('should match tab-trigger containing dot', function()
local result = parser.parse_snippet_header('j.u')
local expected = {
tab_trigger = 'j.u'
}
assert.are_same(expected, result)
end)
it('should match tab_trigger with less than 3 chars', function()
local result = parser.parse_snippet_header('c "Constructor" b')
local expected = {
tab_trigger = 'c',
description = 'Constructor',
options = 'b'
}
assert.are_same(expected, result)
end)
end)
end)
|
print("CTEST_FULL_OUTPUT")
local vec = osg.Vec3d(5, 5, 5)
local vec2 = osg.Vec3d(52, 25, 52)
local mat = osg.Matrix.scale(vec)
print(mat.Scale)
assert(vec == mat.Scale)
mat.Trans = vec2
print(mat.Trans)
assert(vec2 == mat.Trans)
assert(vec == mat.Scale)
require("help")
help(mat)
help(osg.Group())
print("Done!")
|
local Player = {}
Player.players = {}
Player.alive = {}
Player.playerCount = 0
Player.aliveCount = 0
Player.__index = Player
Player.__tostring = function(self)
return table.tostring(self)
end
setmetatable(Player, {
__call = function (cls, name)
return cls.new(name)
end,
})
function Player.new(name)
local self = setmetatable({}, Player)
self.name = name
self.alive = false
self.lives = 0
self.inCooldown = true
self.community = tfm.get.room.playerList[name].community
self.hearts = {}
self.rounds = 0
self.survived = 0
self.won = 0
self.score = 0
self.points = 0
self.packs = 1
self.packsArray = {}
self.equipped = 1
self.tempEquipped = nil
self.openedWindow = nil
for key, code in next, keys do system.bindKeyboard(name, code, true, true) end
Player.players[name] = self
Player.playerCount = Player.playerCount + 1
return self
end
function Player:refresh()
self.alive = true
self.inCooldown = false
self:setLives(3)
if not Player.alive[self.name] then
Player.alive[self.name] = self
Player.aliveCount = Player.aliveCount + 1
end
setNameColor(self.name)
self.tempEquipped = nil
end
function Player:setLives(lives)
self.lives = lives
tfm.exec.setPlayerScore(self.name, lives)
for _, id in next, self.hearts do tfm.exec.removeImage(id) end
self.hearts = {}
local heartCount = 0
while heartCount < lives do
heartCount = heartCount + 1
self.hearts[heartCount] = tfm.exec.addImage(assets.heart, "$" .. self.name, -45 + heartCount * 15, -45)
end
end
function Player:shoot(x, y)
if newRoundStarted and self.alive and not self.inCooldown then
if self.equipped == "Random" and not self.tempEquipped then
self.tempEquipped = #self.packsArray == 0 and "Default" or self.packsArray[math.random(#self.packsArray)]
end
self.inCooldown = true
local stance = self.stance
local pos = getPos(currentItem, stance)
local rot = getRot(currentItem, stance)
local xSpeed = currentItem == 34 and 60 or 40
local object = tfm.exec.addShamanObject(
currentItem,
x + pos.x,
y + pos.y,
rot,
stance == -1 and -xSpeed or xSpeed,
0,
currentItem == 32 or currentItem == 62
)
local equippedPackName = self.tempEquipped or self.equipped
local equippedPack = shop.packs[equippedPackName]
local skin = equippedPack.skins[currentItem]
if (equippedPackName ~= "Default" and equippedPackName ~= "Random") and skin and skin.image then
tfm.exec.addImage(
skin.image,
"#" .. object,
skin.adj.x,
skin.adj.y
)
end
Timer("shootCooldown_" .. self.name, function(object)
tfm.exec.removeObject(object)
self.inCooldown = false
end, 1500, false, object)
end
end
function Player:die()
self.lives = 0
self.alive = false
tfm.exec.chatMessage(translate("LOST_ALL", self.community), self.name)
if statsEnabled then
self.rounds = self.rounds + 1
self:savePlayerData()
end
if Player.alive[self.name] then
Player.alive[self.name] = nil
Player.aliveCount = Player.aliveCount - 1
end
if Player.aliveCount == 1 then
local winner = next(Player.alive)
local winnerPlayer = Player.players[winner]
local n, t = extractName(winner)
tfm.exec.chatMessage(translate("SOLE", tfm.get.room.community, nil, {player = "<b><VI>" .. n .. "</VI><font size='8'><N2>" .. t .. "</N2></font></b>"}))
tfm.exec.giveCheese(winner)
tfm.exec.playerVictory(winner)
if statsEnabled then
winnerPlayer.rounds = winnerPlayer.rounds + 1
winnerPlayer.survived = winnerPlayer.survived + 1
winnerPlayer.won = winnerPlayer.won + 1
winnerPlayer.points = winnerPlayer.points + 5
winnerPlayer:savePlayerData()
end
Timer("newRound", newRound, 3 * 1000)
elseif Player.aliveCount == 0 then
Timer("newRound", newRound, 3 * 1000)
end
end
function Player:savePlayerData()
-- if tfm.get.room.uniquePlayers < MIN_PLAYERS then return end
local name = self.name
dHandler:set(name, "rounds", self.rounds)
dHandler:set(name, "survived", self.survived)
dHandler:set(name, "won", self.won)
dHandler:set(name, "points", self.points)
dHandler:set(name, "packs", shop.packsBitList:encode(self.packs))
dHandler:set(name, "equipped", self.equipped == "Random" and -1 or shop.packsBitList:find(self.equipped))
system.savePlayerData(name, "v2" .. dHandler:dumpPlayer(name))
end
|
local path = require "path"
local date = require "date"
local function older_then(days)
local now = date()
return function (fname, ftime)
return days <= date.diff(now, date(ftime):tolocal()):spandays()
end
end
local function old_files_(mask, days, cmd)
assert(days)
assert(cmd)
-- признак того что в директории есть файлы не поподающие под фильтр
local has_more_files = false
local filter = older_then(days)
local last_fname, last_fdate
path.each{file = mask, param = 'ft',
recurse=false, skipdirs=true,
callback =
function(fname, ftime)
if filter(fname, ftime) then
if not last_fdate then -- первый попавшийся файл
last_fname, last_fdate = fname, date(ftime)
return
end
-- перед этим уже бал найден файл
local next_fname, next_fdate = fname, date(ftime)
-- находим самый "старый" файл
if last_fdate < next_fdate then
last_fdate, next_fdate = next_fdate, last_fdate
last_fname, next_fname = next_fname, last_fname
end
cmd(next_fname, false)
else
-- в директории есть файлы которые поподают под маску и не поподают под фильтр
has_more_files = true
end
end}
if last_fname then cmd(last_fname, not has_more_files) end
end
--
-- @param mask - если первый символ '!', то поиск производится рекурсивно
-- @param days - количество дней после создания после которого файл считается старым
-- @param cmd - команда обработки файла. В нее передается полный путь файла и
-- признак того что файл является последним который подподает под маску в данной директории.
-- Гарантируется что если это последний файл, то он имеет самую позднюю дату (самый "свежий")
local function walk_old_files(mask, days, cmd)
local is_recurse = mask:sub(1,1) == '!'
if is_recurse then mask = mask:sub(2) end
old_files_(mask, days, cmd)
if not is_recurse then return end
local dir_mask, file_mask = path.splitpath(mask)
path.each{file = path.join(dir_mask, '*.*'),
recurse=true, skipdirs=false, skipfiles=true,
callback= function(fname)
if path.isdir(fname) then
old_files_(path.join(fname, file_mask), days, cmd)
end
end
}
end
return walk_old_files |
require "Assets.LuaScripts.Modulus.Common.Define.Define"
require "Assets.LuaScripts.Modulus.Common.Cmd.__init"
require "Assets.LuaScripts.Modulus.Common.TransClass.TransClass"
require "Assets.LuaScripts.Modulus.Common.Utils.Utils" |
local BaseLoginDialog = require("hall/login/widget/baseLoginDialog");
local login_regAccount_psdVerify_close = require("view/kScreen_1280_800/hall/login/login_regAccount_psdVerify_close");
--(注册)密码验证提示
local RegisterAccountVerifyCloseDialog = class(BaseLoginDialog,false);
local h_index = 0;
local getIndex = function(self)
h_index = h_index + 1;
return h_index;
end
RegisterAccountVerifyCloseDialog.s_controls =
{
closeBtn = getIndex();
leftBtn = getIndex();
rightBtn = getIndex();
bg = getIndex();
maskView = getIndex();
};
RegisterAccountVerifyCloseDialog.ctor = function(self,data)
super(self,login_regAccount_psdVerify_close);
self.m_data = data;
self.m_ctrls = RegisterAccountVerifyCloseDialog.s_controls;
self:findViewById(self.m_ctrls.closeBtn):setVisible( not kLoginDataInterface:isForbidLogin() );
end
RegisterAccountVerifyCloseDialog.dtor = function(self)
self.m_data = nil;
end
---------------------------------------------------------------------
----------------- Button event response functions -------------------
---------------------------------------------------------------------
RegisterAccountVerifyCloseDialog.onCloseClick = function(self)
Log.d("-------------RegisterAccountVerifyCloseDialog onCloseClick------------");
RegisterAccountVerifyCloseDialog.hide();
end
RegisterAccountVerifyCloseDialog.onLeftClick = function(self)
Log.d("-------------RegisterAccountVerifyCloseDialog onLeftClick A------------");
RegisterAccountVerifyCloseDialog.hide();
local RegisterAccountVerifyDialog = require("hall/login/widget/registerAccountVerifyDialog");
RegisterAccountVerifyDialog.hide();
end
RegisterAccountVerifyCloseDialog.onRightClick = function(self)
Log.d("-------------RegisterAccountVerifyCloseDialog onRightClick A------------");
RegisterAccountVerifyCloseDialog.hide();
end
RegisterAccountVerifyCloseDialog.onBgClick = function(self)
end
RegisterAccountVerifyCloseDialog.onMaskTouch = function(self , finger_action , x , y, drawing_id_first , drawing_id_current)
end
---------------------------------------------------------------------------------
RegisterAccountVerifyCloseDialog.show = function(...)
RegisterAccountVerifyCloseDialog.hide(true);
RegisterAccountVerifyCloseDialog.s_instance = new(RegisterAccountVerifyCloseDialog , ...);
RegisterAccountVerifyCloseDialog.s_instance:addToRoot();
RegisterAccountVerifyCloseDialog.s_instance:setFillParent(true,true);
-- RegisterAccountVerifyCloseDialog.s_instance:setLevel(15);
return RegisterAccountVerifyCloseDialog.s_instance;
end
RegisterAccountVerifyCloseDialog.hide = function()
delete(RegisterAccountVerifyCloseDialog.s_instance);
RegisterAccountVerifyCloseDialog.s_instance = nil;
end
---------------------------------------------------------------------------------
RegisterAccountVerifyCloseDialog.s_controlConfig =
{
[RegisterAccountVerifyCloseDialog.s_controls.closeBtn] = {"contentView","closeBtn"};
[RegisterAccountVerifyCloseDialog.s_controls.leftBtn] = {"contentView","bottomView","subView","tryAgainBtn"};
[RegisterAccountVerifyCloseDialog.s_controls.rightBtn] = {"contentView","bottomView","subView","fillByHandBtn"};
[RegisterAccountVerifyCloseDialog.s_controls.bg] = {"contentView","bg"};
[RegisterAccountVerifyCloseDialog.s_controls.maskView] = {"shiled"};
};
RegisterAccountVerifyCloseDialog.s_controlFuncMap =
{
[RegisterAccountVerifyCloseDialog.s_controls.closeBtn] = RegisterAccountVerifyCloseDialog.onCloseClick;
[RegisterAccountVerifyCloseDialog.s_controls.leftBtn] = RegisterAccountVerifyCloseDialog.onLeftClick;
[RegisterAccountVerifyCloseDialog.s_controls.rightBtn] = RegisterAccountVerifyCloseDialog.onRightClick;
[RegisterAccountVerifyCloseDialog.s_controls.bg] = RegisterAccountVerifyCloseDialog.onBgClick;
[RegisterAccountVerifyCloseDialog.s_controls.maskView] = RegisterAccountVerifyCloseDialog.onMaskTouch;
};
return RegisterAccountVerifyCloseDialog |
name "github.com/lemonkit/lemon" -- package name
plugin "github.com/gsmake/clang"
properties.clang = {
["lemon"] = {
path = ".";
type = "static";
config = "config.cmake"; -- the cmake config file
test_dependencies = {};
};
}
|
EditCtrl = relative_import('edit_utils').create_edit_class(nil, 'editor/edit/uieditor_edit_callback_btn')
--点击
function EditCtrl:on_init_ui()
self.btn.OnClick = function()
if self._editCallback then
self._editCallback()
end
end
if self._validateParm and self._validateParm['edit_name'] then
self.btn:SetString(self._validateParm['edit_name'])
end
end
function EditCtrl:on_update_data()
end |
return {
TextSize = 14,
Font = Enum.Font.Gotham,
HeaderTextSize = 18,
HeaderFont = Enum.Font.GothamBlack,
Padding = 16,
BigPadding = 24,
}
|
package.path = package.path .. ";./common/?.lua"
-- print(package.path)
-- print(package.cpath)
local tor2url = require("torrent_to_magnet")
print(tor2url.torrent_to_magnet("./moli.torrent"))
|
fx_version 'bodacious'
game 'gta5'
|
--[[------------------------------------------------------
lk.Properties
-------------
Storage with notification on change.
--]]------------------------------------------------------
require 'lubyk'
local should = test.Suite('lk.Properties')
function should.createPropOnNewPropertiesAccessor()
local node = {}
local prop = lk.Properties(node)
assertTrue(node.prop)
end
function should.declarePropertiesWithNodeProperty()
local node = {}
local prop = lk.Properties(node)
node:property('foo', 'this is foo')
assertEqual(node.prop.properties.foo.info, 'this is foo')
end
function should.triggerCallbackIfExists()
local node = {}
local prop = lk.Properties(node)
node:property('foo', 'this is foo')
function node:foo(value) return value + 1; end
prop.foo = 3
assertEqual(4, prop.foo)
end
function should.notRaiseAnErrorOnMissingCallback()
local node = {}
local prop = lk.Properties(node)
node:property('foo', 'this is foo')
prop.foo = 3
assertEqual(3, prop.foo)
end
function should.raiseAnErrorOnInvalidProperty()
local node = {}
local prop = lk.Properties(node)
assertError('Unknown property bar', function()
prop.bar = 4
end)
end
function should.connectPropertiesOnConnect()
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
nodeA:connect('foo', nodeB, 'bar')
-- nodeA.foo ---> nodeB.bar
propA.foo = 4
assertEqual(4, propB.bar)
end
function should.notConnectPropertiesOnMultipleConnect()
local callCount = 0
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
function nodeB:bar(value)
callCount = callCount + 1
return value
end
nodeA:connect('foo', nodeB, 'bar')
nodeA:connect('foo', nodeB, 'bar')
-- nodeA.foo ---> nodeB.bar
propA.foo = 4
assertEqual(4, propB.bar)
assertEqual(1, callCount)
end
function should.disconnectPropOnDisconnect()
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
nodeB:property('baz', 'this is baz')
nodeA:connect('foo', nodeB, 'bar')
nodeA:connect('foo', nodeB, 'baz')
nodeA:disconnect('foo', nodeB, 'bar')
-- nodeA.foo ---> nodeB.bar
propA.foo = 4
assertEqual(nil, propB.bar)
assertEqual(4, propB.baz)
end
function should.disconnectAllOnDisconnectWithoutPropName()
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
nodeB:property('baz', 'this is baz')
nodeA:connect('foo', nodeB, 'bar')
nodeA:connect('foo', nodeB, 'baz')
nodeA:disconnect('foo', nodeB)
-- nodeA.foo ---> nodeB.bar
propA.foo = 4
assertEqual(nil, propB.bar)
assertEqual(nil, propB.baz)
end
function should.disconnectAllOnDisconnectWithoutSrcPropName()
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
nodeB:property('baz', 'this is baz')
nodeA:connect('foo', nodeB, 'bar')
nodeA:connect('foo', nodeB, 'baz')
nodeA:disconnect(nodeB)
-- nodeA.foo ---> nodeB.bar
propA.foo = 4
assertEqual(nil, propB.bar)
assertEqual(nil, propB.baz)
end
function should.triggerCallbackBeforeSending()
local nodeA = {}
local propA = lk.Properties(nodeA)
nodeA:property('foo', 'this is foo')
local nodeB = {}
local propB = lk.Properties(nodeB)
nodeB:property('bar', 'this is bar')
nodeA:connect('foo', nodeB, 'bar')
-- nodeA.foo ---> nodeB.bar
function nodeA:foo(value)
assertEqual(nil, propB.bar)
return value + 1
end
propA.foo = 4
assertEqual(5, propB.bar)
end
function should.connectToAnyMethod()
local node = {}
local prop = lk.Properties(node)
node:property('foo', 'this is foo')
local data = {}
local function changeData(data, idx, value)
data[idx] = value
end
node:connect('foo', changeData, data, 'tada')
-- nodeA.foo ---> changeData(data, 'tada', value)
assertEqual(nil, data['tada'])
prop.foo = 4
assertEqual(4, data['tada'])
end
test.all() |
include("shared.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
function ENT:SpawnDebris(mdl)
local e = ents.Create("prop_physics")
e:SetPos(self:GetPos() + VectorRand() * 150)
e:SetModel(mdl)
e:Spawn()
local phys = e:GetPhysicsObject()
phys:ApplyForceCenter(VectorRand() * 320000)
phys:AddAngleVelocity(VectorRand() * 2000)
if math.random(1, 3) == 1 then e:Ignite(30) end
return e
end
function ENT:Initialize()
self.BaseClass.Initialize(self)
self:AddHook("DroneDestroyed", "drone_destroyed", function()
local ef = EffectData()
ef:SetOrigin(self:GetPos())
util.Effect("dronesrewrite_explosionbig", ef)
for i = 1, 4 do
local e = self:SpawnDebris("models/dronesrewrite/skyartillery/deb1/deb1.mdl")
e:SetAngles(Angle(0, 90 * i, 0))
end
self:SpawnDebris("models/dronesrewrite/skyartillery/deb2/deb1.mdl")
self:SpawnDebris("models/dronesrewrite/skyartillery/deb3/deb1.mdl")
self:SpawnDebris("models/dronesrewrite/skyartillery/deb4/deb1.mdl")
self:SpawnDebris("models/dronesrewrite/skyartillery/deb5/deb1.mdl")
util.ScreenShake(self:GetPos(), 30, 2, 5, 20000)
self:Remove()
end)
end |
return {
["sprite path"] = "sprite path",
["right upperarm"] = "右 上腕",
["neck"] = "首",
["size y"] = "Y軸のサイズ",
["draw shadow"] = "影を表示",
["copy"] = "コピー",
["start size"] = "開始 サイズ",
["clip"] = "クリップ",
["size"] = "サイズ",
["reset view"] = "カメラをリセット",
["right calf"] = "右 ふくらはぎ",
["effect"] = "エフェクト",
["max"] = "最大",
["angles"] = "角度",
["left foot"] = "左 足",
["font"] = "フォント",
["wear"] = "着用",
["load"] = "読み込み",
["bodygroup state"] = "ボディグループ ステータス",
["size x"] = "X軸のサイズ",
["relative bones"] = "relative bones",
["scale"] = "スケール",
["follow"] = "follow",
["outline color"] = "アウトラインの色",
["left thigh"] = "左 太もも",
["bone"] = "骨",
["invert"] = "反転",
["double face"] = "両面",
["clear"] = "全消去",
["right forearm"] = "右 前腕",
["left hand"] = "左 手",
["left upperarm"] = "左 上腕",
["false"] = "無効",
["alpha"] = "透過度",
["use lua"] = "Luaを使用",
["sprite"] = "sprite",
["my outfit"] = "自分の衣装",
["right hand"] = "右 手",
["angle velocity"] = "回転速度",
["right clavicle"] = "右 鎖骨",
["outline"] = "概要",
["string"] = "文字列",
["left clavicle"] = "左 鎖骨",
["color"] = "色",
["save"] = "保存",
["parent name"] = "親の名前",
["toggle t pose"] = "Tポーズのトグル",
["outline alpha"] = "アウトラインの透過度",
["remove"] = "削除",
["spine 4"] = "脊椎 4",
["skin"] = "スキン",
["command"] = "コマンド",
["material"] = "マテリアル",
["sound"] = "音",
["fullbright"] = "明るさの最大化",
["true"] = "有効",
["spine 2"] = "脊椎 2",
["bone merge"] = "骨 統合",
["animation"] = "アニメーション",
["spine 1"] = "脊椎 1",
["text"] = "テキスト",
["rate"] = "速度",
["operator"] = "operator",
["spine"] = "脊椎",
["loop"] = "繰り返し",
["clone"] = "複製",
["position"] = "位置",
["model"] = "モデル",
["sequence name"] = "シーケンス名",
["left toe"] = "左 つま先",
["pelvis"] = "骨盤",
["pitch"] = "ピッチ",
["right toe"] = "右 つま先",
["right finger 2"] = "右 指 2",
["add parts to me!"] = "add parts to me!",
["group"] = "グループ",
["right foot"] = "右 足",
["aim part name"] = "aim part name",
["left calf"] = "左 ふくらはぎ",
["rotate origin"] = "回転の原点",
["trail path"] = "trail path",
["reset eye angles"] = "目の角度をリセット",
["volume"] = "音量",
["entity"] = "エンティティ",
["modify"] = "編集",
["draw weapon"] = "武器を表示",
["hide"] = "隠す",
["length"] = "長さ",
["offset"] = "オフセット",
["owner name"] = "所有者名",
["head"] = "頭",
["bodygroup"] = "ボディグループ",
["brightness"] = "明るさ",
["eye angles"] = "目の角度",
["event"] = "イベント",
["trail"] = "trail",
["arguments"] = "引数",
["name"] = "名前",
["right thigh"] = "右 太もも",
["ping pong loop"] = "ping pong loop",
["min"] = "最小",
["left forearm"] = "左 腕",
["light"] = "ライト",
} |
function Strawman_Burning_Straw(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(31075, Unit:GetClosestPlayer())
end
function Strawman_Brain_Bash(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(31046, Unit:GetClosestPlayer())
end
function Strawman(Unit, event, miscUnit, misc)
Unit:RegisterEvent("Strawman_Burning_Straw", 10000, 0)
Unit:RegisterEvent("Strawman_Brain_Bash", 17000, 0)
end
RegisterUnitEvent(17543, 1, "Strawman")
--[[Strawman yells: Don't let them make... a mattress outta' me.
Strawman yells: Now what should I do with you? I simply can't make up my mind.]] |
---
-- @module ItemStack
--
-- ------------------------------------------------
-- Required Modules
-- ------------------------------------------------
local Class = require( 'lib.Middleclass' )
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local ItemStack = Class( 'ItemStack' )
-- ------------------------------------------------
-- Public Methods
-- ------------------------------------------------
function ItemStack:initialize( id )
if not id or type( id ) ~= 'string' then
error( 'Expected a parameter of type "string".' )
end
self.id = id
self.items = {}
end
function ItemStack:addItem( item )
assert( item:getID() == self.id, 'ID doesn\'t fit the stack' )
self.items[#self.items + 1] = item
return true
end
function ItemStack:removeItem( item )
for i = 1, #self.items do
if self.items[i] == item then
table.remove( self.items, i )
return true
end
end
return false
end
function ItemStack:getWeight()
local weight = 0
for i = 1, #self.items do
weight = weight + self.items[i]:getWeight()
end
return weight
end
function ItemStack:getVolume()
local volume = 0
for i = 1, #self.items do
volume = volume + self.items[i]:getVolume()
end
return volume
end
function ItemStack:split()
if #self.items > 1 then
local count = math.floor( #self.items * 0.5 )
local newStack = ItemStack( self.id )
for i = 1, count do
newStack:addItem( self.items[i] )
self:removeItem( self.items[i] )
end
return newStack
end
return self
end
function ItemStack:serialize()
local t = {
['ItemStack'] = true,
['id'] = self.id,
['items'] = {}
}
for i = 1, #self.items do
t['items'][i] = self.items[i]:serialize()
end
return t
end
function ItemStack:isSameType( itemType, subType )
return self.items[#self.items]:isSameType( itemType, subType )
end
function ItemStack:getItem()
return self.items[#self.items]
end
function ItemStack:getItems()
return self.items
end
function ItemStack:getItemType()
return self.items[#self.items]:getItemType()
end
function ItemStack:getSubType()
return self.items[#self.items]:getSubType()
end
function ItemStack:getDescriptionID()
return self.items[#self.items]:getDescriptionID()
end
function ItemStack:getID()
return self.id
end
function ItemStack:getItemCount()
return #self.items
end
function ItemStack:isEmpty()
return #self.items == 0
end
return ItemStack
|
local model={}
local base_model=torch.reload("../../../Atten/data")
setmetatable(model,{ __index = base_model })
function model:GenerateSample()
self.mode="decoding"
self.sample_target=self:sample()
self.Words_sample,self.Masks_sample,self.Left_sample,self.Padding_sample=self.Data:get_batch(self.sample_target,false)
self.Words_sample=self.Words_sample:cuda()
self.Padding_sample=self.Padding_sample:cuda()
end
function model:Initial(params)
self.Data:Initial(params)
self.params=params;
self.lstm_source =self:lstm_source_()
self.lstm_target =self:lstm_target_()
self.softmax =self:softmax_()
self.Modules={}
self.Modules[#self.Modules+1]=self.lstm_source
self.Modules[#self.Modules+1]=self.lstm_target;
self.Modules[#self.Modules+1]=self.softmax;
self.lstms_s=self:g_cloneManyTimes(self.lstm_source,self.params.source_max_length)
self.lstms_t=self:g_cloneManyTimes(self.lstm_target,self.params.target_max_length)
self.store_s={}
self.store_t={}
self:readModel()
self.mode="test"
--self:test()
self.mode="decoding"
end
function model:Integrate()
self.Word_t=self.Words_sample;
self.Mask_t=self.Masks_sample
self.Left_t=self.Left_sample
self.Padding_t=self.Padding_sample
--[[
self.Word_s=torch.cat(self.Word_s,self.Word_s,1)
local max_word_t=math.max(self.Word_t:size(2),self.Words_sample:size(2))
Word_t=torch.Tensor(self.Word_t:size(1)*2,max_word_t)
Word_t:sub(1,self.Word_t:size(1),1,self.Word_t:size(2)):copy(self.Word_t)
Word_t:sub(self.Word_t:size(1)+1,self.Word_t:size(1)+self.Words_sample:size(1),1,self.Words_sample:size(2)):copy(self.Words_sample);
self.Word_t=Word_t;
self.Padding_s=torch.cat(self.Padding_s,self.Padding_s,1)
local self.Padding_t=torch.Tensor(Word_t:size()):fill(0):cuda()
for i=1,#self.target do
self.Padding_t:sub(i,i,1,self.target:size(2)):fill(1);
end
for i=1,#self.sample_target do
self.Padding_t:sub(i+#self.target,i+#self.target,1,self.sample_target:size(2)):fill(1)
end
self.Mask_s={}
self.Mask_t={}
self.Left_s={}
self.Left_t={}
for i=1,self.Padding_s:size(2)do
self.Mask_s[i]=torch.LongTensor(torch.find(self.Padding_s:sub(1,-1,i,i),0))
self.Left_s[i]=torch.LongTensor(torch.find(self.Padding_s:sub(1,-1,i,i),1))
end
for i=1,self.Padding_t:size(2)do
self.Mask_t[i]=torch.LongTensor(torch.find(self.Padding_t:sub(1,-1,i,i),0))
self.Left_t[i]=torch.LongTensor(torch.find(self.Padding_t:sub(1,-1,i,i),1))
end
--]]
end
function model:model_backward(batch_n)
local d_source=torch.zeros(self.context:size(1),self.context:size(2),self.context:size(3)):cuda();
local d_output={};
for ll=1,self.params.layers do
table.insert(d_output,torch.zeros(self.Word_s:size(1),self.params.dimension):cuda());
table.insert(d_output,torch.zeros(self.Word_s:size(1),self.params.dimension):cuda());
end
local sum_err=0;
local total_num=0;
for t=self.Word_t:size(2)-1,1,-1 do
local current_word=self.Word_t:select(2,t+1);
local softmax_output=self.softmax:forward({self.softmax_h[t],current_word});
local err=softmax_output[1];
sum_err=sum_err+err[1]
total_num=total_num+self.Left_t[t+1]:size(1);
if self.mode=="train" then
local d_pred=torch.Tensor(softmax_output[2]:size()):fill(0):cuda()
for i=1,self.Word_t:size(1) do
if i>d_pred:size(1) or current_word[i]>d_pred:size(2) or i>self.reward:size(1) then
print(i,current_word[i])
print(d_pred:size())
print(self.reward:size())
end
if batch_n==28 then
print("i")
print(i)
print(self.reward)
print(current_word)
end
if self.Padding_t[i][t+1]==1 then
d_pred[i][current_word[i]]=self.reward[i]
end
end
local dh=self.softmax:backward({self.softmax_h[t],current_word},{torch.Tensor({0}),d_pred})
d_store_t=self:clone_(d_output);
table.insert(d_store_t,dh[1])
local now_input={};
if t~=1 then
now_input=self:clone_(self.store_t[t-1]);
else
now_input=self:clone_(self.store_s[self.Word_s:size(2)]);
end
table.insert(now_input,self.context);
table.insert(now_input,self.Word_t:select(2,t));
table.insert(now_input,self.Padding_s);
local now_d_input=self.lstms_t[t]:backward(now_input,d_store_t);
if self.Mask_t[t]:nDimension()~=0 then
for i=1,2*self.params.layers+2 do
now_d_input[i]:indexCopy(1,self.Mask_t[t],torch.zeros(self.Mask_t[t]:size(1),self.params.dimension):cuda())
end
end
d_output={};
for i=1,2*self.params.layers do
d_output[i]=self:copy(now_d_input[i])
end
d_source:add(now_d_input[2*self.params.layers+1]);
end
if self.mode=="train" then
for t=self.Word_s:size(2),1,-1 do
local now_input={}
if t~=1 then
now_input=self:clone_(self.store_s[t-1])
else
for ll=1,self.params.layers do
table.insert(now_input,torch.zeros(self.Word_s:size(1),self.params.dimension):cuda());
table.insert(now_input,torch.zeros(self.Word_s:size(1),self.params.dimension):cuda());
end
end
table.insert(now_input,self.Word_s:select(2,t));
d_output[2*self.params.layers-1]:add(d_source[{{},t,{}}])
local d_now_output=self.lstms_s[t]:backward(now_input,d_output);
if self.Mask_s[t]:nDimension()~=0 then
for i=1,#d_now_output-1 do
d_now_output[i]:indexCopy(1,self.Mask_s[t],torch.zeros(self.Mask_s[t]:size(1),self.params.dimension):cuda())
end
end
d_output={}
for i=1,2*self.params.layers do
d_output[i]=self:copy(d_now_output[i])
end
end
end
end
return sum_err,total_num
end
return model
|
-- if
-- [ 0 为 true ]
if(0)
then
print("0 为 true")
end
-- if else
--[ 定义变量 --]
a = 100;
--[ 检查条件 --]
if( a < 20 )
then
--[ if 条件为 true 时执行该语句块 --]
print("a 小于 20" )
else
--[ if 条件为 false 时执行该语句块 --]
print("a 大于 20" )
end
print("a 的值为 :", a)
-- if...elseif...else
--[ 定义变量 --]
a = 100
--[ 检查布尔条件 --]
if( a == 10 )
then
--[ 如果条件为 true 打印以下信息 --]
print("a 的值为 10" )
elseif( a == 20 )
then
--[ if else if 条件为 true 时打印以下信息 --]
print("a 的值为 20" )
elseif( a == 30 )
then
--[ if else if condition 条件为 true 时打印以下信息 --]
print("a 的值为 30" )
else
--[ 以上条件语句没有一个为 true 时打印以下信息 --]
print("没有匹配 a 的值" )
end
print("a 的真实值为: ", a )
|
local flag = true
local count = 0
local lTime = GetTime()
local prevTime = 0
local xp = UnitXP("player")
local xpPrev = 0
local xpMax = UnitXPMax("player")
MyAddon = LibStub("AceAddon-3.0"):NewAddon("OmegaSTATS", "AceConsole-3.0")
MyAddon:Print(string.format("Hail "..UnitName("player").."! Type \'|cFFFFFF33/gs|r\' to toggle STATS"))
SLASH_MURF1 = "/murf"
SLASH_MURF2 = "/moyf"
function SlashCmdList.MURF(msg)
if string.lower(msg) == "on" then
DEFAULT_CHAT_FRAME:AddMessage("<murf stats ON>",1,.75,.18)
flag = true
elseif string.lower(msg) == "off" then
DEFAULT_CHAT_FRAME:AddMessage("<murf stats OFF>",1,.75,.18)
flag = false
elseif string.lower(msg) == "reset" then
DEFAULT_CHAT_FRAME:AddMessage("<count RESET>",1,.75,.18)
count = 0
else
DEFAULT_CHAT_FRAME:AddMessage("<command not recognized>",1,.75,.18)
end
end
-- #####################################################
-- Storage variables
local Stats1Value = 0
local Stats2Value = 0
local Stats3Value = 0
-- A function for creating display strings
local function DisplayString(parent)
local f = parent:CreateFontString(nil, "OVERLAY")
f:SetFont("Fonts/ARIALN.TTF", 12)
f:SetJustifyH("LEFT")
f:SetJustifyV("TOP")
return f
end
-- Create a basic frame you can drag around the screen
local f = CreateFrame("Frame", "GreyhavenStats", UIParent)
f:SetBackdrop({ bgFile = "Interface/DialogFrame/UI-DialogBox-Background-Dark", edgeFile = "", tile = true, edgeSize = 32, tileSize = 32, insets = { left = 0, right = 0, top = 0, bottom = 0, }, })
f:SetSize(200, 100) -- adjust the size as required.
f:SetPoint("LEFT", 20, 0)
f:SetMovable(true)
f:SetClampedToScreen(true)
f:EnableMouse(true)
f:RegisterForDrag("LeftButton")
f:SetUserPlaced()
f:SetScript("OnDragStart", function(self) self:StartMoving() end)
f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing() end)
-- Add a close button if you like
-- (frametype, framename, parentframe, inheritsframe)
f.close = CreateFrame("Button", "$parentClose", f, "UIPanelCloseButton")
f.close:SetSize(24, 24)
f.close:SetPoint("TOPRIGHT")
f.close:SetScript("OnClick", function(self) self:GetParent():Hide() end)
-- Experiment adding a reset button
f.reset = CreateFrame("Button", "ResetButton", f, "UIPanelButtonTemplate")
f.reset:SetSize(80,24)
f.reset:SetPoint("BOTTOMLEFT")
f.reset:SetText("Reset Kills")
f.reset:SetScript("OnClick", function(self)
MyAddon:Print("Count Reset")
count = 0
end)
-- Place some display strings.
f.Title = DisplayString(f)
f.Title:SetTextColor(0.5, 0.5, 0.5)
f.Title:SetPoint("TOPLEFT", 3, -3)
f.Title:SetPoint("TOPRIGHT", -3, -3)
f.Stats1 = DisplayString(f)
f.Stats1:SetPoint("TOPLEFT", f.Title, "BOTTOMLEFT", 0, -8)
f.Stats1:SetPoint("TOPRIGHT", f.Title, "BOTTOMRIGHT", 0, -8)
f.Stats2 = DisplayString(f)
f.Stats2:SetTextColor(0, 1, 0)
f.Stats2:SetPoint("TOPLEFT", f.Stats1, "BOTTOMLEFT", 0, -4)
f.Stats2:SetPoint("TOPRIGHT", f.Stats1, "BOTTOMRIGHT", 0, -4)
f.Stats3 = DisplayString(f)
f.Stats3:SetTextColor(0, 1, 0)
f.Stats3:SetPoint("TOPLEFT", f.Stats2, "BOTTOMLEFT", 0, -4)
f.Stats3:SetPoint("TOPRIGHT", f.Stats2, "BOTTOMRIGHT", 0, -4)
-- Add Some default text
f.Title:SetText(string.format(" OmegaSTATS |cFF00FFFF%.2f %%|r",(xp*100)/(xpMax)))
f.Stats1:SetText("Kill Count")
f.Stats2:SetText("Kills Remaing")
--f.Stats3:SetText("Time Remaining")
-- An event handler to update the display strings
f:SetScript("OnEvent", function(self, event, ...)
if event == "PLAYER_XP_UPDATE" then
xpPrev = xp -- old exp
xp = UnitXP("player") -- current exp (goes to 0 after a level!)
xpMax = UnitXPMax("player")
-- xpRemain / xpEarned
local mobKillCount = 0
if (xp > xpPrev ) then
mobKillCount = ceil((xpMax-xp)/(xp-xpPrev)) -- // fix for divide by zero
end
prevTime = lTime
lTime = GetTime()
local tDiff = lTime - prevTime
local tDiff = lTime - prevTime
local secTillLevel = tDiff * mobKillCount
local minTillLevel = secTillLevel / 60
local hrs = math.floor(minTillLevel / 60)
local mins = math.ceil(minTillLevel % 60)
count = count + 1
self.Title:SetText(string.format(" OmegaSTATS |cFF00FFFF%.2f %%|r",(xp*100)/(xpMax)))
self.Stats1:SetText(string.format("Killed |cFFFFFF33%d|r. Last kill took |cFF00FFFF%.2f secs|r.",count,tDiff))
self.Stats2:SetText(string.format("Kill |cFFFFFF33%d (|cFF00FFFF%.0f hrs %.0f mins|r) till next level.",mobKillCount,hrs, mins))
--self.Stats3:SetText(string.format("(|cFF00FFFF%.0f hrs %.0f mins|r) till next level.",))
elseif event == "EVENT_FOR_STATS2" then
Stats2Value = Stats1Value + 10
elseif event == "EVENT_FOR_STATS3" then
Stats3Value = Stats1Value + 15
end
end)
-- Register the event(s) to listen for to update the stats.
f:RegisterEvent("PLAYER_XP_UPDATE")
--f:RegisterEvent("EVENT_FOR_STATS2")
--f:RegisterEvent("EVENT_FOR_STATS2")
-- Create a slash command to show/hide the frame
SLASH_GREAYHAVENSTATS1 = "/gs"
SlashCmdList["GREAYHAVENSTATS"] = function(msg)
f:SetShown(not f:IsShown())
end |
local function toRadians(degrees)
return ((degrees % 360) * math.pi / 180)
end
local function isRectPath(obj)
return obj and (obj.x1 ~= nil) and (obj.y1 ~= nil) and (obj.x2 ~= nil) and (obj.y2 ~= nil) and (obj.x3 ~= nil) and (obj.y3 ~= nil) and (obj.x4 ~= nil) and (obj.y4 ~= nil)
end
local function hasRectPath(obj)
return obj and obj.path and isRectPath(obj.path)
end
local function isUserData(target)
return type(target) == "userdata"
end
--[[
Takes a numeric value and makes sure that it is inside of the given interval.
--]]
local function getValidIntervalValue(value, intervalStart, intervalEnd, defaultValue)
if (value == nil) then
return defaultValue
elseif (value < intervalStart) then
return intervalStart
elseif(value > intervalEnd) then
return intervalEnd
else
return value
end
end
-- Performs a shallow copy of a table.
-- @return A new table
local function copyTable(source)
local dest
if (type(source) == "table") then
dest = {}
for k, v in pairs(source) do
dest[k] = v
end
else -- Non-table types are just returned
dest = source
end
return dest
end
local function isTransitionControlProp(propName)
local controlProps = {
time = true,
iterations = true,
tag = true,
transition = true,
delay = true,
delta = true,
onStart = true,
onComplete = true,
onPause = true,
onResume = true,
onCancel = true,
onRepeat = true,
iterationDelay = true,
onIterationStart = true,
onIterationComplete = true,
reverse = true,
transitionReverse = true,
cancelWhen = true,
recalculateOnIteration = true,
}
return controlProps[propName] or false
end
return {
toRadians = toRadians,
isRectPath = isRectPath,
hasRectPath = hasRectPath,
getValidIntervalValue = getValidIntervalValue,
copyTable = copyTable,
isUserData = isUserData,
isTransitionControlProp = isTransitionControlProp,
} |
local t = require( "taptest" )
local deepcopy = require( "deepcopy" )
local same = require( "same" )
tab = { "abc", "def", { 123, 456 } }
copy = deepcopy( tab )
t( tab ~= copy, true )
t( tab[ 3 ] ~= copy[ 3 ], true )
t( same( tab, copy ), true )
t()
|
---- Copyright(c) Cragon. All rights reserved.
--
--ViewForestPartyMenu = ViewBase:new()
--
--function ViewForestPartyMenu:new(o)
-- o = o or {}
-- setmetatable(o, self)
-- self.__index = self
-- if (self.Instance == nil)
-- then
-- self.ViewMgr = nil
-- self.GoUi = nil
-- self.ComUi = nil
-- self.Panel = nil
-- self.UILayer = nil
-- self.InitDepth = nil
-- self.ViewKey = nil
-- self.Instance = o
-- end
--
-- return self.Instance
--end
--
--function ViewForestPartyMenu:onCreate()
-- local com_shade = self.ComUi:GetChild("ComShade").asCom
-- com_shade.onClick:Add(
-- function()
-- self:onClickComShade()
-- end
-- )
-- local com_menuEx = self.ComUi:GetChild("CoMenuEx").asCom
-- local btn_return = com_menuEx:GetChild("BtnReturn").asButton
-- btn_return.onClick:Add(
-- function()
-- self:onClickBtnReturn()
-- end
-- )
-- local btn_rule = com_menuEx:GetChild("BtnRule").asButton
-- btn_rule.onClick:Add(
-- function()
-- self:onClickBtnRule()
-- end
-- )
-- self.TransitionMenu = self.ComUi:GetTransition("TransitionMenu")
-- self.TransitionMenu:Play()
--end
--
--function ViewForestPartyMenu:onClickBtnRule()
-- self.ViewMgr.createView("ForestPartyRule")
-- self.TransitionMenu:PlayReverse(
-- function()
-- self.ViewMgr.destroyView(self)
-- end
-- )
--end
--
--function ViewForestPartyMenu:onClickBtnReturn()
-- self.TransitionMenu:PlayReverse(
-- function()
-- self:leave()
-- end
-- )
--end
--
--function ViewForestPartyMenu:onClickComShade()
-- self.TransitionMenu.PlayReverse(
-- self.ViewMgr.destroyView(self)
-- )
--end
--
--function ViewForestPartyMenu:leave()
-- self.ViewMgr.destroyView(self)
-- local ev = self.ViewMgr:getEv("EvUiRequestLeaveForestParty")
-- if (ev == nil)
-- then
-- ev = EvUiRequestLeaveForestParty:new(nil)
-- end
-- self.ViewMgr:sendEv(ev)
--end
|
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
packer_bootstrap = fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
end
require('packer').startup(function(use)
use 'wbthomason/packer.nvim'
use 'kyazdani42/nvim-web-devicons'
use 'nvim-lua/plenary.nvim'
use 'windwp/nvim-autopairs'
use 'ur4ltz/surround.nvim'
use 'nvim-treesitter/nvim-treesitter'
use 'kyazdani42/nvim-tree.lua'
use 'nvim-lualine/lualine.nvim'
use 'akinsho/bufferline.nvim'
use 'folke/which-key.nvim'
use 'nvim-telescope/telescope.nvim'
use 'numToStr/Comment.nvim'
use 'lukas-reineke/indent-blankline.nvim'
use 'L3MON4D3/LuaSnip'
if packer_bootstrap then require('packer').sync() end
end)
-- plugin setups
require('plugins.autopairs')
require('plugins.indentline')
require('plugins.treesitter')
require('plugins.lualine')
require('plugins.whichkey')
require('plugins.bufferline')
require('plugins.telescope')
require('plugins.nvimtree')
require('plugins.comment')
require('plugins.luasnip')
require('plugins.surround')
|
function sysCall_info()
return {autoStart=false,menu='Importers\nFloor plan importer'}
end
function optimize(grid)
local function findLargestRectFrom(grid,i,j)
local function maxHeightWithFixedW(grid,i,j,w)
local jj=-1
if grid[j][i]~=0 then
jj=j
while jj<=#grid and grid[jj][i]~=0 do
local ii=i
while ii-i<w do
if grid[jj][ii]==0 then
return jj-j
end
ii=ii+1
end
jj=jj+1
end
end
return jj-j
end
local max_w,max_h,max_a=0,0,0
local ei,ej=-1,-1
local max_w=0
while max_w<=#grid[1]-i and grid[j][i+max_w]~=0 do
local max_hh=maxHeightWithFixedW(grid,i,j,max_w+1)
if max_hh>max_h then
max_h=max_hh
end
local max_aa=max_hh*(max_w+1)
if max_aa>max_a then
max_a=max_aa
ei=i+max_w
ej=j+max_hh-1
end
max_w=max_w+1
end
return ei,ej
end
local rects={}
for j=1,#grid do
for i=1,#grid[1] do
if grid[j][i]==1 then
local ii,jj=findLargestRectFrom(grid,i,j)
table.insert(rects,{i,j,ii,jj})
for iii=i,ii do for jjj=j,jj do grid[jjj][iii]=2 end end
end
end
end
return rects
end
function sysCall_init()
color={0.95,0.95,0.95}
colorCSS=function(c) return string.format('rgb(%d,%d,%d)',math.floor(255*c[1]),math.floor(255*c[2]),math.floor(255*c[3])) end
path=sim.getStringParam(sim.stringparam_scene_path)
fmts,fmtss=simUI.supportedImageFormats(';')
imageFile=sim.fileDialog(sim.filedlg_type_load,'Open image...',path,'','Image files',fmtss)
addCuboid=function(classTbl,x1,y1,x2,y2)
local handles={}
for j,classTbl1 in ipairs(classTbl.zSet) do
local h=sim.createPureShape(0,1+(respondable and 8 or 0)+16,{x2-x1,y2-y1,classTbl1.zMax-classTbl1.zMin},0)
sim.setObjectPosition(h,-1,{(x1+x2)/2,(y1+y2)/2,(classTbl1.zMax+classTbl1.zMin)/2})
sim.setShapeColor(h,nil,sim.colorcomponent_ambient_diffuse,color)
table.insert(handles,h)
end
if #handles>1 then
local h=sim.groupShapes(handles)
return h
else
return handles[1]
end
end
addCuboidI=function(classTbl,i1,j1,i2,j2)
i2,j2=i2 or i1,j2 or j1
return addCuboid(classTbl,(i1-0.5)*pixelSize,(j1-0.5)*pixelSize,(i2+0.5)*pixelSize,(j2+0.5)*pixelSize)
end
go=function()
pixelSize=simUI.getSpinboxValue(ui,101)
classes={}
classes.wall={}
classes.wall.height=simUI.getSpinboxValue(ui,111)
classes.wall.valueMin=simUI.getSpinboxValue(ui,201)
classes.wall.valueMax=simUI.getSpinboxValue(ui,202)
classes.wall.zMin=0
classes.wall.zMax=classes.wall.height
classes.wall.zSet={classes.wall}
classes.door={}
classes.door.height=simUI.getSpinboxValue(ui,112)
classes.door.valueMin=simUI.getSpinboxValue(ui,211)
classes.door.valueMax=simUI.getSpinboxValue(ui,212)
classes.door.zMin=classes.door.height
classes.door.zMax=classes.wall.zMax
classes.door.zSet={classes.door}
classes.window={}
classes.window.height=simUI.getSpinboxValue(ui,113)
classes.window.valueMin=simUI.getSpinboxValue(ui,221)
classes.window.valueMax=simUI.getSpinboxValue(ui,222)
classes.window.zMin=0
classes.window.zMax=classes.door.zMin-classes.window.height
classes.window.zSet={classes.window,classes.door}
optimizationEnabled=simUI.getCheckboxValue(ui,901)>0
invertImageValues=simUI.getCheckboxValue(ui,902)>0
respondable=simUI.getCheckboxValue(ui,911)>0
im,res=sim.loadImage(0,imageFile)
c={res[1]/2,res[2]/2}
im=sim.transformBuffer(im,sim.buffer_uint8rgb,1,0,sim.buffer_uint8)
im=sim.unpackUInt8Table(im)
handles={}
for className,classTbl in pairs(classes) do
classTbl.grid={}
for j=1,res[2] do
classTbl.grid[j]=classTbl.grid[j] or {}
for i=1,res[1] do
local v=im[(j-1)*res[1]+i]
if invertImageValues then v=255-v end
classTbl.grid[j][i]=(v>=classTbl.valueMin and v<=classTbl.valueMax) and 1 or 0
end
end
if optimizationEnabled then
classTbl.rects=optimize(classTbl.grid)
for i,rect in ipairs(classTbl.rects) do
table.insert(handles,addCuboidI(classTbl,rect[1]-c[1],rect[2]-c[2],rect[3]-c[1],rect[4]-c[2]))
end
else
for j=1,#classTbl.grid do
for i=1,#classTbl.grid[1] do
if classTbl.grid[j][i]==1 then
table.insert(handles,addCuboidI(classTbl,i-c[1],j-c[2]))
end
end
end
end
end
handle=sim.groupShapes(handles,false)
sim.setObjectAlias(handle,'FloorPlan')
sim.setObjectInt32Param(handle,sim.shapeintparam_respondable,respondable and 1 or 0)
sim.reorientShapeBoundingBox(handle,-1)
sim.setObjectSpecialProperty(handle,sim.objectspecialproperty_collidable|sim.objectspecialproperty_measurable|sim.objectspecialproperty_detectable_all|sim.objectspecialproperty_renderable)
sim.setObjectSelection({handle})
closeUi()
end
chooseColor=function()
newColor=simUI.colorDialog(color)
if newColor then
color=newColor
simUI.setStyleSheet(ui,800,'background-color: '..colorCSS(color))
end
end
closeUi=function()
simUI.destroy(ui)
ui=nil
done=true
end
if imageFile then
ui=simUI.create([[<ui title="Import floorplan..." closeable="true" on-close="closeUi" resizable="true" modal="true" layout="vbox">
<group layout="form">
<label text="Pixel size:" />
<spinbox id="101" float="true" minimum="0.001" maximum="10.000" step="0.001" value="0.200" decimals="6" suffix=" [m]" />
<label text="Walls:" />
<group layout="form">
<label text="Height:" />
<spinbox id="111" float="true" minimum="0.001" maximum="20.000" step="0.001" value="3.000" decimals="3" suffix=" [m]" />
<label text="Range:" />
<group flat="true" layout="hbox">
<spinbox id="201" minimum="0" maximum="255" value="0" />
<spinbox id="202" minimum="0" maximum="255" value="63" />
</group>
</group>
<label text="Doors:" />
<group layout="form">
<label text="Height:" />
<spinbox id="112" float="true" minimum="0.001" maximum="20.000" step="0.001" value="2.000" decimals="3" suffix=" [m]" />
<label text="Range:" />
<group flat="true" layout="hbox">
<spinbox id="211" minimum="0" maximum="255" value="128" />
<spinbox id="212" minimum="0" maximum="255" value="191" />
</group>
</group>
<label text="Windows:" />
<group layout="form">
<label text="Height:" />
<spinbox id="113" float="true" minimum="0.001" maximum="20.000" step="0.001" value="1.200" decimals="3" suffix=" [m]" />
<label text="Range:" />
<group flat="true" layout="hbox">
<spinbox id="221" minimum="0" maximum="255" value="64" />
<spinbox id="222" minimum="0" maximum="255" value="127" />
</group>
</group>
<label text="Color:" />
<button on-click="chooseColor" text=" " style="background-color: ]]..colorCSS(color)..[[" id="800" />
<label />
<checkbox id="911" text="Respondable shape" checked="true" />
<label />
<checkbox id="901" text="Optimize" checked="true" />
<label />
<checkbox id="902" text="Invert image values" checked="false" />
</group>
<group flat="true" layout="hbox">
<button id="998" text="Cancel" on-click="closeUi" />
<button id="999" text="Import" on-click="go" />
</group>
</ui>]])
else
return {cmd='cleanup'}
end
end
function sysCall_nonSimulation()
if done then
return {cmd='cleanup'}
end
end
function sysCall_cleanup()
end
|
package.path = "../?.lua;"..package.path
local testns = require("namespace")()
local funk = require("wordplay.funk")(testns)
print(filter, _G.filter)
print("FUNK EXAMPLES")
print("version: ", funk._VERSION[1], funk._VERSION[2])
print("URL: ", funk._URL)
print("LICENSE: ", funk._LICENSE)
print("DESCRIPTION: ", funk._DESCRIPTION)
---[=[
print("STRING")
for _it, c in iter("Hello Funk.") do
print(c)
end
print("ARRAY")
for _it, c in iter({1,2,3,4}) do
print(c)
end
print("PAIRS")
for _it, k,v in iter({a=1, b=2, c=3}) do
print(k,v)
end
print("EACH")
each(print, iter({'each', 'of','these','will','print'}))
--print(iter({'each', 'of','these','will','print'}))
--for _, it in iter({'each', 'of','these','will','print'}) do
-- print(it)
--end
print("GENERATORS")
print("RANGE")
each(print, range(1,10))
print("RANDOM")
print('each(print, take(10, rands(10, 20)))')
each(print, take(10, rands(10, 20)))
print('each(print, take(5, rands(10)))')
each(print, take(5, rands(10)))
print('each(print, take(5, rands()))')
each(print, take(5, rands()))
print("INDEX")
print(index(2, range(0)))
print(index("b", {"a", "b", "c", "d", "e"}))
print("INDEXES (1,6,8,9")
each(print, indexes("a", {"a", "b", "c", "d", "e", "a", "b", "a", "a"}))
print("TAKE_N (5)")
each(print, take_n(5, range(10)))
--each(print, take_n(5, enumerate(duplicate('x'))))
print("DUPLICATE")
print("each(print, take(3, duplicate('a', 'b', 'c')))")
each(print, take(3, duplicate('a', 'b', 'c')))
print("each(print, take(3, duplicate('x')))")
each(print, take(3, duplicate('x')))
for _it, a, b, c, d, e in take(3, duplicate(1, 2, 'a', 3, 'b')) do
print(a, b, c, d, e)
end
print("TABULATE")
each(print, take(5, tabulate(function(x) return 'a', 'b', 2*x end)))
each(print, take(5, tabulate(function(x) return x^2 end)))
print("FILTERING")
each(print, filter(function(x) return x % 3 == 0 end, range(10)))
each(print, take(5, filter(function(i, x) return i % 3 == 0 end, enumerate(duplicate('x')))))
print("REDUCING/FOLDING")
print('print(length({"a", "b", "c", "d", "e"}))')
print(length({"a", "b", "c", "d", "e"}))
print('print(length({}))')
print(length({}))
print('print(length(range(0)))')
print(length(range(0)))
print('print(length(range(10,100)))')
print(length(range(10,100)))
-- all
print('print(all(function(x) return x end, {true, true, true, true}))')
print(all(function(x) return x end, {true, true, true, true}))
print('print(all(function(x) return x end, {true, true, true, false}))')
print(all(function(x) return x end, {true, true, true, false}))
-- any
print('print(any(function(x) return x end, {false, false, false, false}))')
print(any(function(x) return x end, {false, false, false, false}))
print('print(any(function(x) return x end, {false, false, false, true}))')
print(any(function(x) return x end, {false, false, false, true}))
-- minimum
print('print(minimum(range(1, 10, 1)))')
print(minimum(range(1, 10, 1)))
print('print(minimum({"f", "d", "c", "d", "e"}))')
print(minimum({"f", "d", "c", "d", "e"}))
print('print(min({}))')
print(minimum({}))
-- maximum
print('print(max(range(1, 10, 1)))')
print(maximum(range(1, 10, 1)))
print('print(maximum({"f", "d", "c", "d", "e"}))')
print(maximum({"f", "d", "c", "d", "e"}))
print('print(maximum({}))')
print(maximum({}))
-- totable
print("totable()")
local tab = totable("abcdef")
print(type(tab), #tab)
each(print, tab)
print("MAP - tomap")
local tab = tomap(zip(range(1, 7), 'abcdef'))
print(type(tab), #tab)
each(print, iter(tab))
print("TRANSFORMATIONS")
print('each(print, map(function(x) return 2 * x end, range(4)))')
each(print, map(function(x) return 2 * x end, range(4)))
local fn = function(...) return 'map', ... end
each(print, map(fn, range(4)))
print("INTERSPERSE")
each(print, intersperse("x", {"a", "b", "c", "d", "e"}))
print("SLICING")
print('print(head(enumerate({"a", "b"})))')
print(head(enumerate({"a", "b"})))
print(enumerate({"a", "b"}):head())
print("COMPOSITIONS")
print('each(print, take(15, cycle(range(5))))')
each(print, take(15, cycle(range(5))))
print('each(print, take(15, cycle(zip(range(5), {"a", "b", "c", "d", "e"}))))')
each(print, take(15, cycle(zip(range(5), {"a", "b", "c", "d", "e"}))))
print('each(print, chain(range(2), {"a", "b", "c"}, {"one", "two", "three"}))')
each(print, chain(range(2), {"a", "b", "c"}, {"one", "two", "three"}))
print('each(print, take(15, cycle(chain(enumerate({"a", "b", "c"}),{"one", "two", "three"}))))')
each(print, take(15, cycle(chain(enumerate({"a", "b", "c"}),{"one", "two", "three"}))))
-- generate fibonacci series (1..25)(196417)
print("fibonacci(1..25)")
local function fib(n)
return n < 2 and n or fib(n-1)+fib(n-2)
end
print(range(25):map(fib):sum())
--]=] |
local _, y = term.getCursorPos()
term.scroll(y - 1)
term.setCursorPos(1, 1)
|
local None = newproxy()
local Mock = {}
function Mock.new(name: string?)
local self = {}
self._implementation = None
self._children = {}
self.mock = {
name = name or "Mock",
calls = {},
}
return setmetatable(self, Mock)
end
function Mock:__index(key: string)
local member = rawget(self, key) or rawget(Mock, key)
if member then
return member
end
local mock = self._children[key]
if not mock then
mock = Mock.new(key)
self._children[key] = mock
end
return mock
end
function Mock:__call(...)
local args = table.pack(...)
table.insert(self.mock.calls, args)
local implementation = rawget(self, "_implementation")
if implementation ~= None then
return implementation(...)
end
end
function Mock:__tostring()
return self.mock.name
end
function Mock.is(other: any): boolean
return typeof(other) == "table" and other.mock ~= nil
end
function Mock:mockImplementation(implementation: () -> nil): nil
if implementation == nil then
implementation = None
end
self._implementation = implementation
end
function Mock:reset()
self.mock.calls = {}
self._implementation = None
end
return Mock
|
return function()
local Clock = require(script.Parent.Parent.Clock)
local Collection = require(script.Parent.Collection)
local Error = require(script.Parent.Error)
local Managers = require(script.Parent.Parent.DataStoreServiceMock.Managers)
local document
local collection
beforeEach(function()
collection = Collection.new("collection", {
validate = function(data)
return typeof(data.foo) == "string", "foo must be a string"
end,
defaultData = { foo = "bar" },
})
document = collection:openDocument("document"):expect()
Clock.progress(6)
end)
describe("read", function()
it("should return the data", function()
expect(document:read().foo).to.equal("bar")
end)
end)
describe("write", function()
it("should write the data", function()
document:write({
foo = "baz",
})
expect(document:read().foo).to.equal("baz")
end)
it("should throw when writing to a closed document", function()
local promise = document:close()
expect(function()
document:write({
foo = "qux",
})
end).to.throw("Cannot write to a closed document")
promise:expect()
end)
it("should throw when setting the same value", function()
local value = document:read()
expect(function()
document:write(value)
end).to.throw("Cannot write to a document mutably")
end)
it("should throw when writing a value that does not match validate", function()
expect(function()
document:write({
foo = 5,
})
end).to.throw("foo must be a string")
end)
end)
describe("close", function()
it("should remove the lock", function()
document:close():expect()
Clock.progress(6)
expect(function()
collection:openDocument("document"):expect()
end).never.to.throw()
end)
it("should remove the document from the collection", function()
document:close():expect()
Clock.progress(6)
local nextDocument = collection:openDocument("document"):expect()
expect(document).never.to.equal(nextDocument)
end)
it("should throw when closing a closed document", function()
local promise = document:close()
expect(function()
document:close()
end).to.throw("Cannot close a closed document")
promise:expect()
end)
it("should save the data", function(context)
document:write({
foo = "hello",
})
document:close():expect()
expect(context.read(collection, document).data.foo).to.equal("hello")
end)
it("should not save the data when lock is inconsistent", function(context)
Managers.Data.Global.set("collection", "global", "document", context.makeData({ data = document:read() }))
document:write({
foo = "updated",
})
document:close():expect()
expect(context.read(collection, document).data.foo).never.to.equal("updated")
end)
end)
describe("save", function()
it("should throw when saving a closed document", function()
local promise = document:close()
expect(function()
document:save()
end).to.throw("Cannot save a closed document")
promise:expect()
end)
it("should save the data", function(context)
document:write({
foo = "hello",
})
document:save():expect()
expect(context.read(collection, document).data.foo).to.equal("hello")
end)
it("should not save the data when lock is inconsistent", function(context)
Managers.Data.Global.set("collection", "global", "document", context.makeData({ data = document:read() }))
document:write({
foo = "updated",
})
document:save():await()
expect(context.read(collection, document).data.foo).never.to.equal("hello")
end)
it("should throw when lock is inconsistent", function(context)
Managers.Data.Global.set("collection", "global", "document", context.makeData({ data = document:read() }))
local ok, err = document:save():await()
expect(ok).to.equal(false)
expect(err.kind).to.equal(Error.Kind.InconsistentLock)
end)
it("should throw when data stores are erroring", function()
Managers.Errors.setErrorChance(1)
local ok, err = document:save():await()
expect(ok).to.equal(false)
expect(err.kind).to.equal(Error.Kind.DataStoreFailure)
end)
it("should retry", function()
Managers.Errors.setErrorCounter(1)
expect(function()
document:save():expect()
end).never.to.throw()
end)
describe("when the budget is exhausted", function()
beforeEach(function()
Managers.Budget.setBudget(Enum.DataStoreRequestType.UpdateAsync, 0)
Managers.Budget.setThrottleQueueSize(0)
end)
it("should not throw", function()
expect(function()
document:save():expect()
end).never.to.throw()
end)
it("should should update the data", function(context)
document:write({
foo = "newValue",
})
document:save():expect()
expect(context.read(collection, document).data.foo).to.equal("newValue")
end)
end)
describe("when the document is on write cooldown", function()
beforeEach(function()
Managers.Budget.setThrottleQueueSize(0)
document:save()
end)
it("should not throw", function()
local promise = document:save()
Clock.progress(6)
expect(function()
promise:expect()
end).never.to.throw()
end)
it("should not throw on multiple requests", function()
local first = document:save()
local second = document:save()
Clock.progress(12)
expect(function()
first:expect()
second:expect()
end).never.to.throw()
end)
it("should not throw when the budget is exhausted", function()
Managers.Budget.setBudget(Enum.DataStoreRequestType.UpdateAsync, 0)
local promise = document:save()
Clock.progress(6)
expect(function()
promise:expect()
end).never.to.throw()
end)
it("should should update the data when the budget is exhausted", function(context)
Managers.Budget.setBudget(Enum.DataStoreRequestType.UpdateAsync, 0)
document:write({
foo = "newValue",
})
local promise = document:save()
Clock.progress(6)
promise:expect()
expect(context.read(collection, document).data.foo).to.equal("newValue")
end)
end)
end)
end
|
--[[
Expects the door peripherals to be on the right.
Expects system network on the left.
MIT License
Copyright (c) 2020 Fatboychummy-CC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
assert(peripheral.getType("right") == "modem", "Need modem on right side.")
assert(not peripheral.call("right", "isWireless"), "Modem right needs to be a wired modem.")
assert(peripheral.getType("left") == "modem", "Need modem on left side.")
assert(not peripheral.call("left", "isWireless"), "Modem left needs to be a wired modem.")
-- [[ Modules ]] --
local expect = require("cc.expect").expect
os.loadAPI("bigfont")
-- [[ Semi-Globals ]] --
local function GetPeripherals(sType)
expect(1, sType, "string")
local t = {n = 0}
for _, sName in ipairs(peripheral.call("right", "getNamesRemote")) do
if peripheral.getType(sName) == sType then
t.n = t.n + 1
t[t.n] = sName
end
end
table.sort(t)
local t2 = {n = t.n}
for i = 1, t.n do
t2[i] = peripheral.wrap(t[i])
end
return t2, t
end
local tIntegrators = GetPeripherals("redstone_integrator")
local tMonitors, tMonNames = GetPeripherals("monitor")
local Manip = peripheral.find("manipulator") -- only one is needed.
local nLockdownChannel = 350
local bLockDown = false
local nLockMin = 0
-- [[ Functions ]] --
local function DefineSettings()
local function DefineDefault(sSetting, val)
settings.define(sSetting, {type = type(val), default = val})
end
DefineDefault("door.id1", "M1")
DefineDefault("door.id2", "M2")
DefineDefault("door.name1", "Monitor 1")
DefineDefault("door.name2", "Monitor 2")
DefineDefault("door.level1", 1)
DefineDefault("door.level2", 1)
DefineDefault("door.playerlocked", false)
DefineDefault("door.sensorOffset", {0, 0, 1.5})
DefineDefault("door.serverChannel", 458)
end
local function Palette(monitor)
expect(1, monitor, "table")
local function f(x, y)
monitor.setPaletteColor(x, y)
end
f(colors.orange, 0xffa500)
f(colors.yellow, 0xffff00)
f(colors.red, 0xff0000)
f(colors.green, 0x00ff00)
f(colors.gray, 0x666666)
f(colors.white, 0xffffff)
f(colors.black, 0x000000)
end
local function ForEach(t, f)
expect(1, t, "table")
expect(2, f, "function")
expect(1000, t.n, "number")
for i = 1, t.n do
f(t[i], i)
end
end
local tSides = {"north", "east", "south", "west", n = 4}
local function Integrators(b)
expect(1, b, "boolean")
ForEach(tIntegrators, function(Integrator)
ForEach(tSides, function(side)
Integrator.setOutput(side, b)
end)
end)
end
local function Box(termObj, x, y, w, h, bg)
expect(1, termObj, "table")
expect(2, x, "number")
expect(3, y, "number")
expect(4, w, "number")
expect(5, h, "number")
expect(6, bg, "number")
local rep = string.rep(' ', w)
termObj.setBackgroundColor(bg)
for _y = y, y + h do
termObj.setCursorPos(x, _y)
termObj.write(rep)
end
end
local function Monitors(sState, bUpdateStateOnly, ei)
expect(1, sState, "string")
expect(2, bUpdateStateOnly, "boolean", "nil")
expect(3, ei, "number", "nil")
if not bUpdateStateOnly then
local sId1, sId2, sName1, sName2 =
settings.get("door.id1"),
settings.get("door.id2"),
settings.get("door.name1"),
settings.get("door.name2")
ForEach(tMonitors, function(monitor, i)
Palette(monitor)
local sId, sName
monitor.setBackgroundColor(colors.blue)
monitor.setTextColor(colors.white)
monitor.setTextScale(0.5)
monitor.clear()
if sState == "Errored" then
monitor.setBackgroundColor(colors.black)
monitor.setTextColor(colors.red)
monitor.clear()
sId = tostring(ei)
sName = "System Error"
elseif sState == "Lockdown" or bLockDown then
monitor.setBackgroundColor(colors.black)
monitor.setTextColor(colors.red)
monitor.clear()
sId = "X"
sName = "LOCKDOWN"
else
if i == 1 then
sId = sId1
sName = sName1
else
sId = sId2
sName = sName2
end
end
monitor.setCursorPos(2, 2)
bigfont.writeOn(monitor, 2, sId, 2, 2)
bigfont.writeOn(monitor, 1, sName, 3 + sId:len() * 9, 5)
end)
end
local StateWidth = 7
local tLevels = {settings.get("door.level1"), settings.get("door.level2")}
local function StateFunc(color)
return function(monitor, i)
local mx, my = monitor.getSize()
Box(monitor, mx - StateWidth + 1, 1, StateWidth, my, color)
if tLevels[i] > 1 then
bigfont.writeOn(monitor, 1, "L" .. tostring(tLevels[i]), mx - StateWidth / 2 - ("L" .. tostring(tLevels[i])):len() / 2, my / 2)
end
end
end
if sState == "Closed" then
ForEach(tMonitors, StateFunc(colors.orange))
elseif sState == "Unlocking1" then
ForEach(tMonitors, StateFunc(colors.yellow))
elseif sState == "Unlocking2" then
ForEach(tMonitors, StateFunc(colors.red))
elseif sState == "Opened" then
ForEach(tMonitors, StateFunc(colors.green))
elseif sState == "Errored" or sState == "Lockdown" then
ForEach(tMonitors, StateFunc(colors.gray))
end
end
local function GetDistanceToEntity(entity)
return (
vector.new(table.unpack(settings.get("door.sensorOffset"), 1, 3))
+ vector.new(entity.x, entity.y, entity.z)
):length()
end
local function GetEntitiesInRangeOfDoor()
if Manip then
if Manip.sense then
local tEntities = Manip.sense()
local tInRange = {}
for i = 1, #tEntities do
if GetDistanceToEntity(tEntities[i]) <= 4 then
tInRange[#tInRange + 1] = tEntities[i]
end
end
return tInRange
else
error("Manipulator needs entity sensor!")
end
else
error("Cannot have clearance level > 1 without manipulator and entity sensor!")
end
end
local function RetrieveUUIDClearance(_uuid)
local Channel = settings.get("door.serverChannel")
local modem = peripheral.wrap("left")
modem.open(Channel)
modem.transmit(Channel, Channel, {type = "Get-Clearance", uuid = _uuid, id = os.getComputerID()})
local EndTimer = os.startTimer(0.25)
local Level = 1
while true do
local tEvent = table.pack(os.pullEvent())
if tEvent[1] == "timer" and tEvent[2] == EndTimer then
break
elseif tEvent[1] == "modem_message" then
local side, fRec, _, message = table.unpack(tEvent, 2, tEvent.n)
if side == "left" and fRec == Channel and type(message) == "table" then
if message.type == "Clearance" and message.id == os.getComputerID() then
Level = message.level
break
end
end
end
end
modem.close(Channel)
return Level
end
local function CheckEntities(Level)
local tEntities = GetEntitiesInRangeOfDoor()
print("Entry check:")
for i = 1, #tEntities do
print(" ", tEntities[i].id, "?")
local DetectedLevel = RetrieveUUIDClearance(tEntities[i].id)
if (bLockDown and DetectedLevel >= nLockMin) or (not bLockDown and DetectedLevel >= Level) then
print(" Allowed.")
return true
end
print(" Not high enough clearance.")
end
return false
end
local function Open()
Monitors("Opened", true)
Integrators(true)
sleep(3)
Monitors("Closed", true)
Integrators(false)
end
local function Unlocking(Level)
local bUnlocked = false
parallel.waitForAny(
function() -- check entities thread
while true do
if CheckEntities(Level) then
bUnlocked = true
break
end
sleep(0.5)
end
end,
function() -- monitor drawing thread
for i = 1, 3 do
Monitors("Unlocking1", true)
sleep(0.5)
Monitors("Unlocking2", true)
sleep(0.5)
end
end
)
if bUnlocked then
Open()
else
Monitors("Closed", true)
end
end
-- [[ Main Program ]] --
local function Main()
DefineSettings()
Monitors("Closed")
Integrators(false)
peripheral.call("left", "open", nLockdownChannel)
local tLevels = {settings.get("door.level1"), settings.get("door.level2")}
while true do
local tEvent = table.pack(os.pullEvent())
if tEvent[1] == "monitor_touch" then
for i = 1, tMonNames.n do
local name = tMonNames[i]
if name == tEvent[2] then
Unlocking(tLevels[i])
end
end
elseif tEvent[1] == "modem_message" and tEvent[2] == "left" then
local fRec, _, message = table.unpack(tEvent, 3, tEvent.n)
if fRec == nLockdownChannel and type(message) == "table" then
if message.type == "LOCKDOWN" then
if message.status then
-- lockdown
bLockDown = true
nLockMin = type(message.bypass) == "number" and message.bypass or 999
Monitors("Lockdown")
print("LOCKDOWN LOCKDOWN")
print(" MINIMUM CLEARANCE:", nLockMin)
else
-- no lockdown
if bLockDown then
print("Lockdown ended.")
end
bLockDown = false
nLockMin = 0
Monitors("Closed")
end
end
end
end
end
end
-- [[ Error Handling ]] --
local ok, err = pcall(Main)
if not ok then
printError(err)
pcall(Monitors, "Errored", nil, 10)
for i = 9, 0, -1 do
sleep(1)
pcall(Monitors, "Errored", nil, i)
end
os.reboot()
end
|
OGLHook_Sprites = {
list = {}
}
require([[autorun\OGLHook\Commands]])
require([[autorun\OGLHook\Textures]])
require([[autorun\OGLHook\Utils]])
OGLHook_Sprites.RenderObject = {
x = nil,
y = nil,
width = nil,
height = nil,
scale_x = nil,
scale_y = nil,
rotation = nil,
pivot_x = nil,
pivot_y = nil,
color = nil,
alpha = nil,
visible = nil,
}
OGLHook_Sprite = {}
local inherit = function (cls, obj)
if obj == nil then
obj = {}
end
for k, v in pairs(cls) do
obj[k] = v
end
return obj
end
OGLHook_Sprites.RenderObject.before_render = function (self)
OPENGL32.glPushMatrix()
OPENGL32.glTranslatef(self.x - self.pivot_x, self.y - self.pivot_y, 0)
OPENGL32.glTranslatef(self.pivot_x, self.pivot_y, 0)
OPENGL32.glScalef(self.scale_x, self.scale_y, 1)
OPENGL32.glRotatef(self.rotation, 0, 0, 1)
OPENGL32.glTranslatef(-self.pivot_x, -self.pivot_y, 0)
local cr = (self.color & 0x0000ff) / 255
local cg = ((self.color & 0x00ff00) >> 8) / 255
local cb = ((self.color & 0xff0000) >> 16) / 255
OPENGL32.glColor4f(cr, cg, cb, self.alpha)
end
OGLHook_Sprites.RenderObject.render = nil
OGLHook_Sprites.RenderObject.after_render = function (self)
OPENGL32.glPopMatrix()
end
OGLHook_Sprites.RenderObject.getPosition = function (self)
return self.x, self.y
end
OGLHook_Sprites.RenderObject.setPosition = function (self, x, y)
self.x = x
self.y = y
end
OGLHook_Sprites.RenderObject.getSize = function (self)
return self.width, self.height
end
OGLHook_Sprites.RenderObject.setSize = function (self, width, height)
self.width = width
self.height = height
self:resetPivotPoint()
end
OGLHook_Sprites.RenderObject.getScale = function (self)
return self.scale_x, self.scale_y
end
OGLHook_Sprites.RenderObject.setScale = function (self, scale_x, scale_y)
self.scale_x = scale_x
self.scale_y = scale_y
end
OGLHook_Sprites.RenderObject.resetScale = function (self)
self:setScale(1, 1)
end
OGLHook_Sprites.RenderObject.getRotation = function (self)
return self.rotation
end
OGLHook_Sprites.RenderObject.setRotation = function (self, rotation)
self.rotation = rotation
end
OGLHook_Sprites.RenderObject.resetRotation = function (self)
self:setRotation(0)
end
OGLHook_Sprites.RenderObject.getPivotPoint = function (self)
return self.pivot_x, self.pivot_y
end
OGLHook_Sprites.RenderObject.setPivotPoint = function (self, x, y)
self.pivot_x = x
self.pivot_y = y
end
OGLHook_Sprites.RenderObject.resetPivotPoint = function (self)
-- local w, h = self:getSize()
-- self.pivot_x, self.pivot_y = w / 2, h / 2
self:setPivotPoint(0, 0)
end
OGLHook_Sprites.RenderObject.getColor = function (self)
return self.color
end
OGLHook_Sprites.RenderObject.setColor = function (self, color)
self.color = color
end
OGLHook_Sprites.RenderObject.resetColor = function (self)
self.color = 0xffffff
end
OGLHook_Sprites.RenderObject.getAlpha = function (self)
return self.alpha
end
OGLHook_Sprites.RenderObject.setAlpha = function (self, alpha)
if alpha > 1 then
alpha = 1
elseif alpha < 0 then
alpha = 0
end
self.alpha = alpha
end
OGLHook_Sprites.RenderObject.resetAlpha = function (self, alpha)
self:setAlpha(1)
end
OGLHook_Sprites.RenderObject.getVisible = function (self)
return self.visible
end
OGLHook_Sprites.RenderObject.setVisible = function (self, visible)
if visible then
self.visible = true
else
self.visible = false
end
end
OGLHook_Sprites.RenderObject.destory = function (self)
end
OGLHook_Sprites.RenderObject.new = function (cls, x, y, width, height, visible)
local obj = inherit(OGLHook_Sprites.RenderObject, {})
obj:setPosition(x, y)
obj:setSize(width, height)
obj:resetPivotPoint()
obj:resetRotation()
obj:resetScale()
obj:resetColor()
obj:resetAlpha()
obj:setVisible(visible)
return obj
end
setmetatable(
OGLHook_Sprites.RenderObject,
{__call=OGLHook_Sprites.RenderObject.new}
)
OGLHook_Sprites.Sprite = {
texture_l = nil,
texture_r = nil,
texture_t = nil,
texture_b = nil
}
OGLHook_Sprites.Sprite.resetSize = function (self)
if self.texture then
self:setSize(self.texture.width, self.texture.height)
end
end
OGLHook_Sprites.Sprite.getTextureCoordinates = function (self)
return self.texture_l, self.texture_r, self.texture_t, self.texture_b
end
OGLHook_Sprites.Sprite.setTextureCoordinates = function (self, tl, tr, tt, tb)
self.texture_l = tl
self.texture_r = tr
self.texture_t = tt
self.texture_b = tb
end
OGLHook_Sprites.Sprite.resetTextureCoordinates = function (self)
self.texture_l = 0
self.texture_r = 1
self.texture_t = 0
self.texture_b = 1
end
OGLHook_Sprites.Sprite.assignTexture = function (self, texture)
if not texture then
return
end
if type(texture) == 'string' then
texture = OGLHook_Textures.LoadTexture(texture)
end
self.texture = texture
self:resetSize()
self:resetTextureCoordinates()
end
OGLHook_Sprites.Sprite.before_render = function (self)
if self.texture then
OPENGL32.glEnable(OPENGL32.GL_TEXTURE_2D)
OPENGL32.glEnable(OPENGL32.GL_BLEND)
end
OGLHook_Sprites.RenderObject.before_render(self)
end
OGLHook_Sprites.Sprite.render = function (self)
if self.texture then
OPENGL32.glBindTexture(OPENGL32.GL_TEXTURE_2D, self.texture.register_label)
end
local points = {
{self.texture_l, self.texture_t, 0, 0},
{self.texture_l, self.texture_b, 0, self.height},
{self.texture_r, self.texture_b, self.width, self.height},
{self.texture_r, self.texture_t, self.width, 0}
}
OPENGL32.glBegin(OPENGL32.GL_QUADS)
for _,point in ipairs(points) do
local tx, ty, x, y = unpack(point)
if self.texture then
OPENGL32.glTexCoord2f(tx, ty)
end
OPENGL32.glVertex2f(x, y)
end
OPENGL32.glEnd()
end
OGLHook_Sprites.Sprite.after_render = function (self)
OGLHook_Sprites.RenderObject.after_render(self)
if self.texture then
OPENGL32.glDisable(OPENGL32.GL_BLEND)
OPENGL32.glDisable(OPENGL32.GL_TEXTURE_2D)
end
end
OGLHook_Sprites.Sprite.destroy = function (self)
if self.texture then
self.texture:destroy()
end
for i,ro in ipairs(OGLHook_Sprites.list) do
if ro == self then
OGLHook_Sprites.list[i] = nil
break
end
end
end
OGLHook_Sprites.Sprite.new = function (cls, x, y, texture, visible)
local sprite = OGLHook_Sprites.RenderObject:new(x, y, 0, 0, visible)
inherit(cls, sprite)
sprite:assignTexture(texture)
table.insert(OGLHook_Sprites.list, sprite)
return sprite
end
setmetatable(OGLHook_Sprites.Sprite, {__call = OGLHook_Sprites.Sprite.new})
OGLHook_Sprites.TextContainer = {
background = nil,
_register_label_template = 'oglh_text_container_%s',
}
OGLHook_Sprites.TextContainer =
inherit(OGLHook_Sprites.RenderObject, OGLHook_Sprites.TextContainer)
OGLHook_Sprites.TextContainer.resetSize = function (self)
end
OGLHook_Sprites.TextContainer.assignFontMap = function (self, font_map)
self.font_map = font_map
self:setColor(self.font_map.color)
end
OGLHook_Sprites.TextContainer.setText = function(self, text)
local font_map = self.font_map
if OGLHook_Utils.getAddressSilent(self.register_label) ~= 0 then
OGLHook_Utils.DeallocateRegister(self.register_label)
end
-- glInterleavedArrays
-- GL_T2F_V3F
-- 20 bytes for one point
-- 80 bytes for one symbol
OGLHook_Utils.AllocateRegister(self.register_label, 80*#text)
local container_array_floats = {}
local container_array = {}
local current_pos = 0
local width_coof = 1 / font_map.width
local text_width = 0
for i=1,#text do
local char = text:sub(i,i)
local char_byte = string.byte(char)
local char_left, char_width = unpack(font_map.letters[char_byte])
local texture_left = char_left * width_coof
local texture_width = char_width * width_coof
text_width = text_width + char_width
-- Texture 0,0
table.insert(container_array_floats, texture_left)
table.insert(container_array_floats, 0)
-- Vertex 0,0,0
table.insert(container_array_floats, current_pos)
table.insert(container_array_floats, 0)
table.insert(container_array_floats, 0)
-- Texutre 0,1
table.insert(container_array_floats, texture_left)
table.insert(container_array_floats, 1)
-- Vertex 0,1,0
table.insert(container_array_floats, current_pos)
table.insert(container_array_floats, font_map.height)
table.insert(container_array_floats, 0)
-- Texutre 1,1
table.insert(container_array_floats, texture_left + texture_width)
table.insert(container_array_floats, 1)
-- Vertex 1,1,0
table.insert(container_array_floats, current_pos + char_width)
table.insert(container_array_floats, font_map.height)
table.insert(container_array_floats, 0)
-- Texutre 1,0
table.insert(container_array_floats, texture_left + texture_width)
table.insert(container_array_floats, 0)
-- Vertex 1,0,0
table.insert(container_array_floats, current_pos + char_width)
table.insert(container_array_floats, 0)
table.insert(container_array_floats, 0)
current_pos = current_pos + char_width
end
for _,current in ipairs(container_array_floats) do
for _,byte in ipairs(floatToByteTable(current)) do
table.insert(container_array, byte)
end
end
writeBytes(self.register_label, container_array)
self.text = text
self:setSize(text_width, font_map.height)
end
OGLHook_Sprites.TextContainer.before_render = function (self)
OPENGL32.glEnable(OPENGL32.GL_TEXTURE_2D)
OPENGL32.glEnable(OPENGL32.GL_BLEND)
OGLHook_Sprites.RenderObject.before_render(self)
end
OGLHook_Sprites.TextContainer.render = function (self)
if not (type(self.text) == 'string' and #self.text > 0) then
return false
end
if OGLHook_Utils.getAddressSilent(self.register_label) == 0 then
return false
end
local dword_count = 4*#self.text
OPENGL32.glBindTexture(OPENGL32.GL_TEXTURE_2D, self.font_map.texture.register_label)
OPENGL32.glInterleavedArrays(OPENGL32.GL_T2F_V3F, 20, self.register_label)
OPENGL32.glDrawArrays(OPENGL32.GL_QUADS, 0, dword_count)
end
OGLHook_Sprites.TextContainer.after_render = function (self)
OGLHook_Sprites.RenderObject.after_render(self)
OPENGL32.glDisable(OPENGL32.GL_BLEND)
OPENGL32.glDisable(OPENGL32.GL_TEXTURE_2D)
end
OGLHook_Sprites.TextContainer.destroy = function (self)
if self.background then
self.background:destroy()
end
for i,ro in ipairs(OGLHook_Sprites.list) do
if ro == self then
OGLHook_Sprites.list[i] = nil
break
end
end
end
OGLHook_Sprites.TextContainer.new = function (cls, font_map, x, y, text, visible, background_visible)
local background = OGLHook_Sprites.Sprite(x, y, nil, background_visible)
local container = OGLHook_Sprites.RenderObject:new(x, y, 0, 0, visible)
inherit(cls, container)
container.register_label = string.format(
cls._register_label_template,
OGLHook_Utils.UniqueSuffix()
)
container.background = background
container.background.text_container = container
container.background.before_render = function (self)
self:setSize(self.text_container:getSize())
self:setRotation(self.text_container:getRotation())
self:setScale(self.text_container:getScale())
self:setPivotPoint(self.text_container:getPivotPoint())
OGLHook_Sprites.Sprite.before_render(self)
end
container:assignFontMap(font_map)
if text then
container:setText(text)
end
table.insert(OGLHook_Sprites.list, container)
return container
end
setmetatable(
OGLHook_Sprites.TextContainer,
{__call = OGLHook_Sprites.TextContainer.new}
)
OGLHook_Sprites.destroy = function (self)
for i,ro in ipairs(self.list) do
ro:destroy()
end
end |
local M = {}
local mkutils = require "mkutils"
function M.prepare_extensions(extensions)
return mkutils.add_extensions("+common_domfilters", extensions)
end
function M.prepare_parameters(parameters,extensions)
parameters.tex4ht_sty_par = parameters.tex4ht_sty_par .. ",html5"
parameters = mkutils.extensions_prepare_parameters(extensions,parameters)
return parameters
end
return M
|
local onduty = false
local currentAction = "none"
local obj_net = nil
local handCuffed = false
local drag = false
local officerDrag = -1
local propslist = {}
local lockAskingFine = false
SpawnedSpikes = {}
RegisterCommand('onduty', function()
onduty = not onduty
local str = nil
if onduty then
str = "^2 onduty"
else
str = "^1 offduty"
end
TriggerEvent('chatMessage', "^1[SYSTEM]:^0 You are now"..str.."^0.")
end, false)
--
--Menu
--
Citizen.CreateThread(function()
WarMenu.CreateMenu('main', 'Interaction Menu')
WarMenu.CreateMenu('leo', 'Law Enforcement')
WarMenu.CreateMenu('items', 'Items')
WarMenu.CreateSubMenu('closeMenu', 'main', 'Are you sure?')
while true do
if WarMenu.IsMenuOpened('main') then
if onduty then
if WarMenu.MenuButton('Law Enforcement', 'leo') then -- Open LEO Menu
end
end
if WarMenu.MenuButton('Items', 'items') then -- Open LEO Menu
end
if WarMenu.MenuButton('Exit', 'closeMenu') then -- Exit Menu
end
WarMenu.Display()
elseif WarMenu.IsMenuOpened('items') then
if WarMenu.Button("Deliver Package") then
DoAction("box_carry")
WarMenu.Display()
elseif WarMenu.Button("Deliver Pizza") then
WarMenu.Display()
DoAction("pizza_delivery")
elseif WarMenu.Button("Carry Crate") then
DoAction("crate_delivery")
WarMenu.Display()
elseif WarMenu.Button("Drop Item") then
DoAction("none")
WarMenu.Display()
elseif WarMenu.Button("Give Item") then
DoAction("give_item")
WarMenu.Display()
end
WarMenu.Display()
elseif WarMenu.IsMenuOpened('leo') then
if WarMenu.Button(i18n.translate("menu_weapons_title")) then
RemoveWeapons()
WarMenu.Display()
elseif WarMenu.Button(i18n.translate("menu_toggle_cuff_title")) then
ToggleCuff()
WarMenu.Display()
elseif WarMenu.Button(i18n.translate("menu_force_player_get_in_car_title")) then
PutInVehicle()
WarMenu.Display()
elseif WarMenu.Button(i18n.translate("menu_force_player_get_out_car_title")) then
UnseatVehicle()
WarMenu.Display()
elseif WarMenu.Button(i18n.translate("menu_drag_player_title")) then
DragPlayer()
WarMenu.Display()
elseif WarMenu.Button("Give Fine") then -- Open fines Menu
Fines()
end
WarMenu.Display()
elseif WarMenu.IsMenuOpened('closeMenu') then
if WarMenu.Button('Yes') then
WarMenu.CloseMenu()
elseif WarMenu.MenuButton('No', 'main') then
end
WarMenu.Display()
elseif IsControlJustReleased(0, 244) then --M by default
WarMenu.OpenMenu('main')
end
Citizen.Wait(0)
end
end)
--
--Functions
--
function DoAction(index)
Citizen.CreateThread(function()
if index == "give_item" then
local distance = GetClosestPlayer()
if (distance ~= -1 and distance < 3) then
local one = GetPlayerServerId(GetClosestPlayer())
TriggerServerEvent("arm:GiveItem", one, currentAction)
ClearPedSecondaryTask(GetPlayerPed(PlayerId()))
DetachEntity(NetToObj(obj_net), 1, 1)
DeleteEntity(NetToObj(obj_net))
obj_net = nil
currentAction = "none"
return
else
TriggerEvent('chatMessage', "^1[SYSTEM]:^0 No players are near you.")
return
end
end
if currentAction ~= "none" then
ClearPedSecondaryTask(GetPlayerPed(PlayerId()))
DetachEntity(NetToObj(obj_net), 1, 1)
DeleteEntity(NetToObj(obj_net))
obj_net = nil
currentAction = "none"
end
if index == "none" then
ClearPedSecondaryTask(GetPlayerPed(PlayerId()))
DetachEntity(NetToObj(obj_net), 1, 1)
DeleteEntity(NetToObj(obj_net))
obj_net = nil
currentAction = "none"
return
end
RequestModel(GetHashKey(config.actions[index].animObjects.name))
while not HasModelLoaded(GetHashKey(config.actions[index].animObjects.name)) do
Citizen.Wait(100)
end
RequestAnimDict(config.actions[index].animDictionary)
while not HasAnimDictLoaded(config.actions[index].animDictionary) do
Citizen.Wait(100)
end
local plyCoords = GetOffsetFromEntityInWorldCoords(GetPlayerPed(PlayerId()), 0.0, 0.0, -5.0)
local objSpawned = CreateObject(GetHashKey(config.actions[index].animObjects.name), plyCoords.x, plyCoords.y, plyCoords.z, 1, 1, 1)
Citizen.Wait(1000)
local netid = ObjToNet(objSpawned)
SetNetworkIdExistsOnAllMachines(netid, true)
NetworkSetNetworkIdDynamic(netid, true)
SetNetworkIdCanMigrate(netid, false)
AttachEntityToEntity(objSpawned, GetPlayerPed(PlayerId()), GetPedBoneIndex(GetPlayerPed(PlayerId()), 28422), config.actions[index].animObjects.xoff, config.actions[index].animObjects.yoff, config.actions[index].animObjects.zoff, config.actions[index].animObjects.xrot, config.actions[index].animObjects.yrot, config.actions[index].animObjects.zrot, 1, 1, 0, 1, 0, 1)
TaskPlayAnim(GetPlayerPed(PlayerId()), 1.0, -1, -1, 50, 0, 0, 0, 0) -- 50 = 32 + 16 + 2
TaskPlayAnim(GetPlayerPed(PlayerId()), config.actions[index].animDictionary, config.actions[index].animationName, 1.0, -1, -1, 50, 0, 0, 0, 0)
obj_net = netid
currentAction = index
end)
end
-- --Citizens
-- --Fines
-- buttonsFine[#buttonsFine+1] = {name = "$250", func = 'Fines', params = 250}
-- buttonsFine[#buttonsFine+1] = {name = "$500", func = 'Fines', params = 500}
-- buttonsFine[#buttonsFine+1] = {name = "$1000", func = 'Fines', params = 1000}
-- buttonsFine[#buttonsFine+1] = {name = "$1500", func = 'Fines', params = 1500}
-- buttonsFine[#buttonsFine+1] = {name = "$2000", func = 'Fines', params = 2000}
-- buttonsFine[#buttonsFine+1] = {name = "$4000", func = 'Fines', params = 4000}
-- buttonsFine[#buttonsFine+1] = {name = "$6000", func = 'Fines', params = 6000}
-- buttonsFine[#buttonsFine+1] = {name = "$8000", func = 'Fines', params = 8000}
-- buttonsFine[#buttonsFine+1] = {name = "$10000", func = 'Fines', params = 10000}
-- buttonsFine[#buttonsFine+1] = {name = i18n.translate("menu_custom_amount_fine_title"), func = 'Fines', params = -1}
--
--Events handlers
--
RegisterNetEvent('police:getArrested')
AddEventHandler('police:getArrested', function()
handCuffed = not handCuffed
if(handCuffed) then
TriggerEvent("police:notify", "CHAR_ANDREAS", 1, i18n.translate("title_notification"), false, i18n.translate("now_cuffed"))
else
TriggerEvent("police:notify", "CHAR_ANDREAS", 1, i18n.translate("title_notification"), false, i18n.translate("now_uncuffed"))
drag = false
end
end)
RegisterNetEvent('police:payFines')
AddEventHandler('police:payFines', function(amount, sender)
Citizen.CreateThread(function()
if(lockAskingFine ~= true) then
lockAskingFine = true
local notifReceivedAt = GetGameTimer()
Notification(i18n.translate("info_fine_request_before_amount")..amount..i18n.translate("info_fine_request_after_amount"))
while(true) do
Wait(0)
if (GetTimeDifference(GetGameTimer(), notifReceivedAt) > 15000) then
TriggerServerEvent('police:finesETA', sender, 2)
Notification(i18n.translate("request_fine_expired"))
lockAskingFine = false
break
end
if IsControlPressed(1, config.bindings.accept_fine) then
Notification(i18n.translate("pay_fine_success_before_amount")..amount..i18n.translate("pay_fine_success_after_amount"))
TriggerServerEvent('police:finesETA', sender, 0)
lockAskingFine = false
break
end
if IsControlPressed(1, config.bindings.refuse_fine) then
TriggerServerEvent('police:finesETA', sender, 3)
lockAskingFine = false
break
end
end
else
TriggerServerEvent('police:finesETA', sender, 1)
end
end)
end)
RegisterNetEvent("police:notify")
AddEventHandler("police:notify", function(icon, type, sender, title, text)
SetNotificationTextEntry("STRING");
AddTextComponentString(text);
SetNotificationMessage(icon, icon, true, type, sender, title, text);
DrawNotification(false, true);
end)
--Piece of code given by Thefoxeur54
RegisterNetEvent('police:unseatme')
AddEventHandler('police:unseatme', function(t)
local ped = GetPlayerPed(t)
ClearPedTasksImmediately(ped)
plyPos = GetEntityCoords(PlayerPedId(), true)
local xnew = plyPos.x+2
local ynew = plyPos.y+2
SetEntityCoords(PlayerPedId(), xnew, ynew, plyPos.z)
end)
RegisterNetEvent('police:toggleDrag')
AddEventHandler('police:toggleDrag', function(t)
if(handCuffed) then
drag = not drag
officerDrag = t
end
end)
RegisterNetEvent('police:forcedEnteringVeh')
AddEventHandler('police:forcedEnteringVeh', function(veh)
if(handCuffed) then
local pos = GetEntityCoords(PlayerPedId())
local entityWorld = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0, 20.0, 0.0)
local rayHandle = CastRayPointToPoint(pos.x, pos.y, pos.z, entityWorld.x, entityWorld.y, entityWorld.z, 10, PlayerPedId(), 0)
local _, _, _, _, vehicleHandle = GetRaycastResult(rayHandle)
if vehicleHandle ~= nil then
if(IsVehicleSeatFree(vehicleHandle, 1)) then
SetPedIntoVehicle(PlayerPedId(), vehicleHandle, 1)
else
if(IsVehicleSeatFree(vehicleHandle, 2)) then
SetPedIntoVehicle(PlayerPedId(), vehicleHandle, 2)
end
end
end
end
end)
RegisterNetEvent('police:removeWeapons')
AddEventHandler('police:removeWeapons', function()
RemoveAllPedWeapons(PlayerPedId(), true)
end)
--
--Functions
--
function Notification(msg)
SetNotificationTextEntry("STRING")
AddTextComponentString(msg)
DrawNotification(0,1)
end
function drawNotification(text)
SetNotificationTextEntry("STRING")
AddTextComponentString(text)
DrawNotification(false, false)
end
function GetPlayers()
local players = {}
for i = 0, 31 do
if NetworkIsPlayerActive(i) then
table.insert(players, i)
end
end
return players
end
function GetClosestPlayer()
local players = GetPlayers()
local closestDistance = -1
local closestPlayer = -1
local ply = PlayerPedId()
local plyCoords = GetEntityCoords(ply, 0)
for index,value in ipairs(players) do
local target = GetPlayerPed(value)
if(target ~= ply) then
local targetCoords = GetEntityCoords(GetPlayerPed(value), 0)
local distance = Vdist(targetCoords["x"], targetCoords["y"], targetCoords["z"], plyCoords["x"], plyCoords["y"], plyCoords["z"])
if(closestDistance == -1 or closestDistance > distance) then
closestPlayer = value
closestDistance = distance
end
end
end
return closestPlayer, closestDistance
end
function drawTxt(text,font,centre,x,y,scale,r,g,b,a)
SetTextFont(font)
SetTextProportional(0)
SetTextScale(scale, scale)
SetTextColour(r, g, b, a)
SetTextDropShadow(0, 0, 0, 0,255)
SetTextEdge(1, 0, 0, 0, 255)
SetTextDropShadow()
SetTextOutline()
SetTextCentre(centre)
SetTextEntry("STRING")
AddTextComponentString(text)
DrawText(x, y)
end
function ServiceOn()
isInService = true
TriggerServerEvent("police:takeService")
end
function ServiceOff()
isInService = false
TriggerServerEvent("police:breakService")
end
function DisplayHelpText(str)
BeginTextCommandDisplayHelp("STRING")
AddTextComponentSubstringPlayerName(str)
EndTextCommandDisplayHelp(0, 0, 1, -1)
end
local alreadyDead = false
local playerStillDragged = false
Citizen.CreateThread(function()
while true do
Citizen.Wait(5)
if (handCuffed == true) then
RequestAnimDict('mp_arresting')
while not HasAnimDictLoaded('mp_arresting') do
Citizen.Wait(0)
end
local myPed = PlayerPedId()
local animation = 'idle'
local flags = 16
while(IsPedBeingStunned(myPed, 0)) do
ClearPedTasksImmediately(myPed)
end
TaskPlayAnim(myPed, 'mp_arresting', animation, 8.0, -8, -1, flags, 0, 0, 0, 0)
end
--Piece of code from Drag command (by Frazzle, Valk, Michael_Sanelli, NYKILLA1127 : https://forum.fivem.net/t/release-drag-command/22174)
if drag then
local ped = GetPlayerPed(GetPlayerFromServerId(officerDrag))
local myped = PlayerPedId()
AttachEntityToEntity(myped, ped, 4103, 11816, 0.48, 0.00, 0.0, 0.0, 0.0, 0.0, false, false, false, false, 2, true)
playerStillDragged = true
else
if(playerStillDragged) then
DetachEntity(PlayerPedId(), true, false)
playerStillDragged = false
end
end
end
end)
Citizen.CreateThread(function()
while true do
if drag then
local ped = GetPlayerPed(GetPlayerFromServerId(playerPedDragged))
plyPos = GetEntityCoords(ped, true)
SetEntityCoords(ped, plyPos.x, plyPos.y, plyPos.z)
end
Citizen.Wait(1000)
end
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(1)
if IsPedInAnyVehicle(PlayerPedId(), false) then
currentVeh = GetVehiclePedIsIn(PlayerPedId(), false)
x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true))
if DoesObjectOfTypeExistAtCoords(x, y, z, 0.9, GetHashKey("P_ld_stinger_s"), true) then
for i= 0, 7 do
SetVehicleTyreBurst(currentVeh, i, true, 1148846080)
end
Citizen.Wait(100)
DeleteSpike()
end
end
end
end)
function DoTraffic()
Citizen.CreateThread(function()
TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_CAR_PARK_ATTENDANT", 0, false)
Citizen.Wait(60000)
ClearPedTasksImmediately(PlayerPedId())
end)
drawNotification(i18n.translate("menu_doing_traffic_notification"))
end
function Note()
Citizen.CreateThread(function()
TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_CLIPBOARD", 0, false)
Citizen.Wait(20000)
ClearPedTasksImmediately(PlayerPedId())
end)
drawNotification(i18n.translate("menu_taking_notes_notification"))
end
function StandBy()
Citizen.CreateThread(function()
TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_COP_IDLES", 0, true)
Citizen.Wait(20000)
ClearPedTasksImmediately(PlayerPedId())
end)
drawNotification(i18n.translate("menu_being_stand_by_notification"))
end
function StandBy2()
Citizen.CreateThread(function()
TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_GUARD_STAND", 0, 1)
Citizen.Wait(20000)
ClearPedTasksImmediately(PlayerPedId())
end)
drawNotification(i18n.translate("menu_being_stand_by_notification"))
end
function CheckInventory()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
TriggerServerEvent("police:targetCheckInventory", GetPlayerServerId(t))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function CheckId()
local t , distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
TriggerServerEvent('gc:copOpenIdentity', GetPlayerServerId(t))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function RemoveWeapons()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
TriggerServerEvent("police:removeWeapons", GetPlayerServerId(t))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function ToggleCuff()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
TriggerServerEvent("police:cuffGranted", GetPlayerServerId(t))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function PutInVehicle()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
local v = GetVehiclePedIsIn(PlayerPedId(), true)
TriggerServerEvent("police:forceEnterAsk", GetPlayerServerId(t), v)
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function UnseatVehicle()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 4) then
TriggerServerEvent("police:confirmUnseat", GetPlayerServerId(t))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function DragPlayer()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
TriggerServerEvent("police:dragRequest", GetPlayerServerId(t))
TriggerEvent("police:notify", "CHAR_ANDREAS", 1, i18n.translate("title_notification"), false, i18n.translate("drag_sender_notification_part_1") .. GetPlayerName(serverTargetPlayer) .. i18n.translate("drag_sender_notification_part_2"))
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function Fines()
local t, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
Citizen.Trace("Price : "..tonumber(amount))
DisplayOnscreenKeyboard(1, "FMMC_KEY_TIP8S", "", "", "", "", "", 20)
while (UpdateOnscreenKeyboard() == 0) do
DisableAllControlActions(0);
Wait(0);
end
if (GetOnscreenKeyboardResult()) then
local res = tonumber(GetOnscreenKeyboardResult())
if(res ~= nil and res ~= 0) then
amount = tonumber(res)
end
end
if(tonumber(amount) ~= -1) then
TriggerServerEvent("police:finesGranted", GetPlayerServerId(t), tonumber(amount))
end
else
TriggerEvent('chatMessage', i18n.translate("title_notification"), {255, 0, 0}, i18n.translate("no_player_near_ped"))
end
end
function Crochet()
Citizen.CreateThread(function()
local pos = GetEntityCoords(PlayerPedId())
local entityWorld = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0, 20.0, 0.0)
local rayHandle = CastRayPointToPoint(pos.x, pos.y, pos.z, entityWorld.x, entityWorld.y, entityWorld.z, 10, PlayerPedId(), 0)
local _, _, _, _, vehicleHandle = GetRaycastResult(rayHandle)
if(DoesEntityExist(vehicleHandle)) then
local prevObj = GetClosestObjectOfType(pos.x, pos.y, pos.z, 10.0, GetHashKey("prop_weld_torch"), false, true, true)
if(IsEntityAnObject(prevObj)) then
SetEntityAsMissionEntity(prevObj)
DeleteObject(prevObj)
end
TaskStartScenarioInPlace(PlayerPedId(), "WORLD_HUMAN_WELDING", 0, true)
Citizen.Wait(20000)
SetVehicleDoorsLocked(vehicleHandle, 1)
ClearPedTasksImmediately(PlayerPedId())
drawNotification(i18n.translate("menu_veh_opened_notification"))
else
drawNotification(i18n.translate("no_veh_near_ped"))
end
end)
end
function SpawnSpikesStripe()
if IsPedInAnyPoliceVehicle(PlayerPedId()) then
local modelHash = GetHashKey("P_ld_stinger_s")
local currentVeh = GetVehiclePedIsIn(PlayerPedId(), false)
local x,y,z = table.unpack(GetOffsetFromEntityInWorldCoords(currentVeh, 0.0, -5.2, -0.25))
RequestScriptAudioBank("BIG_SCORE_HIJACK_01", true)
Citizen.Wait(500)
RequestModel(modelHash)
while not HasModelLoaded(modelHash) do
Citizen.Wait(0)
end
if HasModelLoaded(modelHash) then
SpikeObject = CreateObject(modelHash, x, y, z, true, false, true)
SetEntityNoCollisionEntity(SpikeObject, PlayerPedId(), 1)
SetEntityDynamic(SpikeObject, false)
ActivatePhysics(SpikeObject)
if DoesEntityExist(SpikeObject) then
local height = GetEntityHeightAboveGround(SpikeObject)
SetEntityCoords(SpikeObject, x, y, z - height + 0.05)
SetEntityHeading(SpikeObject, GetEntityHeading(PlayerPedId())-80.0)
SetEntityCollision(SpikeObject, false, false)
PlaceObjectOnGroundProperly(SpikeObject)
SetEntityAsMissionEntity(SpikeObject, false, false)
SetModelAsNoLongerNeeded(modelHash)
PlaySoundFromEntity(-1, "DROP_STINGER", PlayerPedId(), "BIG_SCORE_3A_SOUNDS", 0, 0)
end
drawNotification("Spike stripe~g~ deployed~w~.")
end
else
drawNotification("You need to get ~y~inside~w~ a ~y~police vehicle~w~.")
PlaySoundFrontend(-1, "ERROR", "HUD_FRONTEND_DEFAULT_SOUNDSET", true)
end
end
function DeleteSpike()
local model = GetHashKey("P_ld_stinger_s")
local x,y,z = table.unpack(GetEntityCoords(PlayerPedId(), true))
if DoesObjectOfTypeExistAtCoords(x, y, z, 0.9, model, true) then
local spike = GetClosestObjectOfType(x, y, z, 0.9, model, false, false, false)
DeleteObject(spike)
end
end
function CheckPlate()
local pos = GetEntityCoords(PlayerPedId())
local entityWorld = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0, 20.0, 0.0)
local rayHandle = CastRayPointToPoint(pos.x, pos.y, pos.z, entityWorld.x, entityWorld.y, entityWorld.z, 10, PlayerPedId(), 0)
local _, _, _, _, vehicleHandle = GetRaycastResult(rayHandle)
if(DoesEntityExist(vehicleHandle)) then
TriggerServerEvent("police:checkingPlate", GetVehicleNumberPlateText(vehicleHandle))
else
drawNotification(i18n.translate("no_veh_near_ped"))
end
end
function SpawnProps(model)
if(#propslist < 20) then
local prophash = GetHashKey(tostring(model))
RequestModel(prophash)
while not HasModelLoaded(prophash) do
Citizen.Wait(0)
end
local offset = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0, 0.75, 0.0)
local _, worldZ = GetGroundZFor_3dCoord(offset.x, offset.y, offset.z)
local propsobj = CreateObjectNoOffset(prophash, offset.x, offset.y, worldZ, true, true, true)
local heading = GetEntityHeading(PlayerPedId())
SetEntityHeading(propsobj, heading)
SetEntityAsMissionEntity(propsobj)
SetModelAsNoLongerNeeded(prophash)
propslist[#propslist+1] = ObjToNet(propsobj)
else
drawNotification("You have too many props spawned. Please remove some with the menu.")
end
end
function RemoveLastProps()
DeleteObject(NetToObj(propslist[#propslist]))
propslist[#propslist] = nil
end
function RemoveAllProps()
for i, props in pairs(propslist) do
DeleteObject(NetToObj(props))
propslist[i] = nil
end
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(5)
for _, props in pairs(propslist) do
local ox, oy, oz = table.unpack(GetEntityCoords(NetToObj(props), true))
local cVeh = GetClosestVehicle(ox, oy, oz, 20.0, 0, 70)
if(IsEntityAVehicle(cVeh)) then
if IsEntityAtEntity(cVeh, NetToObj(props), 20.0, 20.0, 2.0, 0, 1, 0) then
local cDriver = GetPedInVehicleSeat(cVeh, -1)
TaskVehicleTempAction(cDriver, cVeh, 6, 1000)
SetVehicleHandbrake(cVeh, true)
SetVehicleIndicatorLights(cVeh, 0, true)
SetVehicleIndicatorLights(cVeh, 1, true)
end
end
end
end
end)
-- Events --
RegisterNetEvent("arm:RecieveItem")
AddEventHandler("arm:RecieveItem", function(index)
DoAction(index)
end) |
require("utils.string")
local prompt = require("protocol.prompt")
local gmcp = require("protocol.gmcp")
local statusbar = require("ui.statusbar")
local self = {
host = store.session_read("current_host"),
port = tonumber(store.session_read("current_port") or "0")
}
local function on_connect(host, port)
store.session_write("current_host", host)
store.session_write("current_port", tostring(port))
if host == "localhost" or host == "mg.mud.de" then
statusbar:init()
prompt:init()
gmcp:init()
end
end
local function on_disconnect()
self.host = nil
self.port = nil
store.session_write("current_host", tostring(nil))
store.session_write("current_port", tostring(nil))
blight.status_height(1)
blight.status_line(0, "")
script.reset()
end
mud.on_connect(function(host, port)
on_connect(host, port)
end)
mud.on_disconnect(function()
on_disconnect()
end)
if self.host and self.port then
on_connect(self.host, self.port)
end
|
export type SquareData = {
Bottom: number,
Left: number,
Right: number,
Top: number,
}
return {
Rectangle = function(Horizontal: number, Vertical: number): SquareData
return {
Bottom = Vertical;
Left = Horizontal;
Right = Horizontal;
Top = Vertical;
}
end;
Square = function(Side: number): SquareData
return {
Bottom = Side;
Left = Side;
Right = Side;
Top = Side;
}
end;
Quad = function(Top: number, Right: number, Bottom: number, Left: number): SquareData
return {
Bottom = Bottom;
Left = Left;
Right = Right;
Top = Top;
}
end;
}
|
local pairs = _G.pairs
local libpath = select(1, ...):match(".+%.") or ""
local NIL = require(libpath .. "nil")
local function inplace_update(tbl, upd, nilval)
nilval = nilval or NIL
for k, v in pairs(upd) do
if v == nilval then
tbl[k] = nil
else
tbl[k] = v
end
end
return tbl
end
return inplace_update
|
cfg = {}
cfg.blips = true -- enable blips
cfg.seconds = 300 -- seconds to rob
cfg.cooldown = 3600 -- time between robbaries
cfg.cops = 3 -- minimum cops online
cfg.permission = "lojinha.police" -- permission given to cops
cfg.holdups = { -- list of stores
["paleto_twentyfourseven"] = {
position = { ['x'] = 1734.48046875, ['y'] = 6420.38134765625, ['z'] = 34.5372314453125 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Paleto Bay)",
lastrobbed = 0 -- this is always 0
},
["sandyshores_twentyfoursever"] = {
position = { ['x'] = 1960.7580566406, ['y'] = 3749.26367187, ['z'] = 31.3437423706055 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Sandy Shores)",
lastrobbed = 0
},
["bar_one"] = {
position = { ['x'] = 1983.4105224609, ['y'] = 3049.9191894531, ['z'] = 47.215015411377 },
reward = 100 + math.random(20000,70000),
nameofstore = "Yellow Jack. (Sandy Shores)",
lastrobbed = 0
},
["littleseoul_twentyfourseven"] = {
position = { ['x'] = -709.17022705078, ['y'] = -904.21722412109, ['z'] = 19.215591430664 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Little Seoul)",
lastrobbed = 0
},
["southlossantos_gasstop"] = {
position = { ['x'] = 28.7538948059082, ['y'] = -1339.8212890625, ['z'] = 29.4970436096191 },
reward = 100 + math.random(20000,70000),
nameofstore = "Limited LTD Gas Stop. (South Los Santos)",
lastrobbed = 0
},
["southlossantos_twentyfourseven"] = {
position = { ['x'] = -43.1531448364258, ['y'] = -1748.75244140625, ['z'] = 29.4209976196289 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (South Los Santos)",
lastrobbed = 0
},
["vinewood_twentyfourseven"] = {
position = { ['x'] = 378.030487060547, ['y'] = 332.944427490234, ['z'] = 103.566375732422 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Vinewood)",
lastrobbed = 0
},
--["eastlossantos_robsliquor"] = {
-- position = { ['x'] = 1126.68029785156, ['y'] = -980.39501953125, ['z'] = 45.4157257080078 },
-- reward = 100 + math.random(10000,30000),
-- nameofstore = "Rob's Liquor. (East Los Santos)",
-- lastrobbed = 0
--},
["sandyshores_twentyfourseven"] = {
position = { ['x'] = 2673.32006835938, ['y'] = 3286.4150390625, ['z'] = 55.241138458252 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Sandy Shores)",
lastrobbed = 0
},
["grapeseed_gasstop"] = {
position = { ['x'] = 1707.52648925781, ['y'] = 4920.05126953125, ['z'] = 42.0636787414551 },
reward = 100 + math.random(20000,70000),
nameofstore = "Limited LTD Gas Stop. (Grapeseed)",
lastrobbed = 0
},
--["morningwood_robsliquor"] = {
-- position = { ['x'] = -1479.22424316406, ['y'] = -375.097686767578, ['z'] = 39.1632804870605 },
-- reward = 100 + math.random(10000,30000),
-- nameofstore = "Rob's Liquor. (Morning Wood)",
-- lastrobbed = 0
--},
["chumash_robsliquor"] = {
position = { ['x'] = -2959.37524414063, ['y'] = 387.556365966797, ['z'] = 14.043158531189 },
reward = 100 + math.random(20000,70000),
nameofstore = "Rob's Liquor. (Chumash)",
lastrobbed = 0
},
--["delperro_robsliquor"] = {
-- position = { ['x'] = -1220.14123535156, ['y'] = -915.712158203125, ['z'] = 11.3261671066284 },
-- reward = 100 + math.random(10000,30000),
-- nameofstore = "Rob's Liquor. (Del Perro)",
-- lastrobbed = 0
--},
--["eastlossantos_gasstop"] = {
-- position = { ['x'] = 1160.06237792969, ['y'] = -314.061828613281, ['z'] = 69.2050628662109 },
-- reward = 100 + math.random(10000,30000),
-- nameofstore = "Limited LTD Gas Stop. (East Los Santos)",
-- lastrobbed = 0
--},
["tongva_gasstop"] = {
position = { ['x'] = -1829.00427246094, ['y'] = 798.903076171875, ['z'] = 138.186706542969 },
reward = 100 + math.random(20000,70000),
nameofstore = "Limited LTD Gas Stop. (Tongva Valley)",
lastrobbed = 0
},
["tataviam_twentyfourseven"] = {
position = { ['x'] = 2549.400390625, ['y'] = 385.048309326172, ['z'] = 108.622955322266 },
reward = 100 + math.random(20000,70000),
nameofstore = "Twenty Four Seven. (Tataviam Mountains)",
lastrobbed = 0
},
["rockford_jewlery"] = {
position = { ['x'] = -621.989135742188, ['y'] = -230.804443359375, ['z'] = 38.0570297241211 },
reward = 10000 + math.random(20000,70000),
nameofstore = "Vangelico Jewelry Store. (Rockford Hills)",
lastrobbed = 0
}
} |
--#############################################################################
--# StartScene
--#############################################################################
local SceneEvents = require("lib.SceneEvents") |
local AS = unpack(AddOnSkins)
if not AS:CheckAddOn('Lightheaded') then return end
function AS:LightHeaded()
AS:SkinFrame(LightHeadedFrame)
QuestNPCModel:SetScale(UIParent:GetScale())
LightHeadedFrame:SetScale(UIParent:GetScale())
AS:SkinFrame(LightHeadedSearchBox)
AS:SkinTooltip(LightHeadedTooltip)
AS:StripTextures(LightHeadedScrollFrame)
AS:SkinCloseButton(LightHeadedFrame.close)
AS:SkinArrowButton(LightHeadedFrameSub.prev)
AS:SkinArrowButton(LightHeadedFrameSub.next)
LightHeadedFrameSub.prev:SetSize(16, 16)
LightHeadedFrameSub.next:SetSize(16, 16)
LightHeadedFrameSub.prev:SetPoint('RIGHT', LightHeadedFrameSub.page, 'LEFT', -25, 0)
LightHeadedFrameSub.next:SetPoint('LEFT', LightHeadedFrameSub.page, 'RIGHT', 25, 0)
AS:SkinScrollBar(LightHeadedScrollFrameScrollBar)
LightHeadedFrameSub.title:SetTextColor(23/255, 132/255, 209/255)
end
AS:RegisterSkin('Lightheaded', AS.LightHeaded)
|
---
-- @module Pulser
--
-- ------------------------------------------------
-- Required Modules
-- ------------------------------------------------
local Class = require( 'lib.Middleclass' )
-- ------------------------------------------------
-- Module
-- ------------------------------------------------
local Pulser = Class( 'Middleclass' )
-- ------------------------------------------------
-- Public Methods
-- ------------------------------------------------
function Pulser:initialize( speed, offset, range )
self.speed = speed or 1
self.offset = offset or 1
self.range = range or 1
self.timer = 0
self.value = 0
end
---
-- Returns gradually changing values between 0 and 1 which can be used to
-- make elements slowly pulsate.
-- @tparam number dt The time since the last update in seconds.
--
function Pulser:update( dt )
self.timer = self.timer + dt * self.speed
self.value = math.abs( math.sin( self.timer )) * self.range + self.offset
end
-- ------------------------------------------------
-- Getters
-- ------------------------------------------------
---
-- Returns the pulse value.
-- @treturn number A value between 0 and 1.
--
function Pulser:getPulse()
return self.value
end
return Pulser
|
module(..., package.seeall)
function add_creatures(map_id, start_coord, end_coord, creature_ids, num_creatures, hostility_val)
local avail_coords = map_get_available_creature_coords(map_id, start_coord[1], start_coord[2], end_coord[1], end_coord[2])
for i = 1, num_creatures do
if #avail_coords == 0 then
return
end
local cr_id = creature_ids[RNG_range(1, #creature_ids)]
local coord_idx = RNG_range(1, #avail_coords)
local coord = avail_coords[coord_idx]
local y = coord[1]
local x = coord[2]
table.remove(avail_coords, coord_idx)
-- Check the coordinates to make sure the creature can be placed
-- there.
local tile_details = map_get_tile(map_id, y, x)
local tile_type = tile_details["tile_type"]
if tile_type ~= nil and tile_type ~= CTILE_TYPE_UP_STAIRCASE and tile_type ~= CTILE_TYPE_DOWN_STAIRCASE then
add_creature_to_map(cr_id, y, x, map_id, hostility_val)
end
end
end
|
local stats = {
[69]=900,
[70]=999,
[71]=999,
[72]=999,
[73]=900,
[74]=999,
[75]=900,
[76]=999,
[77]=999,
[78]=999,
[79]=999,
[160]=999,
[225]=999,
[229]=999,
[230]=999
}
do
local random = math.random
function table.shuffle(t)
local n = #t
while n > 1 do
local k = random(n)
n = n - 1
t[n], t[k] = t[k], t[n]
end
return t
end
end
local currentSpawnKey = 0
local g_Spawnpoints
local function spawnAllPlayers()
for i,player in ipairs(getElementsByType"player") do
processPlayerSpawn ( player )
end
end
function processSpawnStart(delay)
currentSpawnKey = 0
--Grab our spawnpoints
g_Spawnpoints = getElementsByType("spawnpoint", g_MapRoot or g_Root )
--Randomize our spawnpoint order
table.shuffle(g_Spawnpoints)
--Calculate our camera position, by grabbing an average spawnpoint position
camX,camY,camZ = 0,0,0
for i,spawnpoint in ipairs(g_Spawnpoints) do
camX,camY,camZ = camX + getElementData(spawnpoint,"posX"), camY + getElementData(spawnpoint,"posY"), camZ + getElementData(spawnpoint,"posZ")
end
camX,camY,camZ = camX/#g_Spawnpoints, camY/#g_Spawnpoints, camZ/#g_Spawnpoints + 30
--Use a random spawnpoint as the target
lookX,lookY,lookZ = getElementData(g_Spawnpoints[1],"posX"), getElementData(g_Spawnpoints[1],"posY"), getElementData(g_Spawnpoints[1],"posZ")
for i,player in ipairs(getElementsByType"player") do
setCameraMatrix ( player, camX,camY,camZ,lookX,lookY,lookZ )
end
setTimer ( spawnAllPlayers, delay, 1 )
end
function processPlayerSpawn ( player )
player = player or source
if not isElement(player) then return end
setStats ( player )
if not getElementData ( player, "Score" ) then
setElementData ( player, "Score", 0 )
end
currentSpawnKey = currentSpawnKey + 1
currentSpawnKey = g_Spawnpoints[currentSpawnKey] and currentSpawnKey or 1
exports.spawnmanager:spawnPlayerAtSpawnpoint ( player, g_Spawnpoints[currentSpawnKey] )
for weapon,ammo in pairs(g_Weapons) do
giveWeapon ( player, weapon, ammo, true )
end
fadeCamera(player,true)
setCameraTarget(player,player)
-- Remove the respawn timer
for i, timer in ipairs(mapTimers) do
if (timer == sourceTimer) then
table.remove(mapTimers, i)
break
end
end
end
addEventHandler ( "onPlayerJoin", g_Root, processPlayerSpawn )
function setStats ( player )
for statID,value in pairs(stats) do
setPedStat ( player, statID, value )
end
end
|
--- This is the networked variant of local_detectable. It simply runs
-- detection.determine_and_network_detection
-- @classmod DetectableEvent
-- region imports
local class = require('classes/class')
local prototype = require('prototypes/prototype')
require('prototypes/event')
require('prototypes/serializable')
local simple_serializer = require('utils/simple_serializer')
local adventurers = require('functional/game_context/adventurers')
local detection = require('functional/detection')
-- endregion
local DetectableEvent = {}
simple_serializer.inject(DetectableEvent)
function DetectableEvent:init()
if type(self.detectable_advn_nm) ~= 'string' then
error(string.format('expected detected_advn_nm is string but got %s (type=%s)',
tostring(self.detectable_advn_nm), type(self.detectable_advn_nm)), 3)
end
if type(self.tags) ~= 'table' then
error(string.format('expected tags is table but got %s (type=%s)',
tostring(self.tags), type(self.tags)), 3)
end
for k,v in pairs(self.tags) do
if type(k) ~= 'string' then
error(string.format('expected tags keys are strings but tags[%s] = %s (type of key is %s)',
tostring(k), tostring(v), type(k)), 3)
end
if v ~= true then
error(string.format('expected tags values are true but tags[\'%s\'] = %s (type of value is %s)',
k, tostring(v), type(v)), 3)
end
end
end
function DetectableEvent:process(game_ctx, local_ctx, networking)
if local_ctx.id ~= 0 then return end
detection.determine_and_network_detection(game_ctx, local_ctx, networking,
self.detectable_advn_nm, self.tags)
end
prototype.support(DetectableEvent, 'event')
prototype.support(DetectableEvent, 'serializable')
return class.create('DetectableEvent', DetectableEvent)
|
--[[--
Holds items within a grid layout.
Inventories are an object that contains `Item`s in a grid layout. Every `Character` will have exactly one inventory attached to
it, which is the only inventory that is allowed to hold bags - any item that has its own inventory (i.e a suitcase). Inventories
can be owned by a character, or it can be individually interacted with as a standalone object. For example, the container plugin
attaches inventories to props, allowing for items to be stored outside of any character inventories and remain "in the world".
]]
-- @classmod Inventory
local META = ix.meta.inventory or {}
META.__index = META
META.slots = META.slots or {}
META.w = META.w or 4
META.h = META.h or 4
META.vars = META.vars or {}
META.receivers = META.receivers or {}
--- Returns a string representation of this inventory
-- @realm shared
-- @treturn string String representation
-- @usage print(ix.item.inventories[1])
-- > "inventory[1]"
function META:__tostring()
return "inventory["..(self.id or 0).."]"
end
--- Returns this inventory's database ID. This is guaranteed to be unique.
-- @realm shared
-- @treturn number Unique ID of inventory
function META:GetID()
return self.id or 0
end
--- Sets the grid size of this inventory.
-- @internal
-- @realm shared
-- @number width New width of inventory
-- @number height New height of inventory
function META:SetSize(width, height)
self.w = width
self.h = height
end
--- Returns the grid size of this inventory.
-- @realm shared
-- @treturn number Width of inventory
-- @treturn number Height of inventory
function META:GetSize()
return self.w, self.h
end
-- this is pretty good to debug/develop function to use.
function META:Print(printPos)
for k, v in pairs(self:GetItems()) do
local str = k .. ": " .. v.name
if (printPos) then
str = str .. " (" .. v.gridX .. ", " .. v.gridY .. ")"
end
print(str)
end
end
-- finds errors for stacked items
function META:FindError()
for _, v in pairs(self:GetItems()) do
if (v.width == 1 and v.height == 1) then
continue
end
print("Finding error: " .. v.name)
print("Item Position: " .. v.gridX, v.gridY)
for x = v.gridX, v.gridX + v.width - 1 do
for y = v.gridY, v.gridY + v.height - 1 do
local item = self.slots[x][y]
if (item and item.id != v.id) then
print("Error Found: ".. item.name)
end
end
end
end
end
-- For the debug/item creation purpose
function META:PrintAll()
print("------------------------")
print("INVID", self:GetID())
print("INVSIZE", self:GetSize())
if (self.slots) then
for x = 1, self.w do
for y = 1, self.h do
local item = self.slots[x] and self.slots[x][y]
if (item and item.id) then
print(item.name .. "(" .. item.id .. ")", x, y)
end
end
end
end
print("INVVARS")
PrintTable(self.vars or {})
print("------------------------")
end
--- Returns the player that owns this inventory.
-- @realm shared
-- @treturn[1] Player Owning player
-- @treturn[2] nil If no connected player owns this inventory
function META:GetOwner()
for _, v in ipairs(player.GetAll()) do
if (v:GetCharacter() and v:GetCharacter().id == self.owner) then
return v
end
end
end
function META:SetOwner(owner, fullUpdate)
if (type(owner) == "Player" and owner:GetNetVar("char")) then
owner = owner:GetNetVar("char")
elseif (!isnumber(owner)) then
return
end
if (SERVER) then
if (fullUpdate) then
for _, v in ipairs(player.GetAll()) do
if (v:GetNetVar("char") == owner) then
self:Sync(v, true)
break
end
end
end
local query = mysql:Update("ix_inventories")
query:Update("character_id", owner)
query:Where("inventory_id", self:GetID())
query:Execute()
end
self.owner = owner
end
--- Checks whether a player has access to an inventory
-- @realm shared
-- @internal
-- @player client Player to check access for
-- @treturn bool Whether or not the player has access to the inventory
function META:OnCheckAccess(client)
local bAccess = false
for _, v in ipairs(self:GetReceivers()) do
if (v == client) then
bAccess = true
break
end
end
return bAccess
end
function META:CanItemFit(x, y, w, h, item2)
local canFit = true
for x2 = 0, w - 1 do
for y2 = 0, h - 1 do
local item = (self.slots[x + x2] or {})[y + y2]
if ((x + x2) > self.w or item) then
if (item2) then
if (item and item.id == item2.id) then
continue
end
end
canFit = false
break
end
end
if (!canFit) then
break
end
end
return canFit
end
function META:GetFilledSlotCount()
local count = 0
for x = 1, self.w do
for y = 1, self.h do
if ((self.slots[x] or {})[y]) then
count = count + 1
end
end
end
return count
end
function META:FindEmptySlot(w, h, onlyMain)
w = w or 1
h = h or 1
if (w > self.w or h > self.h) then
return
end
for y = 1, self.h - (h - 1) do
for x = 1, self.w - (w - 1) do
if (self:CanItemFit(x, y, w, h)) then
return x, y
end
end
end
if (onlyMain != true) then
local bags = self:GetBags()
if (#bags > 0) then
for _, invID in ipairs(bags) do
local bagInv = ix.item.inventories[invID]
if (bagInv) then
local x, y = bagInv:FindEmptySlot(w, h)
if (x and y) then
return x, y, bagInv
end
end
end
end
end
end
function META:GetItemAt(x, y)
if (self.slots and self.slots[x]) then
return self.slots[x][y]
end
end
--- Removes an item from the inventory.
-- @realm shared
-- @number id The item instance ID to remove
-- @bool[opt=false] bNoReplication Whether or not the item's removal should not be replicated
-- @bool[opt=false] bNoDelete Whether or not the item should not be fully deleted
-- @bool[opt=false] bTransferring Whether or not the item is being transferred to another inventory
-- @treturn number The X position that the item was removed from
-- @treturn number The Y position that the item was removed from
function META:Remove(id, bNoReplication, bNoDelete, bTransferring)
local x2, y2
for x = 1, self.w do
if (self.slots[x]) then
for y = 1, self.h do
local item = self.slots[x][y]
if (item and item.id == id) then
self.slots[x][y] = nil
x2 = x2 or x
y2 = y2 or y
end
end
end
end
if (SERVER and !bNoReplication) then
local receivers = self:GetReceivers()
if (istable(receivers)) then
net.Start("ixInventoryRemove")
net.WriteUInt(id, 32)
net.WriteUInt(self:GetID(), 32)
net.Send(receivers)
end
-- we aren't removing the item - we're transferring it to another inventory
if (!bTransferring) then
hook.Run("InventoryItemRemoved", self, ix.item.instances[id])
end
if (!bNoDelete) then
local item = ix.item.instances[id]
if (item and item.OnRemoved) then
item:OnRemoved()
end
local query = mysql:Delete("ix_items")
query:Where("item_id", id)
query:Execute()
ix.item.instances[id] = nil
end
end
return x2, y2
end
function META:AddReceiver(client)
self.receivers[client] = true
end
function META:RemoveReceiver(client)
self.receivers[client] = nil
end
function META:GetReceivers()
local result = {}
if (self.receivers) then
for k, _ in pairs(self.receivers) do
if (IsValid(k) and k:IsPlayer()) then
result[#result + 1] = k
end
end
end
return result
end
function META:GetItemCount(uniqueID, onlyMain)
local i = 0
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.uniqueID == uniqueID) then
i = i + 1
end
end
return i
end
function META:GetItemsByUniqueID(uniqueID, onlyMain)
local items = {}
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.uniqueID == uniqueID) then
items[#items + 1] = v
end
end
return items
end
function META:GetItemsByBase(baseID, bOnlyMain)
local items = {}
for _, v in pairs(self:GetItems(bOnlyMain)) do
if (v.base == baseID) then
items[#items + 1] = v
end
end
return items
end
function META:GetItemByID(id, onlyMain)
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.id == id) then
return v
end
end
end
function META:GetItemsByID(id, onlyMain)
local items = {}
for _, v in pairs(self:GetItems(onlyMain)) do
if (v.id == id) then
items[#items + 1] = v
end
end
return items
end
-- This function may pretty heavy.
function META:GetItems(onlyMain)
local items = {}
for _, v in pairs(self.slots) do
for _, v2 in pairs(v) do
if (istable(v2) and !items[v2.id]) then
items[v2.id] = v2
v2.data = v2.data or {}
local isBag = v2.data.id
if (isBag and isBag != self:GetID() and onlyMain != true) then
local bagInv = ix.item.inventories[isBag]
if (bagInv) then
local bagItems = bagInv:GetItems()
table.Merge(items, bagItems)
end
end
end
end
end
return items
end
function META:GetBags()
local invs = {}
for _, v in pairs(self.slots) do
for _, v2 in pairs(v) do
if (istable(v2) and v2.data) then
local isBag = v2.data.id
if (!table.HasValue(invs, isBag)) then
if (isBag and isBag != self:GetID()) then
invs[#invs + 1] = isBag
end
end
end
end
end
return invs
end
--- Returns the item with the given unique ID (e.g `"handheld_radio"`) if it exists in this inventory. This method checks both
-- this inventory, and any bags that this inventory has inside of it.
-- @realm server
-- @string targetID Unique ID of the item to look for
-- @tab[opt] data Item data to check for
-- @treturn[1] Item Item that belongs to this inventory with the given criteria
-- @treturn[2] bool `false` if the item does not exist
-- @usage local item = inventory:HasItem("handheld_radio")
--
-- if (item) then
-- -- do something with the item table
-- end
function META:HasItem(targetID, data)
local items = self:GetItems()
for _, v in pairs(items) do
if (v.uniqueID == targetID) then
if (data) then
local itemData = v.data
local bFound = true
for dataKey, dataVal in pairs(data) do
if (itemData[dataKey] != dataVal) then
bFound = false
break
end
end
if (!bFound) then
continue
end
end
return v
end
end
return false
end
function META:HasItems(targetIDs)
local items = self:GetItems()
local count = #targetIDs -- assuming array
targetIDs = table.Copy(targetIDs)
for _, v in pairs(items) do
for k, targetID in ipairs(targetIDs) do
if (v.uniqueID == targetID) then
table.remove(targetIDs, k)
count = count - 1
break
end
end
end
return count <= 0, targetIDs
end
function META:HasItemOfBase(baseID, data)
local items = self:GetItems()
for _, v in pairs(items) do
if (v.base == baseID) then
if (data) then
local itemData = v.data
local bFound = true
for dataKey, dataVal in pairs(data) do
if (itemData[dataKey] != dataVal) then
bFound = false
break
end
end
if (!bFound) then
continue
end
end
return v
end
end
return false
end
if (SERVER) then
function META:SendSlot(x, y, item)
local receivers = self:GetReceivers()
local sendData = item and item.data and !table.IsEmpty(item.data) and item.data or {}
net.Start("ixInventorySet")
net.WriteUInt(self:GetID(), 32)
net.WriteUInt(x, 6)
net.WriteUInt(y, 6)
net.WriteString(item and item.uniqueID or "")
net.WriteUInt(item and item.id or 0, 32)
net.WriteUInt(self.owner or 0, 32)
net.WriteTable(sendData)
net.Send(receivers)
if (item) then
for _, v in pairs(receivers) do
item:Call("OnSendData", v)
end
end
end
--- Add an item to the inventory.
-- @realm server
-- @param uniqueID The item unique ID (e.g `"handheld_radio"`) or instance ID (e.g `1024`) to add to the inventory
-- @number[opt=1] quantity The quantity of the item to add
-- @tab data Item data to add to the item
-- @number[opt=nil] x The X position for the item
-- @number[opt=nil] y The Y position for the item
-- @bool[opt=false] noReplication Whether or not the item's addition should not be replicated
-- @treturn[1] bool Whether the add was successful or not
-- @treturn[1] string The error, if applicable
-- @treturn[2] number The X position that the item was added to
-- @treturn[2] number The Y position that the item was added to
-- @treturn[2] number The inventory ID that the item was added to
function META:Add(uniqueID, quantity, data, x, y, noReplication)
quantity = quantity or 1
if (quantity < 1) then
return false, "noOwner"
end
if (!isnumber(uniqueID) and quantity > 1) then
for _ = 1, quantity do
local bSuccess, error = self:Add(uniqueID, 1, data)
if (!bSuccess) then
return false, error
end
end
return true
end
local client = self.GetOwner and self:GetOwner() or nil
local item = isnumber(uniqueID) and ix.item.instances[uniqueID] or ix.item.list[uniqueID]
local targetInv = self
local bagInv
if (!item) then
return false, "invalidItem"
end
if (isnumber(uniqueID)) then
local oldInvID = item.invID
if (!x and !y) then
x, y, bagInv = self:FindEmptySlot(item.width, item.height)
end
if (bagInv) then
targetInv = bagInv
end
-- we need to check for owner since the item instance already exists
if (!item.bAllowMultiCharacterInteraction and IsValid(client) and client:GetCharacter() and
item:GetPlayerID() == client:SteamID64() and item:GetCharacterID() != client:GetCharacter():GetID()) then
return false, "itemOwned"
end
if (hook.Run("CanTransferItem", item, ix.item.inventories[0], targetInv) == false) then
return false, "notAllowed"
end
if (x and y) then
targetInv.slots[x] = targetInv.slots[x] or {}
targetInv.slots[x][y] = true
item.gridX = x
item.gridY = y
item.invID = targetInv:GetID()
for x2 = 0, item.width - 1 do
local index = x + x2
for y2 = 0, item.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = item
end
end
if (!noReplication) then
targetInv:SendSlot(x, y, item)
end
if (!self.noSave) then
local query = mysql:Update("ix_items")
query:Update("inventory_id", targetInv:GetID())
query:Update("x", x)
query:Update("y", y)
query:Where("item_id", item.id)
query:Execute()
end
hook.Run("InventoryItemAdded", ix.item.inventories[oldInvID], targetInv, item)
return x, y, targetInv:GetID()
else
return false, "noFit"
end
else
if (!x and !y) then
x, y, bagInv = self:FindEmptySlot(item.width, item.height)
end
if (bagInv) then
targetInv = bagInv
end
if (hook.Run("CanTransferItem", item, ix.item.inventories[0], targetInv) == false) then
return false, "notAllowed"
end
if (x and y) then
for x2 = 0, item.width - 1 do
local index = x + x2
for y2 = 0, item.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = true
end
end
local characterID
local playerID
if (self.owner) then
local character = ix.char.loaded[self.owner]
if (character) then
characterID = character.id
playerID = character.steamID
end
end
ix.item.Instance(targetInv:GetID(), uniqueID, data, x, y, function(newItem)
newItem.gridX = x
newItem.gridY = y
for x2 = 0, newItem.width - 1 do
local index = x + x2
for y2 = 0, newItem.height - 1 do
targetInv.slots[index] = targetInv.slots[index] or {}
targetInv.slots[index][y + y2] = newItem
end
end
if (!noReplication) then
targetInv:SendSlot(x, y, newItem)
end
hook.Run("InventoryItemAdded", nil, targetInv, newItem)
end, characterID, playerID)
return x, y, targetInv:GetID()
else
return false, "noFit"
end
end
end
function META:Sync(receiver, fullUpdate)
local slots = {}
for x, items in pairs(self.slots) do
for y, item in pairs(items) do
if (istable(item) and item.gridX == x and item.gridY == y) then
slots[#slots + 1] = {x, y, item.uniqueID, item.id, item.data}
end
end
end
net.Start("ixInventorySync")
net.WriteTable(slots)
net.WriteUInt(self:GetID(), 32)
net.WriteUInt(self.w, 6)
net.WriteUInt(self.h, 6)
net.WriteType((receiver == nil or fullUpdate) and self.owner or nil)
net.WriteTable(self.vars or {})
net.Send(receiver)
for _, v in pairs(self:GetItems()) do
v:Call("OnSendData", receiver)
end
end
end
ix.meta.inventory = META
|
local common = {
Env = {
ISPCOPTS = {
"--target=sse4 --cpu=corei7",
{ "--arch=x86"; Config = "win32-*" },
{ "--arch=x86-64"; Config = { "win64-*", "macosx-*" } },
},
CPPPATH = {
-- Pick up generated ISPC headers from the object directory
"$(OBJECTDIR)"
}
},
ReplaceEnv = {
ISPC = "ispc$(PROGSUFFIX)", -- assume ispc.exe is in your path
},
}
Build {
Units = "units.lua",
Passes = {
IspcGen = { Name = "Generate ISPC .h files", BuildOrder = 1 },
},
Configs = {
Config {
Name = "win32-msvc",
DefaultOnHost = "windows",
Tools = { "msvc-vs2010", "ispc" },
Inherit = common,
},
Config {
Name = "macosx-clang",
DefaultOnHost = "macosx",
Tools = { "clang-osx", "ispc" },
Inherit = common,
},
},
}
|
-----------------------------------
-- Area: Bastok Markets
-- NPC: Carmelide
-- Standard Merchant NPC
-- !pos -151.693 -4.819 -69.635 235
-----------------------------------
local ID = require("scripts/zones/Bastok_Markets/IDs")
require("scripts/globals/shop")
function onTrigger(player,npc)
local stock =
{
806, 1713, 2, -- Tourmaline
807, 1713, 2, -- Sardonyx
800, 1713, 2, -- Amethyst
814, 1713, 2, -- Amber
795, 1713, 2, -- Lapis Lazuli
809, 1713, 2, -- Clear Topaz
799, 1713, 2, -- Onyx
796, 1713, 2, -- Light Opal
13454, 69, 3, -- Copper Ring
}
player:showText(npc, ID.text.CARMELIDE_SHOP_DIALOG)
tpz.shop.nation(player, stock, tpz.nation.BASTOK)
end
|
return {
hand_left = {
{ {8, 40}, {9, 39}, {8, 40}, {8, 39}, {8, 40}, {4, 42}, {8, 40}, {8, 40}, {17, 16}, },
{ {8, 41}, {8, 40}, {8, 41}, {8, 40}, {8, 41}, {16, 45}, {8, 41}, {8, 41}, {0, 0}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
{ {8, 41}, {9, 38}, {8, 39}, {8, 28}, {8, 40}, {6, 40}, {-11, 41}, {13, 23}, {13, 27}, },
{ {9, 41}, {9, 40}, {9, 40}, {4, 30}, {8, 41}, {-4, 41}, {-10, 41}, {16, 23}, {15, 29}, },
{ {15, 24}, {13, 38}, {15, 18}, {13, 32}, {0, 0}, {15, 23}, {15, 24}, {13, 37}, {13, 38}, },
{ {8, 41}, {8, 41}, {15, 29}, {15, 29}, {0, 0}, {8, 40}, {8, 41}, {8, 40}, {8, 41}, },
{ {12, 23}, {15, 24}, {13, 38}, {0, 0}, {0, 0}, {10, 36}, {10, 35}, {10, 36}, {10, 35}, },
{ {14, 23}, {2, 24}, {0, 38}, {0, 0}, {0, 0}, {-6, 36}, {-6, 35}, {-6, 36}, {-6, 35}, },
{ {12, 22}, {12, 22}, {15, 23}, {13, 38}, {0, 0}, {11, 34}, {11, 35}, {11, 34}, {11, 35}, },
{ {14, 22}, {14, 22}, {2, 23}, {0, 38}, {0, 0}, {-8, 34}, {-8, 35}, {-8, 34}, {-8, 35}, },
{ {12, 16}, {15, 17}, {13, 31}, {0, 0}, {0, 0}, {18, 33}, {18, 33}, {18, 33}, {18, 33}, },
{ {14, 16}, {2, 17}, {0, 31}, {0, 0}, {0, 0}, {11, 22}, {-10, 33}, {2, 30}, {14, 23}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {18, 32}, {18, 33}, {18, 32}, {18, 33}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {11, 21}, {-10, 33}, {2, 29}, {14, 23}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {18, 26}, {18, 26}, {18, 26}, {18, 26}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {11, 15}, {-10, 26}, {2, 23}, {14, 16}, },
},
hand_right = {
{ {-11, 40}, {-10, 39}, {-10, 39}, {-10, 39}, {-10, 39}, {-17, 45}, {-10, 39}, {-11, 39}, {-17, 15}, },
{ {-9, 40}, {-10, 39}, {-9, 40}, {-9, 39}, {-9, 40}, {-6, 42}, {-9, 39}, {-10, 40}, {0, 0}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
{ {-10, 41}, {-11, 39}, {-12, 38}, {-6, 28}, {-10, 40}, {3, 40}, {9, 41}, {-19, 21}, {-18, 26}, },
{ {-11, 41}, {-11, 40}, {-11, 39}, {-11, 27}, {-10, 39}, {-8, 39}, {10, 40}, {-16, 20}, {-12, 18}, },
{ {-9, 40}, {-10, 40}, {-18, 27}, {-18, 28}, {0, 0}, {-9, 39}, {-9, 40}, {-9, 39}, {-9, 40}, },
{ {-16, 23}, {-15, 37}, {-17, 17}, {-15, 31}, {0, 0}, {-17, 22}, {-17, 23}, {-16, 36}, {-16, 37}, },
{ {-16, 20}, {-2, 20}, {-1, 36}, {0, 0}, {0, 0}, {5, 34}, {5, 33}, {4, 34}, {5, 33}, },
{ {-14, 21}, {-17, 22}, {-16, 37}, {0, 0}, {0, 0}, {-12, 33}, {-12, 32}, {-12, 34}, {-12, 33}, },
{ {-16, 19}, {-16, 20}, {-3, 20}, {-2, 36}, {0, 0}, {7, 32}, {7, 33}, {6, 32}, {6, 33}, },
{ {-14, 19}, {-14, 19}, {-16, 22}, {-16, 36}, {0, 0}, {-13, 31}, {-12, 32}, {-13, 31}, {-13, 32}, },
{ {-17, 13}, {-2, 15}, {-1, 30}, {0, 0}, {0, 0}, {-12, 23}, {8, 32}, {-3, 29}, {-16, 20}, },
{ {-16, 13}, {-18, 15}, {-16, 31}, {0, 0}, {0, 0}, {-19, 32}, {-20, 32}, {-19, 31}, {-19, 32}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {-12, 21}, {7, 33}, {-4, 28}, {-15, 20}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {-20, 31}, {-20, 32}, {-19, 30}, {-20, 32}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {-11, 17}, {8, 25}, {-5, 22}, {-15, 13}, },
{ {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {-19, 25}, {-19, 25}, {-19, 25}, {-19, 25}, },
},
}
|
--[[ ä
Name: Advanced Questbook
By: Crypton
]]
--[[
%s is a "Wild Card" character. AQB uses these to replace with data
such as names of items, players, etc.. It is important not to remove
them or you will receive errors. For translating, you can move them
where they need to go in the sentence so the data forms a proper
sentence in your language.
]]
AQB_XML_QDTAILS = "Detalles de la mision";
AQB_XML_DESCR = "Descripcion:";
AQB_XML_REWARDS = "Recompensas:";
AQB_XML_DETAILS = "Detalles:";
AQB_XML_LOCATIONS = "Localizaciones:";
AQB_XML_CONFIG = "Configuracion";
AQB_XML_HSECTION = "Seccion de Ayuda";
AQB_XML_OPENHELP = "Abrir Ayuda";
AQB_XML_CLOSEHELP = "Cerrar Ayuda";
AQB_XML_SHARERES = "Compartir resultados";
AQB_XML_SHOWSHARE = "Ver compartidas";
AQB_XML_HIDESHARE = "Ocultar compartido";
AQB_XML_BACK = "Atras";
AQB_XML_TYPEKEYWORD = "Introduce un texto para buscar";
AQB_XML_SEARCH = "Buscar";
AQB_XML_SEARCHRES = "Resultados de busqueda";
AQB_XML_CONFIG2 = "Configuracion";
AQB_XML_CONFIG3 = "Icon Configuration"; -- New
AQB_XML_RELOADUI1 = "RecargarUI";
AQB_XML_RELOADUI2 = "Recargar UI si los iconos del mapa se descolocan.";
AQB_XML_RELOADUI3 = "AQD Habilitado, RecargarUI Deshabilitado.";
AQB_XML_SHTOOLTIPS = "Tooltips"; -- Edited
AQB_XML_STTOOLTIPS = "Bloquear Tooltips";
AQB_XML_STICONS = "Bloquear Iconos";
AQB_XML_QDONTIPS = "Quest Description"; -- Edited
AQB_XML_RLONTIPS = "Recommended Level"; -- Edited
AQB_XML_REWONTIPS = "Rewards"; -- Edited
AQB_XML_COORDONTIPS = "Coordinates"; -- Edited
AQB_XML_PREINC = "Guardar incompletas";
AQB_XML_AQD = "Herramienta de volcado de Datos (AQD)";
AQB_XML_QS = "Compartir misiones";
AQB_XML_TMBTN = "Mostrar boton AQB";
--AQB_XML_SAVECLOSE = "Guardar/Salir";
--AQB_XML_CLOSECONFIG = "Cerrar Configuracion";
AQB_XML_PURGE = "Purgar datos";
AQB_XML_STPORT = "Snoop Transports"; -- Edited
AQB_XML_ETRAIN = "Elite Trainers"; -- Edited
AQB_XML_SHOWSHARED = "Shared Quests"; -- Edited
AQB_XML_SHOWDAILY = "Daily Quests"; -- New
AQB_XML_SHOWQUESTS = "Quests"; -- New
AQB_XML_AIRPORT = "Airships"; -- New
AQB_XML_MSGONDUMP = "Mostrar mensaje en la descarga de misiones";
AQB_XML_NOTE1 = "Drag this icon on the map to place an icon in that location."; -- New
AQB_XML_NOTE2 = "Shift+Left Click a Note to Edit It"; -- New
AQB_XML_NOTE3 = "Hold Shift+Right Mouse to Move a Note"; -- New
AQB_XML_NOTE4 = "CTRL+Left Click to Delete a Note"; -- New
AQB_XML_NOTE5 = "New Note"; -- New
AQB_XML_NOTE6 = "Edit Note"; -- New
AQB_XML_NOTE7 = "You currently have %s notes for the current map. Please remove a note before trying to add another."; -- New
AQB_XML_NOTE8 = "Map Notes:"; -- New
AQB_XML_NOTE9 = "Save Note"; -- New
AQB_XML_NOTE10 = "Edit Title"; -- New
AQB_XML_NOTE11 = "Edit Note"; -- New
AQB_XML_NOTE12 = "Custom Notes"; -- Edited
AdvQuestBook_Messages = {
["AQB_AMINFO"] = "una caracteristica muy util para encontrar informacion, realizar un seguimiento y llevar un control de tus misiones.",
["AQB_AMNOTFOUND"] = "AddonManager no detectado. Es un Addon muy util y de uso recomendado para %s. Escribe %s para abrir el panel de %s o puedes usar el boton provisto en el caso de que AddonManager no este instalado.",
["AQB_ERRFILELOAD"] = "Error al subir el archivo",
["AQB_DFAULTSETLOAD"] = "ajustes por defecto cargados",
["AQB_SETSUPDATE"] = "ajustes actualizados",
["AQB_GET_PQUEST"] = "Obtener Misiones de Grupo",
["AQB_SHIFT_RIGHT"] = "Mayus + Click derecho para mover los botones del minimapa.",
["AQB_RCLICK"] = "Boton derecho",
["AQB_MOVE_BTN"] = "Manten presionado el boton izquierdo para mover el boton.",
["AQB_L50ET"] = "Debes tener las habilidades ELite de nivel 45 primarias y secundarias.",
["AQB_LIST_RECIEVED"] = "Recibida lista de misiones compartidas. Por favor, abre %s para ver las misiones compartidas.",
["AQB_NOLIST_RECIEVED"] = "No se ha recibido ningun dato de misiones compartidas.",
["AQB_RECLEVEL"] = "Nivel recomendado",
["AQB_UNKNOWNQID"] = "ID de mision desconocido",
["AQB_COORDS"] = "Coordenadas",
["AQB_NEW_QD"] = "Nueva mision descargada para %s.";
["AQB_CLEARED_DATA"] = "Limpiadas %s misiones y guardadas %s misiones",
["AQB_CLEANED_ALL"] = "Limpiados todos los datos guardados.",
["AQB_UPLOAD"] = "Asegurate de subir tu %s a %s despues de que hayas salido del juego.",
["AQB_MIN_CHARS"] = "Por favor, escribe al menos %s caracteres para la busqueda...",
["AQB_TOOMANY"] = "Se han encontrado mas de %s resultados. Si usas unos parametros de busqueda distintos puedes reducir los resultados a algo mas sencillo para poder visionarlos.",
["AQB_SEARCHING"] = "Buscando %s. Por favor, espera...",
["AQB_FOUND_RESULTS"] = "Encontrados %s resultados para %s.",
["AQB_NOTSUB"] = "Esta mision aun no se ha presentado.",
["AQB_RECLEVEL"] = "Nivel recomendado",
["AQB_START"] = "Çomienza",
["AQB_END"] = "Termina",
["AQB_REWARDS"] = "Recompensas",
["AQB_COORDS"] = "Coordenadas",
["AQB_TRANSPORT"] = "Transporte",
["AQB_LINKSTO"] = "Transporta a",
["AQB_DUMPED"] = "Descargado",
["AQB_GOLD"] = "Oro",
["AQB_XP"] = "Experiencia",
["AQB_TP"] = "Puntos de Talento",
["AQB_MAP"] = "Mapa",
["AQB_AND"] = "y",
["AQB_OPEN"] = "Abrir",
["AQB_LOCK"] = "Bloquea",
["AQB_UNLOCK"] = "Desbloquea",
["AQB_QSTATUS0"] = "No has completado esta mision.",
["AQB_QSTATUS1"] = "Actualmente tienes esta mision.",
["AQB_QSTATUS2"] = "Has completado esta mision.",
};
-- Help topics will be added back later. I need to rewrite them.
|
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "drop",
desc = "drop",
author = "Nixtux",
date = "Jun 3, 2017",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return false
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local dropperID = UnitDefNames['corpokie'].id
local unitsToDrop = UnitDefNames['cormonsta'].id
local holding = {}
local holdingID = {}
local isloadedID = {}
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- Speed-ups
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
if dropperID == unitDefID then
local pieceMap = Spring.GetUnitPieceMap(unitID)
local count = 1
holdingID[unitID] = {}
holdingID[unitID].frame = nil
for pieceName, pieceNum in pairs(pieceMap) do
if pieceName:find("basket") then
local x, y, z = Spring.GetUnitPiecePosDir(unitID,pieceNum)
local heading = Spring.GetUnitHeading(unitID)
local face = math.floor((heading + 8192) / 16384) % 4
local newUnitID = Spring.CreateUnit(unitsToDrop, x, y, z, face, unitTeam)
Spring.SetUnitStealth(newUnitID, true)
Spring.SetUnitSonarStealth(newUnitID, true)
Spring.SetUnitNoSelect(newUnitID, true)
Spring.SetUnitLoadingTransport(newUnitID, unitID)
Spring.UnitAttach(unitID, newUnitID, pieceNum)
--Spring.Echo("Loading ", unitID," with ", newUnitID, "at piece ", pieceNum)
holdingID[unitID][count] = {newUnitID,pieceNum}
--holdingID[unitID].frame = Spring.GetGameFrame()
holdingID[unitID].canAnimate = true
isloadedID[newUnitID] = true
holding[unitID] = true
count = count + 1
end
end
end
end
function gadget:GameFrame(f)
if f%90==0 then
for unitID ,_ in pairs(holdingID) do
holdingID[unitID].canAnimate = true
end
end
end
function gadget:UnitPreDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponID, projectileID, attackerID, attackerDefID, attackerTeam)
if isloadedID[unitID] then
--Spring.Echo(unitID, " Damage reduced")
return 0, 1
else
return damage, 1
end
end
function gadget:UnitDestroyed(unitID, unitDefID)
isloadedID[unitID] = nil
holdingID[unitID] = nil
end
function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponDefID, projectileID, attackerID, attackerDefID, attackerTeam)
if (unitDefID == dropperID) and holding[unitID] then
local currentHP, maxHP = Spring.GetUnitHealth(unitID)
if currentHP <= (math.random(maxHP*.15,maxHP*.75)) then
local passangers = holdingID[unitID]
if passangers == nil then return end
for i = 1, #passangers do
passIDs = passangers[i][1]
Spring.UnitDetach(passIDs)
Spring.SetUnitStealth(passIDs, false)
Spring.SetUnitSonarStealth(passIDs, false)
Spring.SetUnitNoSelect(passIDs, false)
isloadedID[passIDs] = false
--Spring.Echo("UnLoading ", passangers," with ", passIDs)
if attackerID and passIDs then
local x,y,z = Spring.GetUnitPosition(unitID)
local ax,ay,az = Spring.GetUnitPosition(attackerID)
local facing = Spring.GetUnitBuildFacing(unitDefID)
z=z+math.random(-128,128)
x=x+math.random(-128,128)
Spring.GiveOrderToUnit(passIDs, CMD.MOVE, {x,y,z}, {"shift"})
Spring.GiveOrderToUnit(passIDs, CMD.FIGHT, {ax,ay,az}, {"shift"})
--Spring.Echo("Fight Command Given to ", passIDs)
end
passIDs = nil
end
holding[unitID] = nil
elseif damage > 125 and holdingID[unitID].canAnimate then
holdingID[unitID].canAnimate = false
local passangers = holdingID[unitID]
if passangers == nil then return end
for i = 1, #passangers do
passIDs = passangers[i][1]
Spring.CallCOBScript(passIDs, "wriggle", 0, 1)
end
end
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
|
io.input 'const.txt'
io.output '../../src/const.h'
io.write
[[
#ifndef __MAGNET_CONST__
#define __MAGNET_CONST__
#include "api.h"
#define MAGNET_CONST(v) lua_pushinteger(L, v); lua_setfield(L, -2, #v);
int open_const(lua_State* L)
{
]]
for line in io.lines() do
if #line > 0 then
io.write(string.format(
[[
#ifdef %s
MAGNET_CONST(%s)
#endif
]]
, line, line))
end
end
io.write
[[
return 1;
}
#endif
]]
io.flush()
io.close()
|
--[[
_ _ _ _ _ _ _
| | | || || | (_) | | | |
| | | || || |_ _ _ __ ___ __ _ | |_ ___ | | ___ __ _ ___
| | | || || __|| || '_ ` _ \ / _` || __| / _ \ | | / _ \ / _` |/ __|
| |_| || || |_ | || | | | | || (_| || |_ | __/ | |____| (_) || (_| |\__ \
\___/ |_| \__||_||_| |_| |_| \__,_| \__| \___| \_____/ \___/ \__, ||___/
__/ |
|___/
]]--
ULogs.AddGMType( 1, "Sandbox" )
ULogs.AddGMType( 2, "DarkRP" )
ULogs.AddGMType( 3, "TTT" )
ULogs.AddGMType( 4, "Murder" )
ULogs.AddGMType( 5, "Admin" )
ULogs.AddGMType( 6, "Cinema" )
|
fx_version 'adamant'
game 'gta5'
author "Kibra Developments"
description "EXMode Cocaine Job"
client_script {
'client/client.lua',
'config.lua'
}
server_script {
'server/server.lua',
'config.lua'
} |
cloth = {
on_drop = function(player, item)
if player.mapTitle == "Dae Shore" and player.x >= 69 and player.x <= 77 and player.y >= 0 and player.y <= 39 then
local t = {graphic = convertGraphic(838, "item"), color = 0}
player.npcGraphic = t.graphic
player.npcColor = t.color
player.dialogType = 0
player.lastClick = player.ID
if math.random(1, 10) == 1 then
player:addItem("salt_block", 1)
player:removeItem("cloth", 1, 1)
player.fakeDrop = 1
player:dialogSeq({t, "You found a salt block."}, 0)
end
end
end
}
|
-----------------------------------
-- Area: Maze of Shakhrami
-- Quest: Corsair Af1 "Equipped for All Occasions"
-- NPC: Iron Door (Spawn Lost Soul)
-- !pos 247.735 18.499 -142.267 198
-----------------------------------
local ID = require("scripts/zones/Maze_of_Shakhrami/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local efao = player:getQuestStatus(AHT_URHGAN, tpz.quest.id.ahtUrhgan.EQUIPPED_FOR_ALL_OCCASIONS)
local efaoStat = player:getCharVar("EquippedforAllOccasions")
if efao == QUEST_ACCEPTED and efaoStat == 1 and npcUtil.popFromQM(player, npc, ID.mob.LOST_SOUL, {hide = 0}) then
-- no further action
elseif efao == QUEST_ACCEPTED and efaoStat == 2 then
player:startEvent(66)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 66 then
npcUtil.giveKeyItem(player, tpz.ki.WHEEL_LOCK_TRIGGER)
player:setCharVar("EquippedforAllOccasions", 3)
end
end
|
AutoDisenchantIgnoreList = {
}
|
--require "psetup_lib.plugins"
|
--[[
TheNexusAvenger
Manages the selections groups.
Class is static.
--]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local GuiService = game:GetService("GuiService")
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorageProject = require(ReplicatedStorage:WaitForChild("Project"):WaitForChild("ReplicatedStorage"))
local SelectionGroups = ReplicatedStorageProject:GetResource("External.NexusInstance.NexusObject"):Extend()
SelectionGroups:SetClassName("SelectionGroups")
SelectionGroups.Groups = {}
--[[
Adds a selection group to the top.
--]]
function SelectionGroups:Add(SelectionGroup)
table.insert(self.Groups,SelectionGroup)
self:UpdateSelectionGroup()
end
--[[
Adds a selection group to the bottom (intended for
UI that appears below prompts while they are open).
--]]
function SelectionGroups:AddBelow(SelectionGroup)
table.insert(self.Groups,1,SelectionGroup)
self:UpdateSelectionGroup()
end
--[[
Removes the last index of a given selection group.
--]]
function SelectionGroups:Remove(GroupToRemove)
--Get the highest index of the group.
local Index
for i,Group in pairs(self.Groups) do
if Group == GroupToRemove then
Index = i
end
end
--Remove the group.
if Index then
table.remove(self.Groups,Index)
self:UpdateSelectionGroup()
end
end
--[[
Updates the active selection group.
--]]
function SelectionGroups:UpdateSelectionGroup()
--Return if the group is the same.
local NewGroup = self.Groups[#self.Groups]
if NewGroup == self.CurrentGroup then return end
--Disconnect the existing group.
if self.CurrentGroup then
self.CurrentGroup = nil
end
if self.CurrentGroupChangedEvent then
self.CurrentGroupChangedEvent:Disconnect()
self.CurrentGroupChangedEvent = nil
end
--Set up the new group.
if NewGroup then
self.CurrentGroup = NewGroup
self.CurrentGroupChangedEvent = NewGroup.GroupChanged:Connect(function()
self:UpdateSelectedFrame()
end)
end
--Update the selection.
self:UpdateSelectedFrame()
end
--[[
Updates the selected frame.
--]]
function SelectionGroups:UpdateSelectedFrame()
--Unset the selection if there is no gamepad connected or no current group.
if not self.CurrentGroup or not UserInputService:GetGamepadConnected(Enum.UserInputType.Gamepad1) then
GuiService.SelectedObject = nil
return
end
--Update the selection.
if self.LastFrame and not self.CurrentGroup:ContainsFrame(self.LastFrame) then
self.LastFrame = nil
end
GuiService.SelectedObject = (self.CurrentGroup:ContainsFrame(GuiService.SelectedObject) and GuiService.SelectedObject) or self.LastFrame or self.CurrentGroup:GetFirstFrame()
end
--Set up controller events.
UserInputService.GamepadConnected:Connect(function()
SelectionGroups:UpdateSelectedFrame()
end)
UserInputService.GamepadDisconnected:Connect(function()
SelectionGroups:UpdateSelectedFrame()
end)
GuiService.Changed:Connect(function()
SelectionGroups:UpdateSelectedFrame()
end)
return SelectionGroups |
--[[
Carbon for Lua
Test: Carbon.Math.Matrix3x3
]]
local Carbon = (...)
local Dictionary = Carbon.Collections.Dictionary
local Matrix3x3 = Carbon.Math.Matrix3x3
local Test = {}
Carbon.Testing:TestFor(Matrix3x3, Test)
local sqrt = math.sqrt
local function approxeq(a, b, E)
return math.abs(a - b) < (E or 1e-6)
end
-- Compare the 3x3 part of any matrix.
local function matrixapproxeq(a, b, E)
for i = 1, 3 do
for j = 1, 3 do
local x, y = a:Get(i, j), b:Get(i, j)
if (not x or not y) then
return false
end
if (not approxeq(x, y)) then
return false
end
end
end
return true
end
function Test:Run(test)
local a = Matrix3x3:New(
1, 2, 3,
4, 5, 6,
-7, -8, -9
)
local b = Matrix3x3:New(
9, 8, 7,
6, 5, 4,
3, 2, 1
)
local ab_correct = Matrix3x3:New(
30, 24, 18,
84, 69, 54,
-138, -114, -90
)
-- Equivalent matrix in loose 3x3 form
local aa = Matrix3x3:NewFromLoose(3, 3,
1, 2, 3,
4, 5, 6,
-7, -8, -9
)
if (matrixapproxeq(a, aa)) then
test:Pass()
else
test:Fail("NewFromLoose failed!")
end
-- Test transposition:
local correct_a_trans = Matrix3x3:New(
1, 4, -7,
2, 5, -8,
3, 6, -9
)
local a_trans = a:Transpose()
if (matrixapproxeq(a_trans, correct_a_trans)) then
test:Pass()
else
test:Fail("Matrix transposition failed!")
end
-- WolframAlpha says the bottom row is not linearly-independent and is thus (0, 0, 0)
-- We don't really care I don't think, but I should research this more.
local correct_ortho_a = Matrix3x3:New(
1 / sqrt(14), sqrt(2 / 7), 3 / sqrt(14),
4 / sqrt(21), 1 / sqrt(21), -2 / sqrt(21),
-4 / sqrt(21), -1 / sqrt(21), 2 / sqrt(21)
)
local ortho_a = a:Orthonormalize()
if (matrixapproxeq(ortho_a, correct_ortho_a)) then
test:Pass()
else
test:Fail("Failed to orthogonalize matrix!")
end
-- Test GetRow
local x1, y1, z1 = a:GetRow(1)
local x2, y2, z2 = a:GetRow(2)
local x3, y3, z3 = a:GetRow(3)
if (x1 == 1 and y1 == 2 and z1 == 3 and
x2 == 4 and y2 == 5 and z2 == 6 and
x3 == -7 and y3 == -8 and z3 == -9) then
test:Pass()
else
test:Fail("GetRow failed!")
end
-- Test SetRow
local aa = a:Copy()
aa:SetRow(1, 3, 2, 1)
aa:SetRow(2, 6, 5, 4)
aa:SetRow(3, -9, -8, -7)
local x1, y1, z1 = aa:GetRow(1)
local x2, y2, z2 = aa:GetRow(2)
local x3, y3, z3 = aa:GetRow(3)
if (x1 == 3 and y1 == 2 and z1 == 1 and
x2 == 6 and y2 == 5 and z2 == 4 and
x3 == -9 and y3 == -8 and z3 == -7) then
test:Pass()
else
test:Fail("SetRow failed!")
end
-- Test GetColumn
local x1, x2, x3 = a:GetColumn(1)
local y1, y2, y3 = a:GetColumn(2)
local z1, z2, z3 = a:GetColumn(3)
if (x1 == 1 and y1 == 2 and z1 == 3 and
x2 == 4 and y2 == 5 and z2 == 6 and
x3 == -7 and y3 == -8 and z3 == -9) then
test:Pass()
else
test:Fail("GetColumn failed!")
end
-- Test SetColumn
local aa = a:Copy()
aa:SetColumn(1, -7, 4, 1)
aa:SetColumn(2, -8, 5, 2)
aa:SetColumn(3, -9, 6, 3)
local x1, x2, x3 = aa:GetColumn(1)
local y1, y2, y3 = aa:GetColumn(2)
local z1, z2, z3 = aa:GetColumn(3)
if (x1 == -7 and y1 == -8 and z1 == -9 and
x2 == 4 and y2 == 5 and z2 == 6 and
x3 == 1 and y3 == 2 and z3 == 3) then
test:Pass()
else
test:Fail("SetColumn failed!")
end
-- Test Multiplication
local ab = a:MultiplyMatrix(b)
if (matrixapproxeq(ab, ab_correct)) then
test:Pass()
else
test:Fail("Matrix multiplication failed!")
end
-- Test loose multiplication
local ab = a:MultiplyLooseMatrix(b:ToLoose())
if (matrixapproxeq(ab, ab_correct)) then
test:Pass()
else
test:Fail("Loose matrix multiplication failed!")
end
end
return Test |
-- StormFox2 E2 extension
-- By Nak
E2Lib.RegisterExtension("stormfox2", true, "Lets E2 chips use StormFox functions")
__e2setcost( 3 )
-- Time
e2function number sfTime()
return StormFox2.Time.Get()
end
e2function number isNight()
return StormFox2.Time.IsNight() and 1 or 0
end
e2function number isDay()
return StormFox2.Time.IsDay() and 1 or 0
end
__e2setcost( 15 )
e2function string sfTimeDisplay()
return StormFox2.Time.TimeToString(nil)
end
e2function string sfTimeDisplay12h()
return StormFox2.Time.TimeToString(nil,true)
end
-- Weather
__e2setcost( 7 )
local function isRaining()
return StormFox2.Weather.GetCurrent().Name == "Rain"
end
local function isCold()
return StormFox2.Temperature.Get() <= -2
end
e2function number isRaining()
if isCold() then return 0 end
return isRaining() and 1 or 0
end
e2function number isSnowing()
if not isCold() then return 0 end
return isRaining() and 1 or 0
end
e2function number isThundering()
return StormFox2.Thunder.IsThundering() and 1 or 0
end
__e2setcost( 10 )
e2function string getWeather()
return StormFox2.Weather.GetDescription()
end
e2function number getWeatherPercent()
return StormFox2.Weather.GetPercent()
end
-- Wind
__e2setcost( 3 )
e2function number getWind()
return StormFox2.Wind.GetForce()
end
__e2setcost( 10 )
e2function number getWindBeaufort()
return StormFox2.Wind.GetBeaufort()
end |
require 'spec_helper'
describe["_.extend"] = function()
before = function()
source = { a = 1 }
destination = { b = 2, c = 3 }
result = _.extend(source, destination)
end
it["should add all values from the destination table into the source table"] = function()
expect(result).should_equal {a=1,b=2,c=3}
end
it["should return the source table"] = function()
expect(result).should_be(source)
end
end
spec:report(true) |
-- Performs the following transformations on Link targets:
--
-- Case 1:
-- [text](/chapter/#more-stuff) -> [text](#chapter-more-stuff)
--
-- Case 2:
-- [text](/chapter/) -> [text](#chapter)
--
-- All other Links are ignored.
function Link (el)
local n
-- Case 1:
el.target, n = el.target:gsub("^/(%w+)/#([%w-]+)$", "#%1-%2")
-- Case 2:
if n == 0 then
el.target = el.target:gsub("^/(%w+)/$", "#%1")
end
return el
end
|
local WIDTH = 800
-- All other widths reference this value
local EDITOR_WIDTH = WIDTH
local EDITOR_HEIGHT = 600
data.raw["gui-style"].default.flang_editor_window_style = {
type = "textbox_style",
minimal_height = EDITOR_HEIGHT,
minimal_width = EDITOR_WIDTH,
maximal_height = EDITOR_HEIGHT,
maximal_width = EDITOR_WIDTH,
want_ellipsis = false
}
local INFO_WINDOW_WIDTH = WIDTH
local INFO_WINDOW_HEIGHT = 350
data.raw["gui-style"].default.flang_info_window_style = {
type = "textbox_style",
minimal_height = INFO_WINDOW_HEIGHT,
minimal_width = INFO_WINDOW_WIDTH,
maximal_height = INFO_WINDOW_HEIGHT,
maximal_width = INFO_WINDOW_WIDTH,
want_ellipsis = false,
single_line = false,
}
local MENU_WINDOW_WIDTH = WIDTH
local MENU_WINDOW_HEIGHT = 300
data.raw["gui-style"].default.flang_menu_window_style = {
type = "textbox_style",
minimal_height = MENU_WINDOW_HEIGHT,
minimal_width = MENU_WINDOW_WIDTH,
maximal_height = MENU_WINDOW_HEIGHT,
maximal_width = MENU_WINDOW_WIDTH,
want_ellipsis = false,
}
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "InGame",
id = "ResupplyPassengers",
PlaceObj('XTemplateWindow', {
'__context', function (parent, context) return TraitsObjectCreateAndLoad() end,
'__class', "XDialog",
'Id', "idPassengers",
'Padding', box(60, 68, 0, 25),
'InitialMode', "review",
'InternalModes', "traitCategories,items,review",
}, {
PlaceObj('XTemplateFunc', {
'name', "Open",
'func', function (self, ...)
self.context:SetDialog(self)
XDialog.Open(self, ...)
if HintsEnabled then
ContextAwareHintShow("HintPassengerRocket", true)
end
self:SetPadding(GetSafeMargins(self:GetPadding()))
end,
}),
PlaceObj('XTemplateFunc', {
'name', "OnDelete",
'func', function (self, ...)
if HintsEnabled then
ContextAwareHintShow("HintPassengerRocket", false)
end
RefundPassenger()
end,
}),
PlaceObj('XTemplateTemplate', {
'__template', "ActionBarNew",
}),
PlaceObj('XTemplateWindow', {
'Id', "idContent",
'HAlign', "left",
}, {
PlaceObj('XTemplateTemplate', {
'__template', "DialogTitleNew",
'Id', "",
'Margins', box(55, 0, 0, 0),
'Title', T(723122513032, --[[XTemplate ResupplyPassengers Title]] "SELECT COLONISTS"),
'SmallImage', true,
}),
PlaceObj('XTemplateWindow', {
'__class', "XContentTemplate",
'Id', "idTop",
'IdNode', false,
'RespawnOnContext', false,
}, {
PlaceObj('XTemplateWindow', {
'Margins', box(15, 30, 0, 0),
'Dock', "top",
}, {
PlaceObj('XTemplateWindow', {
'__condition', function (parent, context) return GetUIStyleGamepad() end,
'__class', "XImage",
'Id', "idGamepadRenameHint",
'Margins', box(-40, 0, 0, 0),
'Dock', "box",
'HAlign', "left",
'VAlign', "center",
'FoldWhenHidden', true,
'ImageScale', point(520, 520),
}),
PlaceObj('XTemplateCode', {
'run', function (self, parent, context)
local hint = parent:ResolveId("idGamepadRenameHint")
if hint then
hint:SetImage(GetPlatformSpecificImagePath("RSPress"))
end
end,
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idRocketName",
'Padding', box(0, 0, 0, 0),
'HAlign', "left",
'MaxHeight', 50,
'MouseCursor', "UI/Cursors/Rollover.tga",
'TextStyle', "PGLandingPosDetails",
'Translate', true,
'Text', T(454729036303, --[[XTemplate ResupplyPassengers Text]] "<RocketName>"),
'Shorten', true,
'TextHAlign', "right",
}, {
PlaceObj('XTemplateFunc', {
'name', "OnHyperLink(self, hyperlink, argument, hyperlink_box, pos, button)",
'func', function (self, hyperlink, argument, hyperlink_box, pos, button)
local host = GetDialog(self)
host.context:RenameRocket(host)
end,
}),
}),
}),
PlaceObj('XTemplateWindow', {
'__class', "XContextWindow",
'Margins', box(55, 0, 0, 0),
'Dock', "top",
'LayoutMethod', "HList",
'LayoutHSpacing', 70,
'ContextUpdateOnOpen', true,
'OnContextUpdate', function (self, context, ...)
context:SetUIResupplyParams(self)
end,
}, {
PlaceObj('XTemplateWindow', {
'MinWidth', 300,
'MaxWidth', 300,
'LayoutMethod', "VList",
}, {
PlaceObj('XTemplateWindow', {
'__condition', function (parent, context) return not UICity or UICity.launch_mode ~= "passenger_pod" end,
'__class', "XText",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGLandingPosDetails",
'Translate', true,
'Text', T(945506235214, --[[XTemplate ResupplyPassengers Text]] "Rocket Capacity"),
}),
PlaceObj('XTemplateWindow', {
'__condition', function (parent, context) return UICity and UICity.launch_mode == "passenger_pod" end,
'__class', "XText",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGLandingPosDetails",
'Translate', true,
'Text', T(189122132072, --[[XTemplate ResupplyPassengers Text]] "Pod Capacity"),
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGLandingPosDetails",
'Translate', true,
'Text', T(475005233850, --[[XTemplate ResupplyPassengers Text]] "Matching Applicants"),
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGLandingPosDetails",
'Translate', true,
'Text', T(914238670538, --[[XTemplate ResupplyPassengers Text]] "Available Residences on Mars"),
}),
}),
PlaceObj('XTemplateWindow', {
'LayoutMethod', "VList",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idCapacity",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGChallengeDescription",
'Translate', true,
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idMatchingColonists",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGChallengeDescription",
'Translate', true,
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idResidences",
'Padding', box(0, 0, 0, 0),
'TextStyle', "PGChallengeDescription",
'Translate', true,
}),
}),
}),
PlaceObj('XTemplateMode', {
'mode', "traitCategories",
}, {
PlaceObj('XTemplateAction', {
'ActionId', "buyApplicants",
'ActionName', T(5455, --[[XTemplate ResupplyPassengers ActionName]] "BUY APPLICANTS"),
'ActionToolbar', "ActionBar",
'ActionGamepad', "LeftTrigger",
'OnAction', function (self, host, source)
BuyApplicants(host)
end,
'__condition', function (parent, context) return GetMissionSponsor().applicants_price > 0 end,
}),
PlaceObj('XTemplateAction', {
'ActionId', "back",
'ActionName', T(4254, --[[XTemplate ResupplyPassengers ActionName]] "BACK"),
'ActionToolbar', "ActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "back",
}),
PlaceObj('XTemplateAction', {
'ActionId', "clear",
'ActionName', T(5448, --[[XTemplate ResupplyPassengers ActionName]] "CLEAR"),
'ActionToolbar', "ActionBar",
'ActionGamepad', "ButtonY",
'ActionState', function (self, host)
if not host.context:CanClearFilter() then
return "disabled"
end
end,
'OnAction', function (self, host, source)
host.context:ClearTraits()
end,
}),
PlaceObj('XTemplateWindow', {
'Margins', box(55, 20, 0, 0),
'Dock', "top",
'HAlign', "left",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Margins', box(-350, 0, 0, 0),
'Dock', "box",
'MinWidth', 794,
'Image', "UI/CommonNew/pg_action_bar.tga",
'FrameBox', box(42, 0, 341, 0),
'TileFrame', true,
'SqueezeY', false,
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idTitle",
'Padding', box(0, 0, 0, 0),
'VAlign', "center",
'HandleMouse', false,
'TextStyle', "MediumHeader",
'Translate', true,
'HideOnEmpty', true,
}),
}),
PlaceObj('XTemplateWindow', {
'Margins', box(0, 10, 0, 20),
'Dock', "top",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XList",
'Id', "idList",
'BorderWidth', 0,
'Padding', box(15, 2, 2, 2),
'LayoutVSpacing', 8,
'UniformRowHeight', true,
'Clip', false,
'Background', RGBA(0, 0, 0, 0),
'FocusedBackground', RGBA(0, 0, 0, 0),
'VScroll', "idScroll",
'MouseWheelStep', 40,
'ShowPartialItems', false,
}, {
PlaceObj('XTemplateCode', {
'run', function (self, parent, context)
parent:ResolveId("idTitle"):SetText(T(1117, "CATEGORIES"))
end,
}),
PlaceObj('XTemplateForEach', {
'comment', "category",
'array', function (parent, context) return context:GetProperties() end,
'item_in_context', "prop_meta",
'run_after', function (child, context, item, i, n)
local rollover = context:GetCategoryRollover(item)
if rollover then
child:SetRolloverTitle(rollover.title)
child:SetRolloverText(rollover.descr)
child:SetRolloverHint(rollover.hint)
child:SetRolloverHintGamepad(rollover.gamepad_hint)
end
end,
}, {
PlaceObj('XTemplateTemplate', {
'__template', "PropTrait",
'RolloverTemplate', "Rollover",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Id', "idRollover",
'ZOrder', 0,
'Margins', box(-20, -12, -20, -12),
'Dock', "box",
'Visible', false,
'Image', "UI/CommonNew/re_candidate_rollover.tga",
'FrameBox', box(25, 0, 25, 0),
'SqueezeY', false,
}),
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "ScrollbarNew",
'Id', "idScroll",
'Target', "idList",
}),
}),
}),
PlaceObj('XTemplateMode', {
'mode', "items",
}, {
PlaceObj('XTemplateAction', {
'ActionId', "back",
'ActionName', T(4254, --[[XTemplate ResupplyPassengers ActionName]] "BACK"),
'ActionToolbar', "ActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "back",
}),
PlaceObj('XTemplateAction', {
'ActionId', "clear",
'ActionName', T(5448, --[[XTemplate ResupplyPassengers ActionName]] "CLEAR"),
'ActionToolbar', "ActionBar",
'ActionGamepad', "ButtonY",
'ActionState', function (self, host)
local prop_meta = GetDialogModeParam(host)
local category = prop_meta and prop_meta.id or nil
if not host.context:CanClearFilter(category) then
return "disabled"
end
end,
'OnAction', function (self, host, source)
local prop_meta = GetDialogModeParam(host)
host.context:ClearTraits(prop_meta)
end,
}),
PlaceObj('XTemplateWindow', {
'Margins', box(55, 20, 0, 0),
'Dock', "top",
'HAlign', "left",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Margins', box(-350, 0, 0, 0),
'Dock', "box",
'MinWidth', 794,
'Image', "UI/CommonNew/pg_action_bar.tga",
'FrameBox', box(42, 0, 341, 0),
'TileFrame', true,
'SqueezeY', false,
}),
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Id', "idTitle",
'Padding', box(0, 0, 0, 0),
'VAlign', "center",
'HandleMouse', false,
'TextStyle', "MediumHeader",
'Translate', true,
'HideOnEmpty', true,
}),
}),
PlaceObj('XTemplateWindow', {
'Margins', box(0, 10, 0, 20),
'Dock', "top",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XList",
'Id', "idList",
'BorderWidth', 0,
'Padding', box(15, 2, 2, 2),
'LayoutVSpacing', 8,
'UniformRowHeight', true,
'Clip', false,
'Background', RGBA(0, 0, 0, 0),
'FocusedBackground', RGBA(0, 0, 0, 0),
'VScroll', "idScroll",
'MouseWheelStep', 40,
'ShowPartialItems', false,
}, {
PlaceObj('XTemplateCode', {
'run', function (self, parent, context)
local title = parent:ResolveId("idTitle")
local param = GetDialogModeParam(parent)
if title and param then
title:SetText(param.name)
end
end,
}),
PlaceObj('XTemplateForEach', {
'comment', "item",
'array', function (parent, context) return GetDialogModeParam(parent).items(context) end,
'item_in_context', "prop_meta",
'run_after', function (child, context, item, i, n)
local rollover = item.rollover
if rollover then
child:SetRolloverTitle(rollover.title)
child:SetRolloverText(rollover.descr)
child:SetRolloverHint(rollover.hint)
child:SetRolloverHintGamepad(rollover.gamepad_hint)
end
end,
}, {
PlaceObj('XTemplateTemplate', {
'__template', "PropTrait",
'RolloverTemplate', "Rollover",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Id', "idRollover",
'ZOrder', 0,
'Margins', box(-20, -12, -20, -12),
'Dock', "box",
'Visible', false,
'Image', "UI/CommonNew/re_candidate_rollover.tga",
'FrameBox', box(25, 0, 25, 0),
'SqueezeY', false,
}),
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "ScrollbarNew",
'Id', "idScroll",
'Target', "idList",
}),
}),
}),
PlaceObj('XTemplateMode', {
'mode', "review",
}, {
PlaceObj('XTemplateAction', {
'ActionId', "back",
'ActionName', T(4254, --[[XTemplate ResupplyPassengers ActionName]] "BACK"),
'ActionToolbar', "ActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "mode",
'OnActionParam', "categories",
}),
PlaceObj('XTemplateAction', {
'ActionId', "filter",
'ActionName', T(5460, --[[XTemplate ResupplyPassengers ActionName]] "FILTER"),
'ActionToolbar', "ActionBar",
'ActionGamepad', "RightTrigger",
'OnActionEffect', "mode",
'OnActionParam', "traitCategories",
}),
PlaceObj('XTemplateAction', {
'ActionId', "launch",
'ActionName', T(4253, --[[XTemplate ResupplyPassengers ActionName]] "LAUNCH"),
'ActionToolbar', "ActionBar",
'ActionGamepad', "ButtonX",
'OnAction', function (self, host, source)
LaunchPassengerRocket(host)
end,
'FXPress', "LaunchSupplyRocketClick",
}),
PlaceObj('XTemplateWindow', {
'Id', "idListsWrapper",
'Margins', box(0, 20, 0, 0),
'Dock', "top",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Margins', box(-350, 0, 0, 0),
'Dock', "box",
'VAlign', "top",
'MinWidth', 794,
'Image', "UI/CommonNew/pg_action_bar.tga",
'FrameBox', box(42, 0, 341, 0),
'TileFrame', true,
'SqueezeY', false,
}),
PlaceObj('XTemplateWindow', {
'Margins', box(70, 22, 0, 0),
'Dock', "right",
'VAlign', "top",
'LayoutMethod', "VList",
'LayoutVSpacing', 30,
}, {
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Margins', box(22, 0, 0, 0),
'Padding', box(0, 0, 0, 0),
'Dock', "top",
'HAlign', "left",
'HandleMouse', false,
'TextStyle', "MediumHeader",
'Translate', true,
'Text', T(914430779802, --[[XTemplate ResupplyPassengers Text]] "SELECTED <ApprovedColonists>/<PassengerCapacity>"),
}),
PlaceObj('XTemplateWindow', {
'Margins', box(0, 30, 0, 20),
}, {
PlaceObj('XTemplateWindow', {
'__class', "XContentTemplateList",
'Id', "idRightList",
'Margins', box(0, 0, 30, 0),
'BorderWidth', 0,
'Padding', box(0, 0, 0, 0),
'LayoutVSpacing', 2,
'UniformRowHeight', true,
'Clip', false,
'Background', RGBA(0, 0, 0, 0),
'FocusedBackground', RGBA(0, 0, 0, 0),
'VScroll', "idScrollRight",
'ShowPartialItems', false,
'MouseScroll', true,
'GamepadInitialSelection', false,
'OnContextUpdate', function (self, context, ...)
local focus = self.focused_item
XContentTemplateList.OnContextUpdate(self, context, ...)
if focus and self:IsFocused(true) then
self:DeleteThread("select")
self:CreateThread("select", function(focus)
local list = self
if #self <= 0 then
list = self:ResolveId("idLeftList")
self:SetFocus(false, true)
list:SetFocus()
end
list:SetSelection(false)
list:ScrollTo(0,0, "force")
list:SetSelection(Min(#list, focus))
end, focus)
end
end,
}, {
PlaceObj('XTemplateFunc', {
'name', "OnShortcut(self, shortcut, source)",
'func', function (self, shortcut, source)
if shortcut == "DPadLeft" or shortcut == "LeftThumbLeft" then
local list = self:ResolveId("idLeftList")
if list and #list > 0 then
local right_top = self.focused_item or 1
while self[right_top-1] and not self[right_top-1].outside_parent do
right_top = right_top - 1
end
local diff = (self.focused_item or 1) - right_top
local left_top = list.focused_item or 1
while list[left_top-1] and not list[left_top-1].outside_parent do
left_top = left_top - 1
end
self:SetFocus(false, true)
list:SetFocus()
list:SetSelection(Min(#list, left_top + diff))
end
return "break"
end
return XContentTemplateList.OnShortcut(self, shortcut, source)
end,
}),
PlaceObj('XTemplateMode', {
'mode', "review",
}, {
PlaceObj('XTemplateForEach', {
'comment', "item",
'array', function (parent, context) return context:GetApprovedApplicantsList() end,
'item_in_context', "prop_meta",
'run_before', function (parent, context, item, i, n)
NewXVirtualContent(parent, context, "PropApplicantSelected", 322, 35)
end,
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "ScrollbarNew",
'Id', "idScrollRight",
'Dock', "right",
'Target', "idRightList",
}),
}),
}),
PlaceObj('XTemplateWindow', {
'Margins', box(0, 22, 0, 0),
'VAlign', "top",
'LayoutMethod', "VList",
'LayoutVSpacing', 30,
}, {
PlaceObj('XTemplateWindow', {
'__class', "XText",
'Padding', box(0, 0, 0, 0),
'Dock', "top",
'HAlign', "right",
'HandleMouse', false,
'TextStyle', "MediumHeader",
'Translate', true,
'Text', T(794457706937, --[[XTemplate ResupplyPassengers Text]] "MATCHING APPLICANTS <MatchingColonistsCount>"),
}),
PlaceObj('XTemplateWindow', {
'Margins', box(0, 30, 0, 20),
}, {
PlaceObj('XTemplateWindow', {
'__class', "XContentTemplateList",
'Id', "idLeftList",
'Margins', box(39, 0, 0, 0),
'BorderWidth', 0,
'Padding', box(0, 0, 0, 0),
'MinWidth', 300,
'LayoutVSpacing', 2,
'UniformRowHeight', true,
'Clip', false,
'Background', RGBA(0, 0, 0, 0),
'FocusedBackground', RGBA(0, 0, 0, 0),
'VScroll', "idLeftScroll",
'ShowPartialItems', false,
'MouseScroll', true,
'GamepadInitialSelection', false,
'OnContextUpdate', function (self, context, ...)
local focus = self.focused_item
XContentTemplateList.OnContextUpdate(self, context, ...)
if focus and self:IsFocused(true) then
self:DeleteThread("select")
self:CreateThread("select", function(focus)
local list = self
if #self <= 0 then
list = self:ResolveId("idRightList")
self:SetFocus(false, true)
list:SetFocus()
end
list:SetSelection(false)
list:ScrollTo(0,0, "force")
list:SetSelection(Min(#list, focus))
end, focus)
end
end,
}, {
PlaceObj('XTemplateFunc', {
'name', "Open",
'func', function (self, ...)
local list = #self > 0 and self or self:ResolveId("idRightList")
list:SetFocus()
if GetUIStyleGamepad() then
list:SetSelection(1)
end
XContentTemplateList.Open(self, ...)
end,
}),
PlaceObj('XTemplateFunc', {
'name', "OnShortcut(self, shortcut, source)",
'func', function (self, shortcut, source)
if shortcut == "DPadRight" or shortcut == "LeftThumbRight" then
local list = self:ResolveId("idRightList")
if list and #list > 0 then
local left_top = self.focused_item or 1
while self[left_top-1] and not self[left_top-1].outside_parent do
left_top = left_top - 1
end
local diff = (self.focused_item or 1) - left_top
local right_top = list.focused_item or 1
while list[right_top-1] and not list[right_top-1].outside_parent do
right_top = right_top - 1
end
self:SetFocus(false, true)
list:SetFocus()
list:SetSelection(Min(#list, right_top + diff))
end
return "break"
end
return XContentTemplateList.OnShortcut(self, shortcut, source)
end,
}),
PlaceObj('XTemplateMode', {
'mode', "review",
}, {
PlaceObj('XTemplateForEach', {
'comment', "item",
'array', function (parent, context) return context:GetMatchingApplicantsList() end,
'item_in_context', "prop_meta",
'run_before', function (parent, context, item, i, n)
NewXVirtualContent(parent, context, "PropApplicant", 300, 35)
end,
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "ScrollbarNew",
'Id', "idLeftScroll",
'Target', "idLeftList",
}),
}),
}),
}),
}),
}),
}),
}),
})
|
local Typer = require(script.Parent.Parent.Parent.Typer)
local function keys(dictionary)
local keysList = {}
local index = 1
for key in next, dictionary do
keysList[index] = key
index = index + 1
end
return keysList
end
return Typer.AssignSignature(Typer.Table, keys)
|
--[[
The MIT License (MIT)
Copyright (c) 2015 xuwaters@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
local M = { _TYPE = 'module', _NAME = 'sfsio', _VERSION = '1.0.0' }
-- Types
M.T_NULL = 0;
M.T_BOOL = 1;
M.T_BYTE = 2;
M.T_SHORT = 3;
M.T_INT = 4;
M.T_LONG = 5;
M.T_FLOAT = 6;
M.T_DOUBLE = 7;
M.T_UTF_STRING = 8;
M.T_BOOL_ARRAY = 9;
M.T_BYTE_ARRAY = 10;
M.T_SHORT_ARRAY = 11;
M.T_INT_ARRAY = 12;
M.T_LONG_ARRAY = 13;
M.T_FLOAT_ARRAY = 14;
M.T_DOUBLE_ARRAY = 15;
M.T_UTF_STRING_ARRAY = 16;
M.T_SFS_ARRAY = 17;
M.T_SFS_OBJECT = 18;
M.T_CLASS = 19;
M.Encoding = ENC_UTF_8
-- Helpers
local binDecode_NULL = function( tvbuffer, offset )
return nil, offset
end
local binDecode_BOOL = function( tvbuffer, offset )
local val = tvbuffer(offset, 1):uint()
return (val == 1), offset + 1
end
local binDecode_BYTE = function( tvbuffer, offset )
local val = tvbuffer(offset, 1):uint()
return val, offset + 1
end
local binDecode_SHORT = function( tvbuffer, offset )
local val = tvbuffer(offset, 2):int()
return val, offset + 2
end
local binDecode_INT = function( tvbuffer, offset )
local val = tvbuffer(offset, 4):int()
return val, offset + 4
end
-- Int64 object, https://www.wireshark.org/docs/wsdg_html_chunked/lua_module_Int64.html
local binDecode_LONG = function( tvbuffer, offset )
local val = tvbuffer(offset, 8):int64()
-- return val:tonumber(), offset + 8
return tostring(val), offset + 8
end
local binDecode_FLOAT = function( tvbuffer, offset )
local val = tvbuffer(offset, 4):float()
return val, offset + 4
end
local binDecode_DOUBLE = function( tvbuffer, offset )
local val = tvbuffer(offset, 8):float()
return val, offset + 8
end
local binDecode_UTF_STRING = function( tvbuffer, offset )
local strlen
strlen, offset = binDecode_SHORT(tvbuffer, offset)
if strlen < 0 then
error("string length out of range: " .. tostring(strlen))
end
local val = tvbuffer(offset, strlen):string(M.Encoding)
return val, offset + strlen
end
-- array helper
local getTypeArraySize = function( tvbuffer, offset )
local count
count, offset = binDecode_SHORT(tvbuffer, offset)
if count < 0 then
error("array count out of range: " .. count)
else
return count, offset
end
end
local decodeArray = function( tvbuffer, offset, valueDecoder, sizeDecoder )
sizeDecoder = sizeDecoder or getTypeArraySize
local count
count, offset = sizeDecoder(tvbuffer, offset)
local arr = {}
for i=1,count do
local val
val, offset = valueDecoder(tvbuffer, offset)
arr[i] = val
end
return arr, offset
end
local binDecode_BOOL_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_BOOL)
end
-- return tvbuffer_range
local binDecode_BYTE_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_BYTE, binDecode_INT)
end
local binDecode_SHORT_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_SHORT)
end
local binDecode_INT_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_INT)
end
local binDecode_LONG_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_LONG)
end
local binDecode_FLOAT_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_FLOAT)
end
local binDecode_DOUBLE_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_DOUBLE)
end
local binDecode_UTF_STRING_ARRAY = function( tvbuffer, offset )
return decodeArray(tvbuffer, offset, binDecode_UTF_STRING)
end
local binDecode_SFS_ARRAY = function( tvbuffer, offset )
local val
val, offset = M.decodeSFSArray(tvbuffer, offset - 1)
return val, offset
end
local binDecode_SFS_OBJECT = function( tvbuffer, offset )
local val
val, offset = M.decodeSFSObject(tvbuffer, offset - 1)
return val, offset
end
local binDecode_CLASS = function( tvbuffer, offset )
local val
val, offset = binDecode_SFS_OBJECT(tvbuffer, offset)
-- special key: $C, $F
return val, offset
end
-- Funtions
function M.decodeObject( tvbuffer, offset )
-- type
local t = tvbuffer(offset, 1):int()
offset = offset + 1
if t == M.T_NULL then
return binDecode_NULL(tvbuffer, offset)
elseif t == M.T_BOOL then
return binDecode_BOOL(tvbuffer, offset)
elseif t == M.T_BYTE then
return binDecode_BYTE(tvbuffer, offset)
elseif t == M.T_SHORT then
return binDecode_SHORT(tvbuffer, offset)
elseif t == M.T_INT then
return binDecode_INT(tvbuffer, offset)
elseif t == M.T_LONG then
return binDecode_LONG(tvbuffer, offset)
elseif t == M.T_FLOAT then
return binDecode_FLOAT(tvbuffer, offset)
elseif t == M.T_DOUBLE then
return binDecode_DOUBLE(tvbuffer, offset)
elseif t == M.T_UTF_STRING then
return binDecode_UTF_STRING(tvbuffer, offset)
elseif t == M.T_BOOL_ARRAY then
return binDecode_BOOL_ARRAY(tvbuffer, offset)
elseif t == M.T_BYTE_ARRAY then
return binDecode_BYTE_ARRAY(tvbuffer, offset)
elseif t == M.T_SHORT_ARRAY then
return binDecode_SHORT_ARRAY(tvbuffer, offset)
elseif t == M.T_INT_ARRAY then
return binDecode_INT_ARRAY(tvbuffer, offset)
elseif t == M.T_LONG_ARRAY then
return binDecode_LONG_ARRAY(tvbuffer, offset)
elseif t == M.T_FLOAT_ARRAY then
return binDecode_FLOAT_ARRAY(tvbuffer, offset)
elseif t == M.T_DOUBLE_ARRAY then
return binDecode_DOUBLE_ARRAY(tvbuffer, offset)
elseif t == M.T_UTF_STRING_ARRAY then
return binDecode_UTF_STRING_ARRAY(tvbuffer, offset)
elseif t == M.T_SFS_ARRAY then
return binDecode_SFS_ARRAY(tvbuffer, offset)
elseif t == M.T_SFS_OBJECT then
return binDecode_SFS_OBJECT(tvbuffer, offset)
else
error("Unknown object type: " .. t)
end
end
-- @return object, offset
function M.decodeSFSObject(tvbuffer, offset)
-- Type
local t = tvbuffer(offset, 1):int()
offset = offset + 1
if t ~= M.T_SFS_OBJECT then
error("SFSObject type invalid: " .. t)
end
-- Size
local count = tvbuffer(offset, 2):int()
offset = offset + 2
if count < 0 then
error("object size out of range " .. count)
end
local obj = {}
for i=1,count do
-- key
local keylen = tvbuffer(offset, 2):int()
offset = offset + 2
if keylen < 0 or keylen > 255 then
error("key length out of range " .. keylen)
end
local key = tvbuffer(offset, keylen):string(M.Encoding)
offset = offset + keylen
-- Value
local val
val, offset = M.decodeObject(tvbuffer, offset)
obj[key] = val
end
return obj, offset
end
-- @return array, offset
function M.decodeSFSArray(tvbuffer, offset)
-- Type
local t = tvbuffer(offset, 1):int()
offset = offset + 1
if t ~= M.T_SFS_ARRAY then
error("SFSArray type invalid: " .. t)
end
-- Size
local count = tvbuffer(offset, 2):int()
offset = offset + 2
if count < 0 then
error("array size out of range: " .. count)
end
-- Value
local arr = {}
for i=1, count do
local val
val, offset = M.decodeObject(tvbuffer, offset)
arr[i] = val
end
return arr, offset
end
return M
|
-- tree.lua, Lua representation of trees with edge lengths
-- Copyright (C) 2015 Boris Nagaev
-- See the LICENSE file for terms of use.
--[[
https://en.wikipedia.org/wiki/Newick_format#Grammar
The grammar nodes
=================
Tree: The full input Newick Format for a single tree
Subtree: an internal node (and its descendants) or a leaf node
Leaf: a node with no descendants
Internal: a node and its one or more descendants
BranchSet: a set of one or more Branches
Branch: a tree edge and its descendant subtree.
Name: the name of a node
Length: the length of a tree edge.
The grammar rules
=================
Note, "|" separates alternatives.
Tree --> Subtree ";" | Branch ";"
Subtree --> Leaf | Internal
Leaf --> Name
Internal --> "(" BranchSet ")" Name
BranchSet --> Branch | BranchSet "," Branch
Branch --> Subtree Length
Name --> empty | string
Length --> empty | ":" number
Whitespace (spaces, tabs, carriage returns, and linefeeds)
within number is prohibited. Whitespace within string is
often prohibited. Whitespace elsewhere is ignored.
Sometimes the Name string must be of a specified fixed
length; otherwise the punctuation characters from the
grammar (semicolon, parentheses, comma, and colon) are
prohibited.
]]
return function(text, leafs)
local lpeg = require 'lpeg'
local V, R, S, L = lpeg.V, lpeg.R, lpeg.S, lpeg.locale()
local rules = {
"Tree",
Tree = (V("Subtree") + V("Branch")) * ";",
Subtree = V("Leaf") + V("Internal"),
Leaf = V("Name"),
Internal = "(" * V("BranchSet") * ")" * V("Name")^-1,
BranchSet = V("Branch") * ("," * V("BranchSet")) ^ -1,
Branch = V("Subtree") * V("Length")^-1,
Name = (1 - S(";,():"))^1,
Length = (":" * L.digit^1 * ("." * L.digit^1)^-1),
}
rules.Name = lpeg.Cg(rules.Name, "name")
rules.Length = lpeg.Cg(rules.Length, "length")
rules.Branch = lpeg.Ct(rules.Branch)
rules.Tree = lpeg.Ct(rules.Tree)
rules = lpeg.P(rules)
text = text:gsub('%s', '')
local raw = assert(rules:match(text), "Can't parse Newick")
--[[
Example:
rules:match('(A:0.1,B:0.2,(C,D:0.4):0.5);')
{
{
name = "A",
length = ":0.1",
},
{
name = "B",
length = ":0.2",
},
{
{
name = "C",
},
{
name = "D",
length = ":0.4",
},
length = ":0.5",
},
}
]]
local name2leaf = {}
if leafs then
for _, leaf in ipairs(leafs) do
name2leaf[leaf.name] = leaf
end
end
local children_of = {}
local function fromNewick(raw_node)
local name = raw_node.name
local node = name2leaf[name] or {name = name}
children_of[node] = {}
for _, raw_child in ipairs(raw_node) do
local child = fromNewick(raw_child)
local length = raw_child.length
-- remove ":"
length = length and tonumber(length:sub(2))
local edge = {length = length}
children_of[node][child] = edge
end
return node
end
fromNewick(raw)
local Tree = require 'treelua.Tree'
return Tree(children_of)
end
|
local _ab_testing = {}
local http = require "resty.http"
local init_config = require "ngx_spider.config.config"
local ngx = require "ngx"
local op_mysql = require "ngx_spider.lua_script.moudle.op_mysql"
local set_ngx_shared = function(host,uri,uri_type)
local httpc = http.new()
httpc:set_timeout(15000)
local ok, err = httpc:connect(init_config.ab_testing_server["ip"],init_config.ab_testing_server["port"])
if err then
ngx.log(ngx.ERR,'无法连接灰度Nginx,请检查此机器是否正常: ' ,err, " Nginx的地址: " ,init_config.ab_testing_server["ip"] .. ":" .. init_config.ab_testing_server["port"])
return
end
local is_reg = 1
if uri_type == "precise" then
is_reg = 0
end
local request_uri = "/share_set" .. "?" .. "clear=0&zb_start=1&host=" .. host .. "&uri=" .. uri .. "&is_reg=" .. is_reg .. "&version=-1"
local res, err = httpc:request({
path = request_uri,
method = "GET",
headers = {
["Host"] = init_config.ab_testing_server["host"],
},
})
if not res then
ngx.log(ngx.ERR, "请求异常," , "可能的错误原因:" .. err , "URL是:" .. request_uri)
return
end
if res.status >= 400 then
ngx.log(ngx.ERR, "请求异常,状态码是:" ,res.status, "可能的错误原因:" .. err)
return
end
end
function _ab_testing.push_data()
sql = "select uri_type,host,uri from nginx_resource where catch_disaster = '1'"
local res = op_mysql.query_mysql(sql)
for i, v in ipairs(res) do
local uri_type = ngx.escape_uri(v['uri_type'])
local uri = ngx.escape_uri(v['uri'])
local host = ngx.escape_uri(v['host'])
local ok,err = set_ngx_shared(host,uri,uri_type)
if err then
ngx.log(ngx.ERR,'对灰度Nginx进行共享内存修改时,出现异常: ',err)
end
end
return
end
return _ab_testing
|
AddCSLuaFile()
ENT.Base = "bw_printer"
ENT.NiceName = "Nuclear Money Factory"
ENT.MaxHealth = 1650
ENT.Model = "models/props_lab/servers.mdl"
ENT.Material = "models/debug/debugwhite"
ENT.Color = Color(33, 255, 0, 255)
ENT.Power = 4
ENT.LevelStats = {
[0] = {8725000, 9725000, 700000000},
[1] = {17450000, 18450000, 1400000000},
[2] = {34900000, 35900000, 2800000000},
[3] = {69800000, 70800000, 5600000000},
[4] = {139600000, 140600000, nil},
}
// Purchase Price: 700000000
// Name: Nuclear Money Factory
// Limit: 1
AddSpawnableEntity(
{
Class = string.Explode("/",ENT.Folder)[2],
Name = ENT.NiceName,
Category = "Printers",
Model = ENT.Model,
Limit = 1,
Price = 700000000,
}
) |
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua "$0" "$@"
]]
--
-- Issue #194 -- AF_UNIX can't bind source and destination
--
require"regress".export".*"
assert(socket.connect {
path = "foo";
bind = {path="bar"};
})
say("OK")
|
--[========================================================================[
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
--]========================================================================]
local MAJOR, MINOR = "LibDialog", 1.26
if _G[MAJOR] ~= nil and (_G[MAJOR].version and _G[MAJOR].version >= MINOR) then return end
local lib = {}
lib.name = MAJOR
lib.version = MINOR
--Add global variable "LibDialog"
_G[MAJOR] = lib
------------------------------------------------------------------------
-- Local variables, global for the library
------------------------------------------------------------------------
local existingDialogs = {}
------------------------------------------------------------------------
-- Helper functions
------------------------------------------------------------------------
local function StringOrFunctionOrGetString(stringVar)
if type(stringVar) == "function" then
return stringVar()
elseif type(stringVar) == "number" then
return GetString(stringVar)
end
return stringVar
end
------------------------------------------------------------------------
-- Dialog creation functions
------------------------------------------------------------------------
--register the unique dialog name at the global ESO_Dialogs namespace
local function RegisterCustomDialogAtZOsDialogs(dialogName)
ESO_Dialogs[dialogName] = {
canQueue = true,
uniqueIdentifier = "",
title = {
text = "",
},
mainText = {
text = "",
},
buttons = {
[1] = {
text = SI_DIALOG_CONFIRM,
callback = function(dialog) end,
},
[2] = {
text = SI_DIALOG_CANCEL,
callback = function(dialog) end,
}
},
setup = function(dialog, data) end,
}
return ESO_Dialogs[dialogName]
end
--Create the new dialog now
local function createCustomDialog(uniqueAddonName, uniqueDialogName, title, body, callbackYes, callbackNo, callbackSetup)
local dialogName = uniqueAddonName .. "_" .. uniqueDialogName
--Register the unique dialog name at the global ESO_Dialogs namespace now, and add 2 buttons (confirm, reject)
local dialog = RegisterCustomDialogAtZOsDialogs(dialogName)
dialog.title.text = title
dialog.mainText.text = body
dialog.buttons[1].callback = callbackYes
dialog.buttons[2].callback = callbackNo
dialog.setup = callbackSetup
dialog.uniqueIdentifier = dialogName
return dialog
end
--Show the dialog now
local function showDialogNow(uniqueDialogName, data)
--Show the dialog now, and provide it the data
ZO_Dialogs_ShowDialog(uniqueDialogName, data)
end
------------------------------------------------------------------------
-- Library functions
------------------------------------------------------------------------
function lib:RegisterDialog(uniqueAddonName, uniqueDialogName, title, body, callbackYes, callbackNo, callbackSetup, forceUpdate)
--Is any of the needed variables not given?
local titleStr = StringOrFunctionOrGetString(title)
local bodyStr = StringOrFunctionOrGetString(body)
assert (titleStr ~= nil, string.format("[" .. MAJOR .. "]Error: Missing title for dialog with the unique identifier \'%s\', addon \'%s\'!", tostring(uniqueDialogName), tostring(uniqueAddonName)))
assert (bodyStr ~= nil, string.format("[" .. MAJOR .. "]Error: Missing body text for dialog with the unique identifier \'%s\', addon \'%s\'!", tostring(uniqueDialogName), tostring(uniqueAddonName)))
forceUpdate = forceUpdate or false
if callbackYes == nil then
callbackYes = function() end
end
if callbackNo == nil then
callbackNo = function() end
end
if callbackSetup == nil then
callbackSetup = function(dialog, data) end
end
--Is there already a dialog for this addon and does the uniqueDialogName already exist?
if existingDialogs[uniqueAddonName] == nil then
existingDialogs[uniqueAddonName] = {}
end
local dialogs = existingDialogs[uniqueAddonName]
if not forceUpdate then
assert(dialogs[uniqueDialogName] == nil, string.format("[" .. MAJOR .. "]Error: Dialog with the unique identifier \'%s\' is already registered for the addon \'%s\'!", tostring(uniqueDialogName), tostring(uniqueAddonName)))
end
--Create the table for the dialog in the addon
dialogs[uniqueDialogName] = {}
local dialog = dialogs[uniqueDialogName]
--Create the dialog now
dialog.dialog = createCustomDialog(uniqueAddonName, uniqueDialogName, titleStr, bodyStr, callbackYes, callbackNo, callbackSetup)
--return the new created dialog now
return dialog.dialog
end
--Show a registered dialog now
function lib:ShowDialog(uniqueAddonName, uniqueDialogName, data)
--Show the dialog now
local dialogName = uniqueAddonName .. "_" .. uniqueDialogName
assert(ESO_Dialogs[dialogName] ~= nil, string.format("[" .. MAJOR .. "]Error: Dialog with the unique identifier \'%s\' does not exist in ESO_Dialogs, addon \'%s\'!", tostring(uniqueDialogName), tostring(uniqueAddonName)))
--Is there already a dialog for this addon and does the uniqueDialogName already exist?
local dialogs = existingDialogs[uniqueAddonName]
assert(dialogs ~= nil and dialogs[uniqueDialogName] ~= nil, string.format("[" .. MAJOR .. "]Error: Dialog with the unique identifier \'%s\' does not exist for the addon \'%s\'!", tostring(uniqueDialogName), tostring(uniqueAddonName)))
--Show the dialog now
showDialogNow(dialogName, data)
return true
end
--Addon loaded function
local function OnLibraryLoaded(event, name)
--Only load lib if ingame
if name:find("^ZO_") then return end
EVENT_MANAGER:UnregisterForEvent(MAJOR, EVENT_ADD_ON_LOADED)
--Provide the library the "list of registered dialogs"
lib.dialogs = existingDialogs
end
--Load the addon now
EVENT_MANAGER:UnregisterForEvent(MAJOR, EVENT_ADD_ON_LOADED)
EVENT_MANAGER:RegisterForEvent(MAJOR, EVENT_ADD_ON_LOADED, OnLibraryLoaded)
|
-- minmax.lua
local function minmax(values)
local vmin = math.huge
local vmax = -math.huge
for i=1, #values do
vmin = math.min(vmin, values[i])
vmax = math.max(vmax, values[i])
end
return vmin, vmax
end
local values = {10, 2, 5, 20, 3, 12}
local min, max = minmax(values)
io.write("min=", min, ", max=", max)
print("")
|
local plugin_c = import("classes.plugin")
local command = import("classes.command")
local plugin = plugin_c("pluginmanager")
local utilities = require("table-utils")
local generic_admin_template = {
args = {"string"},
perms = {
"administrator"
},
}
local enable = command("enable",utilities.overwrite(generic_admin_template,{
category = "Utilities",
exec = function(msg,args,opts)
local status,message = plugin_handler:load(args[1])
local plugin_data = command_handler:get_metadata().plugins
local embed = {
description = message,
color = discordia.Color.fromHex("ff5100").value,
}
if status then
embed.fields = {
{name = "New commands:",value =
table.concat(plugin_data[args[1]] or {},", ").." "
}
}
end
msg:reply({embed = embed})
end
}))
plugin:add_command(enable)
local disable = command("disable",utilities.overwrite(generic_admin_template,{
category = "Utilities",
exec = function(msg,args,opts)
local plugin_data = command_handler:get_metadata().plugins
if not (args[1] == "plugins") then
local status,message = plugin_handler:unload(args[1])
local embed = {
description = message,
color = discordia.Color.fromHex("ff5100").value,
}
if status then
embed.fields = {
{name = "Removed commands:",value =
table.concat(plugin_data[args[1]] or {},", ").." "
}
}
end
msg:reply({embed = embed})
else
msg:reply("TIME PARADOX")
end
end
}))
plugin:add_command(disable)
local plugins = command("plugins",utilities.overwrite(generic_admin_template,{
category = "Utilities",
args = {},
exec = function(msg,args,opts)
local all_plugins = plugin_handler:list_loadable()
local unloaded_plugins = {}
local loaded_plugins = {}
for k,v in pairs(all_plugins) do
if not v.loaded then
table.insert(unloaded_plugins,k)
else
table.insert(loaded_plugins,k)
end
end
if #unloaded_plugins == 0 then
table.insert(unloaded_plugins," ")
end
msg:reply({embed={
color = discordia.Color.fromHex("ff5100").value,
fields = {
{name = "Loaded plugins",value = "``"..table.concat(loaded_plugins,"``,\n``").."``"},
{name = "Unloaded plugins",value = "``"..table.concat(unloaded_plugins,"``,\n``").."``"}
}
}})
end
}))
plugin:add_command(plugins)
plugin:load_helpdb(plugin_path.."help.lua")
return plugin
|
-- creates a new media item.
-- @return MediaItem
function Track:add_media_item_to_track()
return r.AddMediaItemToTrack(self.pointer)
end
-- [BR] Get media track freeze count (if track isn't frozen at all, returns 0).
-- @return integer
function Track:b_r__get_media_track_freeze_count()
return r.BR_GetMediaTrackFreezeCount(self.pointer)
end
-- [BR] Deprecated, see GetSetMediaTrackInfo_String (v5.95+). Get media track GUID as a string (guidStringOut_sz should be at least 64). To get media track back from GUID string, see BR_GetMediaTrackByGUID.
-- @return string
function Track:b_r__get_media_track_g_u_i_d()
return r.BR_GetMediaTrackGUID(self.pointer)
end
-- [BR] Deprecated, see GetSetMediaTrackInfo (REAPER v5.02+). Get media track layouts for MCP and TCP. Empty string ("") means that layout is set to the default layout. To set media track layouts, see BR_SetMediaTrackLayouts.
-- @return string, string
function Track:b_r__get_media_track_layouts()
return r.BR_GetMediaTrackLayouts(self.pointer)
end
-- Note: To get or set other send attributes, see BR_GetSetTrackSendInfo and BR_GetMediaTrackSendInfo_Track.
-- @category integer
-- @sendidx integer
-- @envelope_type integer
-- @return TrackEnvelope
function Track:b_r__get_media_track_send_info__envelope(category, sendidx, envelope_type)
return r.BR_GetMediaTrackSendInfo_Envelope(self.pointer, category, sendidx, envelope_type)
end
-- Note: To get or set other send attributes, see BR_GetSetTrackSendInfo and BR_GetMediaTrackSendInfo_Envelope.
-- @category integer
-- @sendidx integer
-- @track_type integer
-- @return MediaTrack
function Track:b_r__get_media_track_send_info__track(category, sendidx, track_type)
return r.BR_GetMediaTrackSendInfo_Track(self.pointer, category, sendidx, track_type)
end
-- Note: To get or set other send attributes, see BR_GetMediaTrackSendInfo_Envelope and BR_GetMediaTrackSendInfo_Track.
-- @category integer
-- @sendidx integer
-- @parmname string
-- @set_new_value boolean
-- @new_value number
-- @return number
function Track:b_r__get_set_track_send_info(category, sendidx, parmname, set_new_value, new_value)
return r.BR_GetSetTrackSendInfo(self.pointer, category, sendidx, parmname, set_new_value, new_value)
end
-- To get media track layouts, see BR_GetMediaTrackLayouts.
-- @mcp_layout_name_in string
-- @tcp_layout_name_in string
-- @return boolean
function Track:b_r__set_media_track_layouts(mcp_layout_name_in, tcp_layout_name_in)
return r.BR_SetMediaTrackLayouts(self.pointer, mcp_layout_name_in, tcp_layout_name_in)
end
-- [BR] Get the exact name (like effect.dll, effect.vst3, etc...) of an FX.
-- @fx integer
-- @return string
function Track:b_r__track_f_x__get_f_x_module_name(fx)
local retval, name = r.BR_TrackFX_GetFXModuleName(self.pointer, fx)
if retval then
return name
end
end
-- Return a handle to the given track FX chain window.
-- @return FxChain
function Track:c_f__get_track_f_x_chain()
return r.CF_GetTrackFXChain(self.pointer)
end
-- Set which track effect is active in the track's FX chain. The FX chain window does not have to be open.
-- @index integer
-- @return boolean
function Track:c_f__select_track_f_x(index)
return r.CF_SelectTrackFX(self.pointer, index)
end
-- @is_pan integer
-- @return boolean
function Track:c_surf__get_touch_state(is_pan)
return r.CSurf_GetTouchState(self.pointer, is_pan)
end
-- @en integer
-- @return boolean
function Track:c_surf__on_f_x_change(en)
return r.CSurf_OnFXChange(self.pointer, en)
end
-- @monitor integer
-- @return integer
function Track:c_surf__on_input_monitor_change(monitor)
return r.CSurf_OnInputMonitorChange(self.pointer, monitor)
end
-- @monitor integer
-- @allowgang boolean
-- @return integer
function Track:c_surf__on_input_monitor_change_ex(monitor, allowgang)
return r.CSurf_OnInputMonitorChangeEx(self.pointer, monitor, allowgang)
end
-- @mute integer
-- @return boolean
function Track:c_surf__on_mute_change(mute)
return r.CSurf_OnMuteChange(self.pointer, mute)
end
-- @mute integer
-- @allowgang boolean
-- @return boolean
function Track:c_surf__on_mute_change_ex(mute, allowgang)
return r.CSurf_OnMuteChangeEx(self.pointer, mute, allowgang)
end
-- @pan number
-- @relative boolean
-- @return number
function Track:c_surf__on_pan_change(pan, relative)
return r.CSurf_OnPanChange(self.pointer, pan, relative)
end
-- @pan number
-- @relative boolean
-- @allow_gang boolean
-- @return number
function Track:c_surf__on_pan_change_ex(pan, relative, allow_gang)
return r.CSurf_OnPanChangeEx(self.pointer, pan, relative, allow_gang)
end
-- @recarm integer
-- @return boolean
function Track:c_surf__on_rec_arm_change(recarm)
return r.CSurf_OnRecArmChange(self.pointer, recarm)
end
-- @recarm integer
-- @allowgang boolean
-- @return boolean
function Track:c_surf__on_rec_arm_change_ex(recarm, allowgang)
return r.CSurf_OnRecArmChangeEx(self.pointer, recarm, allowgang)
end
-- @recv_index integer
-- @pan number
-- @relative boolean
-- @return number
function Track:c_surf__on_recv_pan_change(recv_index, pan, relative)
return r.CSurf_OnRecvPanChange(self.pointer, recv_index, pan, relative)
end
-- @recv_index integer
-- @volume number
-- @relative boolean
-- @return number
function Track:c_surf__on_recv_volume_change(recv_index, volume, relative)
return r.CSurf_OnRecvVolumeChange(self.pointer, recv_index, volume, relative)
end
-- @selected integer
-- @return boolean
function Track:c_surf__on_selected_change(selected)
return r.CSurf_OnSelectedChange(self.pointer, selected)
end
-- @send_index integer
-- @pan number
-- @relative boolean
-- @return number
function Track:c_surf__on_send_pan_change(send_index, pan, relative)
return r.CSurf_OnSendPanChange(self.pointer, send_index, pan, relative)
end
-- @send_index integer
-- @volume number
-- @relative boolean
-- @return number
function Track:c_surf__on_send_volume_change(send_index, volume, relative)
return r.CSurf_OnSendVolumeChange(self.pointer, send_index, volume, relative)
end
-- @solo integer
-- @return boolean
function Track:c_surf__on_solo_change(solo)
return r.CSurf_OnSoloChange(self.pointer, solo)
end
-- @solo integer
-- @allowgang boolean
-- @return boolean
function Track:c_surf__on_solo_change_ex(solo, allowgang)
return r.CSurf_OnSoloChangeEx(self.pointer, solo, allowgang)
end
function Track:c_surf__on_track_selection()
return r.CSurf_OnTrackSelection(self.pointer)
end
-- @volume number
-- @relative boolean
-- @return number
function Track:c_surf__on_volume_change(volume, relative)
return r.CSurf_OnVolumeChange(self.pointer, volume, relative)
end
-- @volume number
-- @relative boolean
-- @allow_gang boolean
-- @return number
function Track:c_surf__on_volume_change_ex(volume, relative, allow_gang)
return r.CSurf_OnVolumeChangeEx(self.pointer, volume, relative, allow_gang)
end
-- @width number
-- @relative boolean
-- @return number
function Track:c_surf__on_width_change(width, relative)
return r.CSurf_OnWidthChange(self.pointer, width, relative)
end
-- @width number
-- @relative boolean
-- @allow_gang boolean
-- @return number
function Track:c_surf__on_width_change_ex(width, relative, allow_gang)
return r.CSurf_OnWidthChangeEx(self.pointer, width, relative, allow_gang)
end
-- @mute boolean
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_mute(mute, ignoresurf)
return r.CSurf_SetSurfaceMute(self.pointer, mute, ignoresurf)
end
-- @pan number
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_pan(pan, ignoresurf)
return r.CSurf_SetSurfacePan(self.pointer, pan, ignoresurf)
end
-- @recarm boolean
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_rec_arm(recarm, ignoresurf)
return r.CSurf_SetSurfaceRecArm(self.pointer, recarm, ignoresurf)
end
-- @selected boolean
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_selected(selected, ignoresurf)
return r.CSurf_SetSurfaceSelected(self.pointer, selected, ignoresurf)
end
-- @solo boolean
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_solo(solo, ignoresurf)
return r.CSurf_SetSurfaceSolo(self.pointer, solo, ignoresurf)
end
-- @volume number
-- @ignoresurf IReaperControlSurface
function Track:c_surf__set_surface_volume(volume, ignoresurf)
return r.CSurf_SetSurfaceVolume(self.pointer, volume, ignoresurf)
end
-- @mcp_view boolean
-- @return integer
function Track:c_surf__track_to_i_d(mcp_view)
return r.CSurf_TrackToID(self.pointer, mcp_view)
end
-- see GetTrackEnvelope
-- @return integer
function Track:count_track_envelopes()
return r.CountTrackEnvelopes(self.pointer)
end
-- count the number of items in the track
-- @return integer
function Track:count_track_media_items()
return r.CountTrackMediaItems(self.pointer)
end
-- Create a new MIDI media item, containing no MIDI events. Time is in seconds unless qn is set.
-- @starttime number
-- @endtime number
-- @qn_in boolean
-- @return MediaItem
function Track:create_new_m_i_d_i_item_in_proj(starttime, endtime, qn_in)
return r.CreateNewMIDIItemInProj(self.pointer, starttime, endtime, qn_in)
end
-- Create an audio accessor object for this track. Must only call from the main thread. See CreateTakeAudioAccessor, DestroyAudioAccessor, AudioAccessorStateChanged, GetAudioAccessorStartTime, GetAudioAccessorEndTime, GetAudioAccessorSamples.
-- @return AudioAccessor
function Track:create_track_audio_accessor()
return r.CreateTrackAudioAccessor(self.pointer)
end
-- Create a send/receive (desttrInOptional!=NULL), or a hardware output (desttrInOptional==NULL) with default properties, return >=0 on success (== new send/receive index). See RemoveTrackSend, GetSetTrackSendInfo, GetTrackSendInfo_Value, SetTrackSendInfo_Value.
-- @desttr_in MediaTrack
-- @return integer
function Track:create_track_send(desttr_in)
return r.CreateTrackSend(self.pointer, desttr_in)
end
-- deletes a track
function Track:delete_track()
return r.DeleteTrack(self.pointer)
end
-- @it MediaItem
-- @return boolean
function Track:delete_track_media_item(it)
return r.DeleteTrackMediaItem(self.pointer, it)
end
-- Returns the FX parameter envelope. If the envelope does not exist and create=true, the envelope will be created.
-- @fxindex integer
-- @parameterindex integer
-- @create boolean
-- @return TrackEnvelope
function Track:get_f_x_envelope(fxindex, parameterindex, create)
return r.GetFXEnvelope(self.pointer, fxindex, parameterindex, create)
end
-- @parmname string
-- @return number
function Track:get_media_track_info__value(parmname)
return r.GetMediaTrackInfo_Value(self.pointer, parmname)
end
-- @return MediaTrack
function Track:get_parent_track()
return r.GetParentTrack(self.pointer)
end
-- Returns meter hold state, in dB*0.01 (0 = +0dB, -0.01 = -1dB, 0.02 = +2dB, etc). If clear is set, clears the meter hold. If master track and channel==1024 or channel==1025, returns/clears RMS maximum state.
-- @channel integer
-- @clear boolean
-- @return number
function Track:get_peak_hold_d_b(channel, clear)
return r.Track_GetPeakHoldDB(self.pointer, channel, clear)
end
-- Returns peak meter value (1.0=+0dB, 0.0=-inf) for channel. If master track and channel==1024 or channel==1025, returns RMS meter value. if master track and channel==2048 or channel=2049, returns RMS meter hold value.
-- @channel integer
-- @return number
function Track:get_peak_info(channel)
return r.Track_GetPeakInfo(self.pointer, channel)
end
-- @parmname string
-- @string_need_big string
-- @set_new_value boolean
-- @return string
function Track:get_set_media_track_info__string(parmname, string_need_big, set_new_value)
local retval, string_need_big_ = r.GetSetMediaTrackInfo_String(self.pointer, parmname, string_need_big, set_new_value)
if retval then
return string_need_big_
end
end
-- @groupname string
-- @setmask integer
-- @setvalue integer
-- @return integer
function Track:get_set_track_group_membership(groupname, setmask, setvalue)
return r.GetSetTrackGroupMembership(self.pointer, groupname, setmask, setvalue)
end
-- @groupname string
-- @setmask integer
-- @setvalue integer
-- @return integer
function Track:get_set_track_group_membership_high(groupname, setmask, setvalue)
return r.GetSetTrackGroupMembershipHigh(self.pointer, groupname, setmask, setvalue)
end
-- @category integer
-- @sendidx integer
-- @parmname string
-- @string_need_big string
-- @set_new_value boolean
-- @return string
function Track:get_set_track_send_info__string(category, sendidx, parmname, string_need_big, set_new_value)
local retval, string_need_big_ = r.GetSetTrackSendInfo_String(self.pointer, category, sendidx, parmname, string_need_big, set_new_value)
if retval then
return string_need_big_
end
end
-- deprecated -- see SetTrackStateChunk, GetTrackStateChunk
-- @str string
-- @return string
function Track:get_set_track_state(str)
local retval, str_ = r.GetSetTrackState(self.pointer, str)
if retval then
return str_
end
end
-- deprecated -- see SetTrackStateChunk, GetTrackStateChunk
-- @str string
-- @isundo boolean
-- @return string
function Track:get_set_track_state2(str, isundo)
local retval, str_ = r.GetSetTrackState2(self.pointer, str, isundo)
if retval then
return str_
end
end
-- return the track mode, regardless of global override
-- @return integer
function Track:get_track_automation_mode()
return r.GetTrackAutomationMode(self.pointer)
end
-- Returns the track custom color as OS dependent color|0x100000 (i.e. ColorToNative(r,g,b)|0x100000). Black is returned as 0x01000000, no color setting is returned as 0.
-- @return integer
function Track:get_track_color()
return r.GetTrackColor(self.pointer)
end
-- @return integer
function Track:get_track_depth()
return r.GetTrackDepth(self.pointer)
end
-- @envidx integer
-- @return TrackEnvelope
function Track:get_track_envelope(envidx)
return r.GetTrackEnvelope(self.pointer, envidx)
end
-- @cfgchunkname_or_guid string
-- @return TrackEnvelope
function Track:get_track_envelope_by_chunk_name(cfgchunkname_or_guid)
return r.GetTrackEnvelopeByChunkName(self.pointer, cfgchunkname_or_guid)
end
-- @envname string
-- @return TrackEnvelope
function Track:get_track_envelope_by_name(envname)
return r.GetTrackEnvelopeByName(self.pointer, envname)
end
-- @return string
function Track:get_track_g_u_i_d()
return r.GetTrackGUID(self.pointer)
end
-- Get all MIDI lyrics on the track. Lyrics will be returned as one string with tabs between each word. flag&1: double tabs at the end of each measure and triple tabs when skipping measures, flag&2: each lyric is preceded by its beat position in the project (example with flag=2: "1.1.2\tLyric for measure 1 beat 2\t.1.1\tLyric for measure 2 beat 1 "). See SetTrackMIDILyrics
-- @flag integer
-- @buf_want string
-- @return string
function Track:get_track_m_i_d_i_lyrics(flag, buf_want)
local retval, buf_want_ = r.GetTrackMIDILyrics(self.pointer, flag, buf_want)
if retval then
return buf_want_
end
end
-- @itemidx integer
-- @return MediaItem
function Track:get_track_media_item(itemidx)
return r.GetTrackMediaItem(self.pointer, itemidx)
end
-- Returns "MASTER" for master track, "Track N" if track has no name.
-- @return string
function Track:get_track_name()
local retval, buf = r.GetTrackName(self.pointer)
if retval then
return buf
end
end
-- @return integer
function Track:get_track_num_media_items()
return r.GetTrackNumMediaItems(self.pointer)
end
-- returns number of sends/receives/hardware outputs - category is <0 for receives, 0=sends, >0 for hardware outputs
-- @category integer
-- @return integer
function Track:get_track_num_sends(category)
return r.GetTrackNumSends(self.pointer, category)
end
-- See GetTrackSendName.
-- @recv_index integer
-- @buf string
-- @return string
function Track:get_track_receive_name(recv_index, buf)
local retval, buf_ = r.GetTrackReceiveName(self.pointer, recv_index, buf)
if retval then
return buf_
end
end
-- See GetTrackSendUIMute.
-- @recv_index integer
-- @return boolean
function Track:get_track_receive_u_i_mute(recv_index)
local retval, mute = r.GetTrackReceiveUIMute(self.pointer, recv_index)
if retval then
return mute
end
end
-- See GetTrackSendUIVolPan.
-- @recv_index integer
-- @return number, number
function Track:get_track_receive_u_i_vol_pan(recv_index)
local retval, volume, pan = r.GetTrackReceiveUIVolPan(self.pointer, recv_index)
if retval then
return volume, pan
end
end
-- See CreateTrackSend, RemoveTrackSend, GetTrackNumSends.
-- @category integer
-- @sendidx integer
-- @parmname string
-- @return number
function Track:get_track_send_info__value(category, sendidx, parmname)
return r.GetTrackSendInfo_Value(self.pointer, category, sendidx, parmname)
end
-- send_idx>=0 for hw ouputs, >=nb_of_hw_ouputs for sends. See GetTrackReceiveName.
-- @send_index integer
-- @buf string
-- @return string
function Track:get_track_send_name(send_index, buf)
local retval, buf_ = r.GetTrackSendName(self.pointer, send_index, buf)
if retval then
return buf_
end
end
-- send_idx>=0 for hw ouputs, >=nb_of_hw_ouputs for sends. See GetTrackReceiveUIMute.
-- @send_index integer
-- @return boolean
function Track:get_track_send_u_i_mute(send_index)
local retval, mute = r.GetTrackSendUIMute(self.pointer, send_index)
if retval then
return mute
end
end
-- send_idx>=0 for hw ouputs, >=nb_of_hw_ouputs for sends. See GetTrackReceiveUIVolPan.
-- @send_index integer
-- @return number, number
function Track:get_track_send_u_i_vol_pan(send_index)
local retval, volume, pan = r.GetTrackSendUIVolPan(self.pointer, send_index)
if retval then
return volume, pan
end
end
-- &1024=hide from MCP
-- @return number
function Track:get_track_state()
local retval, flags = r.GetTrackState(self.pointer)
if retval then
return flags
end
end
-- Gets the RPPXML state of a track, returns true if successful. Undo flag is a performance/caching hint.
-- @str string
-- @isundo boolean
-- @return string
function Track:get_track_state_chunk(str, isundo)
local retval, str_ = r.GetTrackStateChunk(self.pointer, str, isundo)
if retval then
return str_
end
end
-- @return boolean
function Track:get_track_u_i_mute()
local retval, mute = r.GetTrackUIMute(self.pointer)
if retval then
return mute
end
end
-- @return number, number, number
function Track:get_track_u_i_pan()
local retval, pan1, pan2, panmode = r.GetTrackUIPan(self.pointer)
if retval then
return pan1, pan2, panmode
end
end
-- @return number, number
function Track:get_track_u_i_vol_pan()
local retval, volume, pan = r.GetTrackUIVolPan(self.pointer)
if retval then
return volume, pan
end
end
-- @return boolean
function Track:is_track_selected()
return r.IsTrackSelected(self.pointer)
end
-- If mixer==true, returns true if the track is visible in the mixer. If mixer==false, returns true if the track is visible in the track control panel.
-- @mixer boolean
-- @return boolean
function Track:is_track_visible(mixer)
return r.IsTrackVisible(self.pointer, mixer)
end
-- Get a string that only changes when the MIDI data changes. If notesonly==true, then the string changes only when the MIDI notes change. See MIDI_GetHash
-- @notesonly boolean
-- @hash string
-- @return string
function Track:m_i_d_i__get_track_hash(notesonly, hash)
local retval, hash_ = r.MIDI_GetTrackHash(self.pointer, notesonly, hash)
if retval then
return hash_
end
end
-- If track is supplied, item is ignored
-- @item MediaItem
function Track:mark_track_items_dirty(item)
return r.MarkTrackItemsDirty(self.pointer, item)
end
-- @return string
function Track:n_f__get_s_w_s_track_notes()
return r.NF_GetSWSTrackNotes(self.pointer)
end
-- @str string
function Track:n_f__set_s_w_s_track_notes(str)
return r.NF_SetSWSTrackNotes(self.pointer, str)
end
-- Remove a send/receive/hardware output, return true on success. category is <0 for receives, 0=sends, >0 for hardware outputs. See CreateTrackSend, GetSetTrackSendInfo, GetTrackSendInfo_Value, SetTrackSendInfo_Value, GetTrackNumSends.
-- @category integer
-- @sendidx integer
-- @return boolean
function Track:remove_track_send(category, sendidx)
return r.RemoveTrackSend(self.pointer, category, sendidx)
end
-- Note: obeys default sends preferences, supports frozen tracks, etc..
-- @dest MediaTrack
-- @type integer
-- @return boolean
function Track:s_n_m__add_receive(dest, type)
return r.SNM_AddReceive(self.pointer, dest, type)
end
-- [S&M] Add an FX parameter knob in the TCP. Returns false if nothing updated (invalid parameters, knob already present, etc..)
-- @fx_id integer
-- @prm_id integer
-- @return boolean
function Track:s_n_m__add_t_c_p_f_x_parm(fx_id, prm_id)
return r.SNM_AddTCPFXParm(self.pointer, fx_id, prm_id)
end
-- fxId: fx index in chain or -1 for the selected fx. what: 0 to remove, -1 to move fx up in chain, 1 to move fx down in chain.
-- @fx_id integer
-- @what integer
-- @return boolean
function Track:s_n_m__move_or_remove_track_f_x(fx_id, what)
return r.SNM_MoveOrRemoveTrackFX(self.pointer, fx_id, what)
end
-- [S&M] Deprecated, see RemoveTrackSend (v5.15pre1+). Removes a receive. Returns false if nothing updated.
-- @rcvidx integer
-- @return boolean
function Track:s_n_m__remove_receive(rcvidx)
return r.SNM_RemoveReceive(self.pointer, rcvidx)
end
-- [S&M] Removes all receives from srctr. Returns false if nothing updated.
-- @srctr MediaTrack
-- @return boolean
function Track:s_n_m__remove_receives_from(srctr)
return r.SNM_RemoveReceivesFrom(self.pointer, srctr)
end
-- @parmname string
-- @newvalue number
-- @return boolean
function Track:set_media_track_info__value(parmname, newvalue)
return r.SetMediaTrackInfo_Value(self.pointer, parmname, newvalue)
end
-- Scroll the mixer so that leftmosttrack is the leftmost visible track. Returns the leftmost track after scrolling, which may be different from the passed-in track if there are not enough tracks to its right.
-- @return MediaTrack
function Track:set_mixer_scroll()
return r.SetMixerScroll(self.pointer)
end
-- Set exactly one track selected, deselect all others
function Track:set_only_track_selected()
return r.SetOnlyTrackSelected(self.pointer)
end
-- @mode integer
function Track:set_track_automation_mode(mode)
return r.SetTrackAutomationMode(self.pointer, mode)
end
-- Set the custom track color, color is OS dependent (i.e. ColorToNative(r,g,b).
-- @color integer
function Track:set_track_color(color)
return r.SetTrackColor(self.pointer, color)
end
-- Set all MIDI lyrics on the track. Lyrics will be stuffed into any MIDI items found in range. Flag is unused at present. str is passed in as beat position, tab, text, tab (example with flag=2: "1.1.2\tLyric for measure 1 beat 2\t.1.1\tLyric for measure 2 beat 1 "). See GetTrackMIDILyrics
-- @flag integer
-- @str string
-- @return boolean
function Track:set_track_m_i_d_i_lyrics(flag, str)
return r.SetTrackMIDILyrics(self.pointer, flag, str)
end
-- @selected boolean
function Track:set_track_selected(selected)
return r.SetTrackSelected(self.pointer, selected)
end
-- See CreateTrackSend, RemoveTrackSend, GetTrackNumSends.
-- @category integer
-- @sendidx integer
-- @parmname string
-- @newvalue number
-- @return boolean
function Track:set_track_send_info__value(category, sendidx, parmname, newvalue)
return r.SetTrackSendInfo_Value(self.pointer, category, sendidx, parmname, newvalue)
end
-- send_idx<0 for receives, >=0 for hw ouputs, >=nb_of_hw_ouputs for sends. isend=1 for end of edit, -1 for an instant edit (such as reset), 0 for normal tweak.
-- @send_idx integer
-- @pan number
-- @isend integer
-- @return boolean
function Track:set_track_send_u_i_pan(send_idx, pan, isend)
return r.SetTrackSendUIPan(self.pointer, send_idx, pan, isend)
end
-- send_idx<0 for receives, >=0 for hw ouputs, >=nb_of_hw_ouputs for sends. isend=1 for end of edit, -1 for an instant edit (such as reset), 0 for normal tweak.
-- @send_idx integer
-- @vol number
-- @isend integer
-- @return boolean
function Track:set_track_send_u_i_vol(send_idx, vol, isend)
return r.SetTrackSendUIVol(self.pointer, send_idx, vol, isend)
end
-- Sets the RPPXML state of a track, returns true if successful. Undo flag is a performance/caching hint.
-- @str string
-- @isundo boolean
-- @return boolean
function Track:set_track_state_chunk(str, isundo)
return r.SetTrackStateChunk(self.pointer, str, isundo)
end
-- send_idx<0 for receives, >=0 for hw ouputs, >=nb_of_hw_ouputs for sends.
-- @send_idx integer
-- @return boolean
function Track:toggle_track_send_u_i_mute(send_idx)
return r.ToggleTrackSendUIMute(self.pointer, send_idx)
end
-- Adds or queries the position of a named FX from the track FX chain (recFX=false) or record input FX/monitoring FX (recFX=true, monitoring FX are on master track). Specify a negative value for instantiate to always create a new effect, 0 to only query the first instance of an effect, or a positive value to add an instance if one is not found. If instantiate is <= -1000, it is used for the insertion position (-1000 is first item in chain, -1001 is second, etc). fxname can have prefix to specify type: VST3:,VST2:,VST:,AU:,JS:, or DX:, or FXADD: which adds selected items from the currently-open FX browser, FXADD:2 to limit to 2 FX added, or FXADD:2e to only succeed if exactly 2 FX are selected. Returns -1 on failure or the new position in chain on success.
-- @fxname string
-- @rec_f_x boolean
-- @instantiate integer
-- @return integer
function Track:track_f_x__add_by_name(fxname, rec_f_x, instantiate)
return r.TrackFX_AddByName(self.pointer, fxname, rec_f_x, instantiate)
end
-- Copies (or moves) FX from src_track to dest_take. src_fx can have 0x1000000 set to reference input FX.
-- @src_fx integer
-- @dest_take MediaItem_Take
-- @dest_fx integer
-- @is_move boolean
function Track:track_f_x__copy_to_take(src_fx, dest_take, dest_fx, is_move)
return r.TrackFX_CopyToTake(self.pointer, src_fx, dest_take, dest_fx, is_move)
end
-- Copies (or moves) FX from src_track to dest_track. Can be used with src_track=dest_track to reorder, FX indices have 0x1000000 set to reference input FX.
-- @src_fx integer
-- @dest_track MediaTrack
-- @dest_fx integer
-- @is_move boolean
function Track:track_f_x__copy_to_track(src_fx, dest_track, dest_fx, is_move)
return r.TrackFX_CopyToTrack(self.pointer, src_fx, dest_track, dest_fx, is_move)
end
-- Remove a FX from track chain (returns true on success)
-- @fx integer
-- @return boolean
function Track:track_f_x__delete(fx)
return r.TrackFX_Delete(self.pointer, fx)
end
-- @fx integer
-- @param integer
-- @return boolean
function Track:track_f_x__end_param_edit(fx, param)
return r.TrackFX_EndParamEdit(self.pointer, fx, param)
end
-- Note: only works with FX that support Cockos VST extensions.
-- @fx integer
-- @param integer
-- @val number
-- @buf string
-- @return string
function Track:track_f_x__format_param_value(fx, param, val, buf)
local retval, buf_ = r.TrackFX_FormatParamValue(self.pointer, fx, param, val, buf)
if retval then
return buf_
end
end
-- Note: only works with FX that support Cockos VST extensions.
-- @fx integer
-- @param integer
-- @value number
-- @buf string
-- @return string
function Track:track_f_x__format_param_value_normalized(fx, param, value, buf)
local retval, buf_ = r.TrackFX_FormatParamValueNormalized(self.pointer, fx, param, value, buf)
if retval then
return buf_
end
end
-- Get the index of the first track FX insert that matches fxname. If the FX is not in the chain and instantiate is true, it will be inserted. See TrackFX_GetInstrument, TrackFX_GetEQ. Deprecated in favor of TrackFX_AddByName.
-- @fxname string
-- @instantiate boolean
-- @return integer
function Track:track_f_x__get_by_name(fxname, instantiate)
return r.TrackFX_GetByName(self.pointer, fxname, instantiate)
end
-- returns index of effect visible in chain, or -1 for chain hidden, or -2 for chain visible but no effect selected
-- @return integer
function Track:track_f_x__get_chain_visible()
return r.TrackFX_GetChainVisible(self.pointer)
end
-- @return integer
function Track:track_f_x__get_count()
return r.TrackFX_GetCount(self.pointer)
end
-- Get the index of ReaEQ in the track FX chain. If ReaEQ is not in the chain and instantiate is true, it will be inserted. See TrackFX_GetInstrument, TrackFX_GetByName.
-- @instantiate boolean
-- @return integer
function Track:track_f_x__get_e_q(instantiate)
return r.TrackFX_GetEQ(self.pointer, instantiate)
end
-- See TrackFX_GetEQ, TrackFX_GetEQParam, TrackFX_SetEQParam, TrackFX_SetEQBandEnabled.
-- @fxidx integer
-- @bandtype integer
-- @bandidx integer
-- @return boolean
function Track:track_f_x__get_e_q_band_enabled(fxidx, bandtype, bandidx)
return r.TrackFX_GetEQBandEnabled(self.pointer, fxidx, bandtype, bandidx)
end
-- See TrackFX_GetEQ, TrackFX_SetEQParam, TrackFX_GetEQBandEnabled, TrackFX_SetEQBandEnabled.
-- @fxidx integer
-- @paramidx integer
-- @return number, number, number, number
function Track:track_f_x__get_e_q_param(fxidx, paramidx)
local retval, bandtype, bandidx, paramtype, normval = r.TrackFX_GetEQParam(self.pointer, fxidx, paramidx)
if retval then
return bandtype, bandidx, paramtype, normval
end
end
-- See TrackFX_SetEnabled
-- @fx integer
-- @return boolean
function Track:track_f_x__get_enabled(fx)
return r.TrackFX_GetEnabled(self.pointer, fx)
end
-- @fx integer
-- @return string
function Track:track_f_x__get_f_x_g_u_i_d(fx)
return r.TrackFX_GetFXGUID(self.pointer, fx)
end
-- @fx integer
-- @buf string
-- @return string
function Track:track_f_x__get_f_x_name(fx, buf)
local retval, buf_ = r.TrackFX_GetFXName(self.pointer, fx, buf)
if retval then
return buf_
end
end
-- returns HWND of floating window for effect index, if any
-- @index integer
-- @return HWND
function Track:track_f_x__get_floating_window(index)
return r.TrackFX_GetFloatingWindow(self.pointer, index)
end
-- @fx integer
-- @param integer
-- @buf string
-- @return string
function Track:track_f_x__get_formatted_param_value(fx, param, buf)
local retval, buf_ = r.TrackFX_GetFormattedParamValue(self.pointer, fx, param, buf)
if retval then
return buf_
end
end
-- sets the number of input/output pins for FX if available, returns plug-in type or -1 on error
-- @fx integer
-- @return number, number
function Track:track_f_x__get_i_o_size(fx)
local retval, input_pins, output_pins = r.TrackFX_GetIOSize(self.pointer, fx)
if retval then
return input_pins, output_pins
end
end
-- Get the index of the first track FX insert that is a virtual instrument, or -1 if none. See TrackFX_GetEQ, TrackFX_GetByName.
-- @return integer
function Track:track_f_x__get_instrument()
return r.TrackFX_GetInstrument(self.pointer)
end
-- gets plug-in specific named configuration value (returns true on success). Special values: 'pdc' returns PDC latency. 'in_pin_0' returns name of first input pin (if available), 'out_pin_0' returns name of first output pin (if available), etc.
-- @fx integer
-- @parmname string
-- @return string
function Track:track_f_x__get_named_config_parm(fx, parmname)
local retval, buf = r.TrackFX_GetNamedConfigParm(self.pointer, fx, parmname)
if retval then
return buf
end
end
-- @fx integer
-- @return integer
function Track:track_f_x__get_num_params(fx)
return r.TrackFX_GetNumParams(self.pointer, fx)
end
-- See TrackFX_SetOffline
-- @fx integer
-- @return boolean
function Track:track_f_x__get_offline(fx)
return r.TrackFX_GetOffline(self.pointer, fx)
end
-- Returns true if this FX UI is open in the FX chain window or a floating window. See TrackFX_SetOpen
-- @fx integer
-- @return boolean
function Track:track_f_x__get_open(fx)
return r.TrackFX_GetOpen(self.pointer, fx)
end
-- @fx integer
-- @param integer
-- @return number, number
function Track:track_f_x__get_param(fx, param)
local retval, minval, maxval = r.TrackFX_GetParam(self.pointer, fx, param)
if retval then
return minval, maxval
end
end
-- @fx integer
-- @param integer
-- @return number, number, number
function Track:track_f_x__get_param_ex(fx, param)
local retval, minval, maxval, midval = r.TrackFX_GetParamEx(self.pointer, fx, param)
if retval then
return minval, maxval, midval
end
end
-- @fx integer
-- @param integer
-- @buf string
-- @return string
function Track:track_f_x__get_param_name(fx, param, buf)
local retval, buf_ = r.TrackFX_GetParamName(self.pointer, fx, param, buf)
if retval then
return buf_
end
end
-- @fx integer
-- @param integer
-- @return number
function Track:track_f_x__get_param_normalized(fx, param)
return r.TrackFX_GetParamNormalized(self.pointer, fx, param)
end
-- @fx integer
-- @param integer
-- @return number, number, number, boolean
function Track:track_f_x__get_parameter_step_sizes(fx, param)
local retval, step, smallstep, largestep, istoggle = r.TrackFX_GetParameterStepSizes(self.pointer, fx, param)
if retval then
return step, smallstep, largestep, istoggle
end
end
-- gets the effective channel mapping bitmask for a particular pin. high32OutOptional will be set to the high 32 bits
-- @fx integer
-- @isoutput integer
-- @pin integer
-- @return number
function Track:track_f_x__get_pin_mappings(fx, isoutput, pin)
local retval, high32 = r.TrackFX_GetPinMappings(self.pointer, fx, isoutput, pin)
if retval then
return high32
end
end
-- Get the name of the preset currently showing in the REAPER dropdown, or the full path to a factory preset file for VST3 plug-ins (.vstpreset). Returns false if the current FX parameters do not exactly match the preset (in other words, if the user loaded the preset but moved the knobs afterward). See TrackFX_SetPreset.
-- @fx integer
-- @presetname string
-- @return string
function Track:track_f_x__get_preset(fx, presetname)
local retval, presetname_ = r.TrackFX_GetPreset(self.pointer, fx, presetname)
if retval then
return presetname_
end
end
-- Returns current preset index, or -1 if error. numberOfPresetsOut will be set to total number of presets available. See TrackFX_SetPresetByIndex
-- @fx integer
-- @return number
function Track:track_f_x__get_preset_index(fx)
local retval, number_of_presets = r.TrackFX_GetPresetIndex(self.pointer, fx)
if retval then
return number_of_presets
end
end
-- returns index of effect visible in record input chain, or -1 for chain hidden, or -2 for chain visible but no effect selected
-- @return integer
function Track:track_f_x__get_rec_chain_visible()
return r.TrackFX_GetRecChainVisible(self.pointer)
end
-- returns count of record input FX. To access record input FX, use a FX indices [0x1000000..0x1000000+n). On the master track, this accesses monitoring FX rather than record input FX.
-- @return integer
function Track:track_f_x__get_rec_count()
return r.TrackFX_GetRecCount(self.pointer)
end
-- @fx integer
-- @fn string
-- @return string
function Track:track_f_x__get_user_preset_filename(fx, fn)
return r.TrackFX_GetUserPresetFilename(self.pointer, fx, fn)
end
-- presetmove==1 activates the next preset, presetmove==-1 activates the previous preset, etc.
-- @fx integer
-- @presetmove integer
-- @return boolean
function Track:track_f_x__navigate_presets(fx, presetmove)
return r.TrackFX_NavigatePresets(self.pointer, fx, presetmove)
end
-- See TrackFX_GetEQ, TrackFX_GetEQParam, TrackFX_SetEQParam, TrackFX_GetEQBandEnabled.
-- @fxidx integer
-- @bandtype integer
-- @bandidx integer
-- @enable boolean
-- @return boolean
function Track:track_f_x__set_e_q_band_enabled(fxidx, bandtype, bandidx, enable)
return r.TrackFX_SetEQBandEnabled(self.pointer, fxidx, bandtype, bandidx, enable)
end
-- See TrackFX_GetEQ, TrackFX_GetEQParam, TrackFX_GetEQBandEnabled, TrackFX_SetEQBandEnabled.
-- @fxidx integer
-- @bandtype integer
-- @bandidx integer
-- @paramtype integer
-- @val number
-- @isnorm boolean
-- @return boolean
function Track:track_f_x__set_e_q_param(fxidx, bandtype, bandidx, paramtype, val, isnorm)
return r.TrackFX_SetEQParam(self.pointer, fxidx, bandtype, bandidx, paramtype, val, isnorm)
end
-- See TrackFX_GetEnabled
-- @fx integer
-- @enabled boolean
function Track:track_f_x__set_enabled(fx, enabled)
return r.TrackFX_SetEnabled(self.pointer, fx, enabled)
end
-- sets plug-in specific named configuration value (returns true on success)
-- @fx integer
-- @parmname string
-- @value string
-- @return boolean
function Track:track_f_x__set_named_config_parm(fx, parmname, value)
return r.TrackFX_SetNamedConfigParm(self.pointer, fx, parmname, value)
end
-- See TrackFX_GetOffline
-- @fx integer
-- @offline boolean
function Track:track_f_x__set_offline(fx, offline)
return r.TrackFX_SetOffline(self.pointer, fx, offline)
end
-- Open this FX UI. See TrackFX_GetOpen
-- @fx integer
-- @open boolean
function Track:track_f_x__set_open(fx, open)
return r.TrackFX_SetOpen(self.pointer, fx, open)
end
-- @fx integer
-- @param integer
-- @val number
-- @return boolean
function Track:track_f_x__set_param(fx, param, val)
return r.TrackFX_SetParam(self.pointer, fx, param, val)
end
-- @fx integer
-- @param integer
-- @value number
-- @return boolean
function Track:track_f_x__set_param_normalized(fx, param, value)
return r.TrackFX_SetParamNormalized(self.pointer, fx, param, value)
end
-- sets the channel mapping bitmask for a particular pin. returns false if unsupported (not all types of plug-ins support this capability)
-- @fx integer
-- @isoutput integer
-- @pin integer
-- @low32bits integer
-- @hi32bits integer
-- @return boolean
function Track:track_f_x__set_pin_mappings(fx, isoutput, pin, low32bits, hi32bits)
return r.TrackFX_SetPinMappings(self.pointer, fx, isoutput, pin, low32bits, hi32bits)
end
-- Activate a preset with the name shown in the REAPER dropdown. Full paths to .vstpreset files are also supported for VST3 plug-ins. See TrackFX_GetPreset.
-- @fx integer
-- @presetname string
-- @return boolean
function Track:track_f_x__set_preset(fx, presetname)
return r.TrackFX_SetPreset(self.pointer, fx, presetname)
end
-- Sets the preset idx, or the factory preset (idx==-2), or the default user preset (idx==-1). Returns true on success. See TrackFX_GetPresetIndex.
-- @fx integer
-- @idx integer
-- @return boolean
function Track:track_f_x__set_preset_by_index(fx, idx)
return r.TrackFX_SetPresetByIndex(self.pointer, fx, idx)
end
-- showflag=0 for hidechain, =1 for show chain(index valid), =2 for hide floating window(index valid), =3 for show floating window (index valid)
-- @index integer
-- @show_flag integer
function Track:track_f_x__show(index, show_flag)
return r.TrackFX_Show(self.pointer, index, show_flag)
end
|
local component = require("component")
if component.isAvailable("nc_fission_reactor") then
r = component.proxy(component.nc_fission_reactor.address)
else
--Some kind of error handling or break
end
tMax = r.getMaxHeatLevel()
eMax = r.getMaxEnergyStored()
while true
t = r.getHeatLevel()
e = r.getEnergyLevel()
ePercent = e / eMax
if ePercent < 0.8 then
r.activate()
else
r.deactivate()
end
end |
graphics.enableGraphicsMode(256)
x,y = graphics.getSize()
graphics.drawRect(1,1,x,y,0)
graphics.drawRect(1,25,x,y,1)
graphics.drawRect(1,50,x,y,2)
graphics.drawRect(1,75,x,y,3)
graphics.drawRect(1,100,x,y,4)
graphics.drawRect(1,125,x,y,5)
graphics.drawRect(1,150,x,y,6)
graphics.drawRect(1,175,x,y,7)
graphics.drawRect(1,200,x,y,8)
graphics.drawRect(1,225,x,y,9)
graphics.drawRect(1,250,x,y,10)
graphics.drawRect(1,275,x,y,11)
graphics.drawRect(1,300,x,y,12)
graphics.drawRect(1,325,x,y,13)
graphics.drawRect(1,350,x,y,14)
graphics.drawRect(1,375,x,y,15)
sleep(2)
graphics.disableGraphicsMode()
|
if FirstLoad then
g_TitleObj = false
g_RenameRocketObj = false
g_UIAvailableRockets = 0
g_UITotalRockets = 0
end
DefineClass.PGTitleObject = {
__parents = { "PropertyObject" },
replace_param = false,
replace_value = false,
map_challenge_rating = false,
}
function PGTitleObject:GetTitleText()
local dlg = GetPreGameMainMenu()
if dlg and dlg.Mode == "Challenge" then
local mode = dlg.idContent.PGChallenge.Mode
if mode == "landing" then
return T(10880, "CHALLENGES") .. Untranslated("<newline>") .. T{10881, "<white>Completed <CompletedChallenges>/<TotalChallenges></white>", self}
elseif mode == "payload" then
return T(4159, "PAYLOAD")
else
return ""
end
end
if dlg and dlg.Mode == "Mission" then
local mode = dlg.idContent.PGMission and dlg.idContent.PGMission.Mode or false
if mode == "sponsor" then
return T(10892, "MISSION PARAMETERS") .. Untranslated("<newline>") .. T{10893, "<white>Difficulty Challenge <percent(DifficultyBonus)></white>", self}
elseif mode == "payload" then
return T(4159, "PAYLOAD") .. Untranslated("<newline>") .. T{10893, "<white>Difficulty Challenge <percent(DifficultyBonus)></white>", self}
elseif mode == "landing" then
return T(10894, "COLONY SITE") .. Untranslated("<newline>") .. T{10893, "<white>Difficulty Challenge <percent(DifficultyBonus)></white>", self}
else
return ""
end
end
local dlg = GetDialog("Resupply")
if dlg then
return T(4159, "PAYLOAD") .. Untranslated("<newline>") .. T{10893, "<white>Difficulty Challenge <percent(DifficultyBonus)></white>", self}
end
return ""
end
function PGTitleObject:GetDifficultyBonus()
return 100 + CalcChallengeRating(self.replace_param, self.replace_value, self.map_challenge_rating)
end
function PGTitleObject:GetCompletedChallenges()
return GetCompletedChallenges()
end
function PGTitleObject:GetTotalChallenges()
return GetTotalChallenges()
end
function PGTitleObject:RecalcMapChallengeRating()
self.map_challenge_rating = GetMapChallengeRating()
end
function PGTitleObjectCreate()
g_TitleObj = PGTitleObject:new()
return g_TitleObj
end
function GetCompletedChallenges()
local n = 0
ForEachPreset("Challenge", function(preset)
if preset.id ~= "" and AccountStorage.CompletedChallenges and AccountStorage.CompletedChallenges[preset.id] then
n = n + 1
end
end)
return n
end
function GetTotalChallenges()
local n = 0
ForEachPreset("Challenge", function(preset)
if preset.id ~= "" then
n = n + 1
end
end)
return n
end
local function MissionParamCombo(id)
local items = {}
for k,v in ipairs(MissionParams[id].items) do
if v.filter == nil or v.filter == true or (type(v.filter) == "function" and v:filter()) then
local rollover
if id == "idMissionSponsor" then
rollover = GetSponsorEntryRollover(v)
if rollover and rollover.descr and rollover.descr.flavor~="" then
rollover.descr = table.concat({rollover.descr, rollover.descr.flavor},"\n")
end
else
rollover = GetEntryRollover(v)
end
local enabled = true
if IsKindOf(v, "PropertyObject") and v:HasMember("IsEnabled") then
enabled = v:IsEnabled()
end
items[#items + 1] = {
value = v.id,
text = T{11438, "<new_in(new_in)>", new_in = v.new_in} .. v.display_name,
rollover = rollover,
image = id == "idMissionLogo" and v.image,
item_type = id,
enabled = enabled,
}
end
end
return items
end
function GetMissionParamUICategories()
local keys = GetSortedMissionParamsKeys()
local items = {}
for _, category in ipairs(keys) do
local value = MissionParams[category]
items[#items + 1] = {
id = category,
name = value.display_name,
title = value.display_name_caps,
descr = value.descr,
gamepad_hint = value.gamepad_hint,
editor = "dropdown",
submenu = true,
items = function()
return MissionParamCombo(category)
end,
}
end
return items
end
function GetMissionParamRollover(item, value)
local id = item.id
if id == "idMissionSponsor" or id == "idCommanderProfile" then
local entry = table.find_value(MissionParams[id].items, "id", value)
local descr = item.descr
local effect = entry and entry.effect or ""
if effect ~= "" then
if id == "idMissionSponsor" then
descr = descr .. "<newline><newline>" .. GetSponsorDescr(entry, false, "include rockets")
else
descr = descr .. "<newline><newline>" .. T{ effect, entry }
end
end
return {
title = item.title,
descr = descr,
gamepad_hint = item.gamepad_hint,
}
end
if id == "idGameRules" then
local descr = item.descr
local names = GetGameRulesNames()
if names and names ~= "" then
descr = table.concat({descr, names}, "\n\n")
end
return {
title = item.title,
descr = descr,
gamepad_hint = item.gamepad_hint,
}
end
return item
end
DefineClass.PGMissionObject = {
__parents = { "PropertyObject" },
params = false,
}
function PGMissionObject:GetEffects()
return GetDescrEffects()
end
function PGMissionObject:GetProperty(prop_id)
if self.params[prop_id] then
return self.params[prop_id]
end
return PropertyObject.GetProperty(self, prop_id)
end
function PGMissionObject:SetProperty(prop_id, prop_val)
self.params[prop_id] = prop_val
end
function PGMissionObject:GetDifficultyBonus()
if g_TitleObj then
return g_TitleObj:GetDifficultyBonus()
end
return ""
end
function PGMissionObjectCreateAndLoad(obj)
local obj = PGMissionObject:new(obj)
obj.params = {}
for k, v in pairs(g_CurrentMissionParams) do
obj.params[k] = v
end
return obj
end
function GetCargoSumTitle(name)
return T{4065, "<style LandingPosName><name></style><newline>", name = name}
end
------ RocketRenameObject
DefineClass.RocketRenameObject = {
__parents = {"PropertyObject"},
pregame = false,
rocket_name = false,
rocket_name_base = false,
rolover_image = "UI/Common/pm_rename_rollover.tga",
normal_image = "UI/Common/pm_rename.tga",
rename_image = "UI/Common/pm_rename.tga",
}
function RocketRenameObject:InitRocketName(pregame)
self.pregame = pregame
if self.pregame then
if not g_CurrentMapParams.rocket_name then
g_CurrentMapParams.rocket_name, g_CurrentMapParams.rocket_name_base = GenerateRocketName(true)
end
self.rocket_name = g_CurrentMapParams.rocket_name
self.rocket_name_base = g_CurrentMapParams.rocket_name_base
else
local rockets = UICity.labels.SupplyRocket or empty_table
local has_rocket = false
for _, rocket in ipairs(rockets) do
if rocket:IsAvailable() and rocket.name~="" then
self.rocket_name = rocket.name
break
end
end
if not self.rocket_name then
self.rocket_name, self.rocket_name_base = GenerateRocketName(true)
end
end
end
function RocketRenameObject:GetRocketName()
--if UICity and UICity.launch_elevator_mode then
if UICity and UICity.launch_mode == "elevator" then
return BuildingTemplates.SpaceElevator.display_name
end
return self.rocket_name
end
function RocketRenameObject:SetRocketName(rocket_name)
self.rocket_name = rocket_name
if self.pregame then
g_CurrentMapParams.rocket_name = self.rocket_name
end
end
function RocketRenameObject:RenameRocket(host, func)
CreateMarsRenameControl(host, T(4069, "Rename"), self:GetRocketName(),
function(name)
local prev = self:GetRocketName()
self:SetRocketName(name)
if func then func() end
if prev~=name then
self.rocket_name_base = false
end
end,
nil, self, {max_len = 23, console_show = Platform.steam and GetUIStyleGamepad()})
end
function RocketRenameObject:GetRocketHyperlink()
if UICity and UICity.launch_mode == "elevator" then
return BuildingTemplates.SpaceElevator.display_name
end
local base = T{6898, "<h RenameRocket Rename>< image <img> 2000 > ", img = Untranslated(self.rename_image)}
return T{11250, "<base><name><end_link>", base = base, name = Untranslated(self.rocket_name), end_link = T(4162, "</h>")}
end
function InitRocketRenameObject(pregame, new_instance)
if not g_RenameRocketObj or new_instance then
g_RenameRocketObj = RocketRenameObject:new()
g_RenameRocketObj:InitRocketName(pregame)
end
return g_RenameRocketObj
end
function ResupplyDialogOpen(host, ...)
local rockets = UICity and UICity.labels.AllRockets or ""
local owned, available = 0, 0
local total = #rockets
for i = 1, total do
local supply_pod = rockets[i]:IsKindOf("SupplyPod")
if rockets[i].owned then
if not supply_pod then
owned = owned + 1
end
if rockets[i]:IsAvailable() and not supply_pod then
available = available + 1
end
end
end
g_UIAvailableRockets = available
g_UITotalRockets = owned
if g_ActiveHints["HintResupply"] then
HintDisable("HintResupply")
end
if HintsEnabled or g_Tutorial then
if HintsEnabled then
ContextAwareHintShow("HintResupplyUI", true)
end
local hintdlg = GetOnScreenHintDlg()
if hintdlg then
hintdlg:SetParent(terminal.desktop)
hintdlg:SetHiddenMinimized(true)
end
end
end
function ResupplyDialogClose(host, ...)
g_RenameRocketObj = false
ResetCargo()
g_UIAvailableRockets = 0
g_UITotalRockets = 0
g_UITraitsObject = false
if g_ActiveHints["HintResupplyUI"] then
ContextAwareHintShow("HintResupplyUI", false)
end
if HintsEnabled or g_Tutorial then
local hintdlg = GetOnScreenHintDlg()
if hintdlg then
hintdlg:SetParent(GetInGameInterface())
hintdlg:SetHiddenMinimized(false)
end
end
end
function BuyRocket(host)
CreateRealTimeThread(function()
local price = g_Consts.RocketPrice
if UICity and (UICity:GetFunding() - g_CargoCost) >= price then
if WaitMarsQuestion(host, T(6880, "Warning"), T{6881, "Are you sure you want to buy a new Rocket for <funding(price)>?", price = price}, T(1138, "Yes"), T(1139, "No"), "UI/Messages/rocket.tga") == "ok" then
g_UIAvailableRockets = g_UIAvailableRockets + 1
g_UITotalRockets = g_UITotalRockets + 1
UICity:ChangeFunding(-price, "Rocket")
local rocket = PlaceBuilding(GetRocketClass(), {city = UICity})
UICity:AddToLabel("SupplyRocket", rocket) -- add manually to avoid reliance on running game time
rocket:SetCommand("OnEarth")
local obj = host.context
ObjModified(obj)
end
else
CreateMarsMessageBox(T(6902, "Warning"), T{7546, "Insufficient funding! You need <funding(price)> to purchase a Rocket!", price = price}, T(1000136, "OK"), host)
end
end)
end
function SetupLaunchLabel(mode)
local label = "SupplyRocket"
if mode == "pod" then
label = "SupplyPod"
end
return label
end
function LaunchCargoRocket(obj, func_on_launch)
--local elevator = UICity and UICity.launch_elevator_mode
--local elevator = UICity and UICity.launch_mode == "elevator"
local mode = UICity and UICity.launch_mode or "rocket"
local label = SetupLaunchLabel(mode)
Msg("ResupplyRocketLaunched", label, g_CargoCost)
CreateRealTimeThread(function(cargo, cost, obj, mode, label)
if mode == "elevator" then
assert(UICity.labels.SpaceElevator and #UICity.labels.SpaceElevator > 0)
UICity.labels.SpaceElevator[1]:OrderResupply(cargo, cost)
else
cargo.rocket_name = g_RenameRocketObj.rocket_name
MarkNameAsUsed("Rocket", g_RenameRocketObj.rocket_name_base)
UICity:OrderLanding(cargo, cost, false, label)
end
if func_on_launch then
func_on_launch()
end
end, g_RocketCargo, g_CargoCost, obj, mode, label)
if HintsEnabled then
HintDisable("HintResupplyUI")
end
end
------ PayloadObject
DefineClass.RocketPayloadObject = {
__parents = { "PropertyObject" },
properties = {
{ id = "idPrefabs", category = "Payload", name = T(1109, "Prefab Buildings"), editor = "payload", default = 0, submenu = true, }
},
}
function RocketPayload_GetMeta(id)
assert(#(ResupplyItemDefinitions or "") > 0)
assert(type(id) == "string")
return table.find_value(ResupplyItemDefinitions, "id", id)
end
function RocketPayload_GetCargo(id)
return table.find_value(g_RocketCargo, "class", id)
end
function RocketPayload_GetAmount(id)
local cargo = RocketPayload_GetCargo(id)
return cargo and cargo.amount or 0
end
function RocketPayloadObject:GetProperties()
local props = table.icopy(self.properties)
table.iappend(props, ResupplyItemDefinitions)
return props
end
function RocketPayloadObject:IsLocked(item_id)
local def = RocketPayload_GetMeta(item_id)
return def and def.locked
end
GlobalVar("g_ImportLocks", {})
--[[@@@
Locks an item from the list of available imports. Once locked an item will no longer be visible in the resupply interface until unlocked.
@function void Gameplay@LockImport(string item, string lock_id)
@param string item - The name of the item to be locked.
@param string lock_id - Lock id of the lock. For an item to be unlocked all unique locks must be removed.
@result void
]]
function LockImport(item, lock_id)
local locks = g_ImportLocks[item] or {}
g_ImportLocks[item] = locks
locks[lock_id] = true
end
--[[@@@
Removes a lock or all locks from an import item. Unlocked item will appear normally in the resupply interface.
@function void Gameplay@UnlockImport(string item[, string lock_id])
@param string crop_name - The name of the item to be unlocked.
@param string lock_id - Optional. Lock id of the lock. For an item to be unlocked all unique locks must be removed. If omitted all locks for the given item will be removed.
@result void
]]
function UnlockImport(item, lock_id)
if not lock_id then
g_ImportLocks[item or false] = nil
else
local locks = g_ImportLocks[item or false]
if locks then
locks[lock_id] = nil
if next(locks) == nil then
g_ImportLocks[item or false] = nil
end
end
end
end
function RocketPayloadObject:IsBlacklisted(prop_meta)
if prop_meta.id == "OrbitalProbe" and GameState.gameplay then
local _, fully_scanned = UnexploredSectorsExist()
return fully_scanned
end
if prop_meta.id == "Food" and IsGameRuleActive("Hunger") then
return true
end
if g_ImportLocks[prop_meta.id] and next(g_ImportLocks[prop_meta.id]) ~= nil then
return true
end
--local blacklist_classes = UICity and UICity.launch_elevator_mode and {"Vehicle"}
local blacklist_classes = UICity and UICity.launch_mode == "elevator" and {"Vehicle"}
return blacklist_classes and IsKindOfClasses(g_Classes[prop_meta.id], blacklist_classes)
end
function RocketPayload_CalcCargoWeightCost()
g_CargoCost = 0
g_CargoWeight = 0
for k, item in ipairs(ResupplyItemDefinitions) do
g_CargoCost = g_CargoCost + RocketPayload_GetTotalItemPrice(item)
g_CargoWeight = g_CargoWeight + RocketPayload_GetTotalItemWeight(item)
end
end
function RocketPayloadObject:AddItem(item_id)
local item = RocketPayload_GetMeta(item_id)
if self:CanLoad(item) then
local cargo = RocketPayload_GetCargo(item_id)
if cargo then
cargo.amount = cargo.amount + item.pack
ObjModified(self)
end
end
end
function RocketPayloadObject:RemoveItem(item_id)
local item = RocketPayload_GetMeta(item_id)
if self:CanUnload(item) then
local cargo = RocketPayload_GetCargo(item_id)
if cargo then
cargo.amount = Max(0, cargo.amount - item.pack)
ObjModified(self)
end
end
end
function LaunchModeCargoExceeded(item)
end
function RocketPayloadObject:CanLoad(item)
if LaunchModeCargoExceeded(item) then
return false
end
local cargo = item and RocketPayload_GetCargo(item.id)
local loaded_amount = cargo and cargo.amount or 0
return item and loaded_amount < item.max and self:GetFunding() >= RocketPayload_GetItemPrice(item) and self:GetCapacity() >= RocketPayload_GetItemWeight(item)
end
function RocketPayloadObject:CanUnload(item)
return item and RocketPayload_GetAmount(item.id) - item.pack >= 0
end
function RocketPayloadObject:GetCapacity()
assert(g_RocketCargo)
local cargo = UICity and UICity:GetCargoCapacity() or GetMissionSponsor().cargo
return cargo - g_CargoWeight
end
function RocketPayloadObject:GetFunding()
assert(g_RocketCargo)
local funding = UICity and UICity:GetFunding() or GetSponsorModifiedFunding()*1000000
return funding - g_CargoCost
end
function RocketPayloadObject:GetAvailableRockets()
return g_UIAvailableRockets
end
function RocketPayloadObject:GetTotalRockets()
return g_UITotalRockets
end
function RocketPayloadObject:GetRocketName()
local name = g_RenameRocketObj:GetRocketHyperlink()
return GetCargoSumTitle(name)
end
function RocketPayloadObject:RenameRocket(host)
g_RenameRocketObj:RenameRocket(host, function() ObjModified(self) end)
end
function RocketPayloadObject:PassengerRocketDisabledRolloverTitle()
if IsGameRuleActive("TheLastArk") then
return T(972855831022, "The Last Ark")
elseif not AreNewColonistsAccepted() then
return T(10446, "Colonization Temporarily Suspended")
else
return T(1116, "Passenger Rocket")
end
end
function RocketPayloadObject:PassengerRocketDisabledRolloverText()
if IsGameRuleActive("TheLastArk") then
return T(10447, "Can call a Passenger Rocket only once.")
elseif not AreNewColonistsAccepted() then
return T{8537, "<SponsorDisplayName> has to make sure the Colony is sustainable before allowing more Colonists to come to Mars. Make sure the Founders are supplied with Water, Oxygen, and Food for 10 Sols after they arrive on Mars.", SponsorDisplayName = GetMissionSponsor().display_name or ""}
else
return T(8538, "Rockets unavailable.")
end
end
function RocketPayloadObject:GetPrefabsTitle()
local name = T(4068, "PREFABS")
return GetCargoSumTitle(name)
end
function RocketPayloadObject:GetRocketTypeTitle()
local name = T(4067, "SELECT ROCKET")
return GetCargoSumTitle(name)
end
function RocketPayloadObject:SetProperty(id, value)
local cargo = RocketPayload_GetCargo(id)
if cargo then
cargo.amount = value
return
end
return PropertyObject.SetProperty(self, id, value)
end
function RocketPayloadObject:GetProperty(id)
local cargo = RocketPayload_GetCargo(id)
if cargo then
return cargo.amount
end
return PropertyObject.GetProperty(self, id)
end
function RocketPayloadObject:GetAmount(item)
local amount = 0
if not item then
amount = RocketPayload_GetPrefabsCount()
else
amount = RocketPayload_GetAmount(item.id)
end
return amount
end
function RocketPayloadObject:GetDifficultyBonus()
if g_TitleObj then
return g_TitleObj:GetDifficultyBonus()
end
return ""
end
function RocketPayload_GetPrefabsCount()
local prefab_count = 0
for k, item in ipairs(ResupplyItemDefinitions) do
if not item.locked and BuildingTemplates[item.id] then
prefab_count = prefab_count + RocketPayload_GetAmount(item.id)
end
end
return prefab_count
end
function RocketPayloadObject:GetPrice(item)
local money
if not item then
money = RocketPayload_GetPrefabsPrice()
else
money = RocketPayload_GetTotalItemPrice(item)
end
return T{4075, "<funding(money)>", money = money}
end
function RocketPayloadObject:GetNumAvailablePods(label)
local n = 0
for _, pod in ipairs(UICity.labels[label] or empty_table) do
if pod:IsAvailable() then
n = n + 1
end
end
return n
end
function RocketPayloadObject:GetAvailableSupplyPods()
return self:GetNumAvailablePods("SupplyPod")
end
function RocketPayloadObject:GetTotalSupplyPods()
return table.count(UICity.labels.SupplyPod or {})
end
function RocketPayloadObject:GetAvailablePassengerPods()
return self:GetNumAvailablePods("PassengerPod")
end
function RefundPods(label)
local list = UICity.labels[label] or empty_table
for i = #list, 1, -1 do
if list[i].refund > 0 then
DoneObject(list[i])
end
end
end
function RefundPassenger()
end
function RefundSupply()
RefundPods("SupplyPod")
end
function RocketPayload_GetTotalItemPrice(item)
return (RocketPayload_GetAmount(item.id) / item.pack) * RocketPayload_GetItemPrice(item)
end
function RocketPayload_GetItemPrice(item)
local price = item.price
--if UICity and UICity.launch_elevator_mode and #(UICity.labels.SpaceElevator or empty_table) > 0 then
if UICity and UICity.launch_mode == "elevator" and #(UICity.labels.SpaceElevator or empty_table) > 0 then
local price_mod = UICity.labels.SpaceElevator[1].price_mod
price = MulDivRound(item.price, price_mod, 100)
end
local sponsor = GetMissionSponsor()
if sponsor.WeightCostModifierGroup == item.group then
price = MulDivRound(price, sponsor.CostModifierPercent, 100)
end
return price
end
function RocketPayload_GetTotalItemWeight(item)
return (RocketPayload_GetAmount(item.id) / item.pack) * RocketPayload_GetItemWeight(item)
end
function RocketPayload_GetItemWeight(item)
local weight = item.kg
local sponsor = GetMissionSponsor()
if sponsor.WeightCostModifierGroup == item.group then
weight = MulDivRound(weight, sponsor.WeightModifierPercent, 100)
end
return weight
end
function RocketPayload_GetPrefabsPrice()
local money = 0
for k, item in ipairs(ResupplyItemDefinitions) do
if BuildingTemplates[item.id] then
money = money + RocketPayload_GetTotalItemPrice(item)
end
end
return money
end
function RocketPayloadObject:GetRollover(id)
if id == "idPrefabs" then
return {
title = T(1110, "Prefab Buildings"),
descr = T(1111, "Prefabricated parts needed for the construction of certain buildings on Mars."),
hint = T(1112, "<left_click> Browse Prefab Buildings"),
gamepad_hint = T(1113, "<ButtonA> Browse Prefab Buildings"),
}
end
local item = RocketPayload_GetMeta(id)
if not item then
assert(false, "No such cargo item!")
return
end
local display_name, description = item.name, item.description
if not display_name or display_name == "" then
display_name, description = ResolveDisplayName(id)
end
description = (description and description ~= "" and description .. "<newline><newline>") or ""
local icon = item.icon and Untranslated("<image "..item.icon.." 2000><newline><newline>") or ""
description = icon..description .. T{1114, "Weight: <value> kg<newline>Cost: <funding(cost)>", value = RocketPayload_GetItemWeight(item), cost = RocketPayload_GetItemPrice(item)}
return {
title = display_name,
descr = description,
gamepad_hint = T(7580, "<DPadLeft> Change value <DPadRight>"),
}
end
function RocketPayloadObject:GetPodItemText()
local pod_class = GetMissionSponsor().pod_class
local template = pod_class and BuildingTemplates[pod_class]
local name = template and template.display_name or T(824938247285, "Supply Pod")
if self:GetNumAvailablePods("SupplyPod") > 0 then
return T(11439, "<new_in('gagarin')>") .. name
end
return T(11439, "<new_in('gagarin')>") .. T{10860, "<name> ($<cost> M)", name = name, cost = GetMissionSponsor().pod_price / (1000*1000)}
end
function RocketPayloadObjectCreateAndLoad(pregame)
InitRocketRenameObject(pregame, true)
if pregame then
RocketPayload_Init()
else
g_RocketCargo = false
g_CargoMode = false
end
if not g_RocketCargo then
g_RocketCargo = GetMissionInitialLoadout(pregame)
RocketPayload_CalcCargoWeightCost()
end
return RocketPayloadObject:new()
end
function ClearRocketCargo()
g_RocketCargo = GetMissionInitialLoadout()
RocketPayload_CalcCargoWeightCost()
end |
tutorialsIndex_en = {"I. How to play Greed?", "II. Kilika", "III. Mi'hen", "IV. Merchants"}
tutorialsInfo_en = {
{
{name = "01. Introduction", text = "Greed Online is an online MMORPG based on Tibia version 8.6. It is built with The Forgotten Server 1.5, a virtual server capable of emulating the game and keeping it open online for players from all over the world, and OTClient 2.0b (mehah), capable of integrating automatic bot, animations, graphics, etc. directly from the client.", img = "imgs/basic/b1"},
{name = "02. Experience", text = "Your goal in the game is to level up by accumulating experience so that your character is stronger and stronger. Experience is gained by attacking and killing creatures you can find while exploring the continent.\n\nThere are two main cities that you will need to explore: Kilika and Mi'hen. On your journey through these cities you will encounter difficult challenges that will lead you to incredible rewards.", img = "imgs/basic/b2"},
{name = "03. Control Types", text = "We recommend having the 'Classic Control' box activated in the options/control panel. If this box is not checked, you must include the 'Ctrl' key in your actions. Holding down the 'Ctrl' key and right-clicking on a creature or object will open its context menu.\n\nWith 'Classic Control' actions such as attacking, opening creature bodies, using sewers, opening your backpack, etc., are carried out performed automatically without opening the context menu when you right-click with the cursor on your target.\n\nIt is advisable to maximize your 'Hotkey delay' so that typing on your keyboard is faster.", img = "imgs/basic/b3"},
{name = "04. Movement", text = "To walk use the arrow keys on your keyboard. Another option is to lock your number pad (to the right of the keyboard) so you can use the numbers to move around. The numbers 1, 3, 7 and 9 will move your character diagonally.", img = "imgs/basic/b4"},
{name = "05. Combat", text = "The 'Health Information' menu shows the amount of health and mana of your character. Your character passively regenerates health and mana. You can regenerate life with healing magic and healing potions. You can also regenerate mana with mana potions.\n\nAlso the 'Capacity' indicates how much weight (o.z) the character can carry. The 'Soul' indicates the limit of runes that the character can make and is recharged by killing creatures or training.\n\nThe 'Combat Controls' panel shows the fighting modes of your character, you can choose between 'aggressive', 'balanced ' and 'defensive'.\n\nThe 'Battle' panel allows you to select a target and attack it by pressing the left click. You can also open the context menu of the target by pressing 'Ctrl' and right clicking.", img = "imgs/basic/b5"},
{name = "06. Skills", text = "The 'skills' panel displays all of your character's stats. The 'experience' bar will fill up as you kill creatures. If you reach the maximum your character will level up. 'Stamina' is the maximum amount of time you can hunt without rest.\n\nYour 'skills' are divided into 'magic level', 'fist fighting', 'maul fighting', 'sword fighting', ' ranged combat', 'shield' and 'fishing'. To increase the level of your skills you must use magic, attack creatures, take or block physical damage, train in the temple portal, or use a fishing rod.", img = "imgs/basic/b6"},
{name = "07. Inventory", text = "Your character's inventory contains the items that your character can carry until your 'capacity' is exhausted. It consists of 10 main slots.\n\nThe 'armor', 'legs', 'boots', 'ring', 'amulet', and 'shield' slots allow you to equip defensive items to your character.\n\nThe 'weapon' slot allows you to equip a one-handed or two-handed weapon. If your weapon is two-handed, your shield slot must be free. The 'equipment' slot allows you to equip crossbow and bow ammo or light-emitting items, backpacks, ropes, etc.\n\nThe 'container' slot is for equipping a backpack or bag and filling it with items, gold, creature products, equipment, etc.\n\nTo put an item in your backpack, hover over the item, press left click and drag the item into your container. You can open your backpack with right click if you use 'Tibia Classic Control' or use 'Ctrl' and right click to open the 'context menu' of your backpack.", img = "imgs/basic/b7"},
{name = "08. Outfits", text = "To change your clothes hold down the 'Ctrl' key and click on your character with the right mouse button then select 'Set Outfit'.\n\nIf you want to unlock new outfits you must complete quests, or use 'greed points'. The clothes are only aesthetic and do not grant any type of additional characteristic in the character's attributes.", img = "imgs/basic/b8"},
{name = "09. Hotkeys", text = "'Hotkeys' allow you to quickly assign actions on your keyboard via the 'hotkey panel' or the 'action bar' located at the top of the chat.\n\nThe 'add' button allows you to add a new 'key' to 'hotkey panel'. The 'edit text' slot allows you to assign a text. If you choose to enable 'send automatically' the sending of the text to the chat will be immediate.\n\nYou should know that if you write 'magic words' in the 'edit text' box and activate 'send automatically' these words will be conjured instantly by pressing the 'key' they were assigned to.\n\nYou can also assign 'keys' to the use of 'items' and choose between the following actions: 'use it on your character', 'use it on the target' or ' use with crosshair'.", img = "imgs/basic/b9"},
},
{
{name = "01. Kilika Temple", text = "The 'temple' is the place where you first appear in the game. This area is protected and no character or creature can emit or receive attacks. If your character dies, he will reappear in the temple but will lose a percentage of experience, and the items you have in your inventory.\n\nTo prevent the loss of items you can use a necklace called 'amulet of loss'. You can also prevent experience loss if your character gets 'blessings'.", img = "imgs/inter/a1"},
{name = "02. Kilika Deposit", text = "To get to the deposit you must walk west from Kilika's temple.\n\nThe 'deposit' is where the characters store their items. Each player has their own 'deposit' and no other character can access it. This area contains a bank NPC where you can deposit or withdraw your money. You can also find several merchant NPCs to whom you can sell valuable items or buy important supplies.", img = "imgs/inter/a2"},
{name = "03. Kilika Port", text = "To get to the port you must walk northwest from Kilika's deposit.\n\nAt Kilika's 'port' you can travel for 20 gold coin to the city of Mi'hen. Be careful when traveling using ships as they are not protected areas.", img = "imgs/inter/a3"},
},
{
{name = "01. Mi'hen Temple", text = "The 'temple' is the place where you first appear in the game. This area is protected and no character or creature can emit or receive attacks. If your character dies, he will reappear in the temple but will lose a percentage of experience, and the items you have in your inventory.\n\nTo prevent the loss of items you can use a necklace called 'amulet of loss'. You can also prevent experience loss if your character gets 'blessings'.", img = "imgs/advanced/c1"},
{name = "02. Mi'hen Deposit", text = "To get to the deposit you must walk south from the Mi'hen temple.\n\nThe 'deposit' is where the characters store their items. Each player has their own 'deposit' and no other character can access it. This area contains a bank NPC where you can deposit or withdraw your money. You can also find several merchant NPCs to whom you can sell valuable items or buy important supplies.", img = "imgs/advanced/c2"},
{name = "03. Mi'hen Port", text = "To get to the port you have to walk southeast from the Mi'hen deposit.\n\nAt the Mi'hen 'port' you can travel for 20 gold coin to the town of Kilika. Be careful when traveling using ships as they are not protected areas.", img = "imgs/advanced/c3"},
},
{
{name = "01. Promotions", text = "Father Zuke and Isaaru are NPCs capable of changing your 'hometown' and creating 'marks' on your map. In addition, your character can buy a 'promotion' to improve your vocation for 20,000 gold coins.\n\nThat is, if your character is 'knight' it will become 'elite knight', 'paladin' to 'royal paladin', ' sorcerer' to 'master sorcerer', and druid to 'elite druid'. This will increase your character's health and mana per second regeneration values and unlock new spells.", img = "imgs/profesion/p1"},
{name = "02. Blessings", text = "Jassu and Nimrook are NPCs that sell 'blessings'. The value of blessings is calculated by a formula based on your character's level.\n\nAcquiring 'blessings' prevents your character from losing experience or inventory items upon death. Upon death, your blessings will disappear and you will need to repurchase them if you wish to regain this protection.\n\nJassu and Nimrook also sell the 'amulet of loss' item that prevents item loss when equipped for 10,000 gold if you use the 'trade' command.", img = "imgs/profesion/p2"},
{name = "03. PVP Blessings", text = "Amanda and Alia sell the special blessing called 'twist of fate' or 'turn of fate'. This boon does not prevent you from losing your gear or reduce experience lost on death, however it does protect your normal boons if you die in PvP combat.", img = "imgs/profesion/p3"},
{name = "04. Magic Objects", text = "It is essential for all vocations to use potions and magic items to go hunting. You can find Jyscal in Kilika and Mi'hen's deposit. You also have the option to offer a lottery ticket for your empty vials.", img = "imgs/profesion/p4"},
{name = "05. Tools", text = "Equipment is paramount when exploring. In the NPC Keyakku you will find available tools such as shovels, ropes, backpacks, etc. In addition, it allows you to trade rings and amulets.", img = "imgs/profesion/p5"},
{name = "06. Weapons and Munitions", text = "Rin is the classic weapons NPC that allows you to buy weapons for low levels, ranged weapons such as crossbows, bows, etc. and ammunition. You can also get money quickly by selling the weapons you don't use.", img = "imgs/profesion/p6"},
{name = "07. Armors and Shields", text = "O'aka is the classic armor NPC that allows you to buy low level armor and shields to make your character stronger. You can also get money quickly by selling shields and armor that you don't use.", img = "imgs/profesion/p7"},
{name = "08. Bank", text = "In the bank your character can deposit, withdraw or transfer money so as not to load it in coins. In addition, there is the option of selling valuable objects such as gems, sapphires, rubies, pearls, among others.", img = "imgs/profesion/p8"},
{name = "09. Products", text = "Brother is the owner of the creature products shop, this shop is important to get money quickly, since most of the products that you will gather by killing creatures can be sold here.", img = "imgs/profesion/p9"},
{name = "10. Blacksmithing", text = "Blacksmithing is an ancient art that only Nhadala can perform to perfection. Certain metals, or tools, necessary to progress through Greed's quests can be crafted from this NPC.", img = "imgs/profesion/p10"},
{name = "11. Outfits", text = "Your character's clothing can be unlocked at Maroda, this NPC will offer you the option to unlock the first or second decoration of your clothing in exchange for specific items.", img = "imgs/profesion/p11"},
{name = "12. Premium Points", text = "Seymour is able to exchange your premium points for greed currency. The greed currency is the currency that physically represents your donation points, the NPC allows you to change one, ten, or a hundred coins at a time.", img = "imgs/profesion/p12"},
},
} |
--[[
Pixel Vision 8 - Display Example
Copyright (C) 2017, Pixel Vision 8 (http://pixelvision8.com)
Created by Jesse Freeman (@jessefreeman)
Learn more about making Pixel Vision 8 games at
https://www.pixelvision8.com/getting-started
]]--
-- Create a canvas to visualize the screen sizes
local canvas = NewCanvas(256, 240)
function Init()
-- Get the full size of the display
local sizeA = Display(false)
-- Get the visible size of the display
local sizeB = Display()
-- Draw the two sizes to the display
DrawText("Full Display Size " .. sizeA.x .. "x" ..sizeB.y, 1, 1, DrawMode.Tile, "large", 15)
DrawText("Visible Display Size " .. sizeB.x .. "x" ..sizeB.y, 1, 2, DrawMode.Tile, "large", 15)
-- Set the canvas stroke to white
canvas:SetStroke({15}, 1, 1)
-- Set the fill color to 5 and draw the full size square
canvas:SetPattern({5}, 1, 1)
canvas:DrawSquare(8, 32, sizeA.x / 2 + 8, sizeA.y / 2 + 32, true)
-- Set the fill color to 0 and draw the visible size square
canvas:SetPattern({0}, 1, 1)
canvas:DrawSquare(8, 32, sizeB.x / 2 + 8, sizeB.y / 2 + 32, true)
end
function Draw()
-- Redraw the display
RedrawDisplay()
-- Draw the canvas to the display
canvas:DrawPixels()
end
|
local helpers = require('test.functional.helpers')(after_each)
local clear, meths, funcs, eq =
helpers.clear, helpers.meths, helpers.funcs, helpers.eq
describe('history support code', function()
before_each(clear)
it('correctly clears start of the history', function()
-- Regression test: check absense of the memory leak when clearing start of
-- the history using ex_getln.c/clr_history().
eq(1, funcs.histadd(':', 'foo'))
eq(1, funcs.histdel(':'))
eq('', funcs.histget(':', -1))
end)
it('correctly clears end of the history', function()
-- Regression test: check absense of the memory leak when clearing end of
-- the history using ex_getln.c/clr_history().
meths.set_option('history', 1)
eq(1, funcs.histadd(':', 'foo'))
eq(1, funcs.histdel(':'))
eq('', funcs.histget(':', -1))
end)
it('correctly removes item from history', function()
-- Regression test: check that ex_getln.c/del_history_idx() correctly clears
-- history index after removing history entry. If it does not then deleting
-- history will result in a double free.
eq(1, funcs.histadd(':', 'foo'))
eq(1, funcs.histadd(':', 'bar'))
eq(1, funcs.histadd(':', 'baz'))
eq(1, funcs.histdel(':', -2))
eq(1, funcs.histdel(':'))
eq('', funcs.histget(':', -1))
end)
end)
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
CW_TURKISH = Clockwork.lang:GetTable("Turkish");
CW_TURKISH["Acrobatics"] = "Akrobasi";
CW_TURKISH["Dexterity"] = "Hüner";
CW_TURKISH["Endurance"] = "Dayanıklılık";
CW_TURKISH["Medical"] = "Tıbbi";
CW_TURKISH["Strength"] = "Güç";
CW_TURKISH["Agility"] = "Çeviklik";
CW_TURKISH["Objectives"] = "Hedefler";
CW_TURKISH["Breach"] = "İhlal";
CW_TURKISH["BreachTargetID"] = "Doğrudan şarj edilebilir.";
CW_TURKISH["Radio"] = "Radyo";
CW_TURKISH["RadioTargetID"] = "Bu radyonun frekansı yok.";
CW_TURKISH["InfoCitizenID"] = "Sivil ID: #1";
CW_TURKISH["CannotDropWhileCarrying"] = "İçinde eşya taşırken bunu düşüremezsiniz!";
CW_TURKISH["PermaKillModeDisabled"] = "Kalıcı-ölüm modu kapatıldı, şimdi güvendesiniz!";
CW_TURKISH["PermaKillModeTurnedOff"] = "#1 Kalıcı-ölüm modunu kapattı, şimdi güvendesin!";
CW_TURKISH["PermaKillModeEnabled"] = "#1 adlı kişi #2 dakikalığına kalıcı-ölümü aktifleştirdi, ölmemeye çalış.";
CW_TURKISH["InvalidAmountOfMinutes"] = "Bu geçersiz bir dakikadır!";
CW_TURKISH["RemovedFromServerWhitelist"] = "#1 adlı kişi #2 kişisini '#3' sunucu beyaz listesinden sildi!";
CW_TURKISH["AddedToServerWhitelist"] = "#1 adlı kişi #2 kişisini '#3' sunucu beyaz listesine ekledi!";
CW_TURKISH["AlreadyOnServerWhitelist"] = "#1 zaten '#2' sunucu beyaz listesinde!";
CW_TURKISH["NotOnServerWhitelist"] = "#1 şuan '#2' sunucu beyaz listesinde değil!";
CW_TURKISH["PlayerTookCustomClass"] = "#1 adlı kişi #2 kişisinin özel sınıfını sildi.";
CW_TURKISH["PlayerSetCustomClass"] = "#1 adlı kişi #2 kişisinin özel sınıfını '#3' yaptı.";
CW_TURKISH["PlayerPermaKilledOther"] = "#1 adlı kişi '#2' karakterini kalıcı-öldürdü!";
CW_TURKISH["PlayerAlreadyPermaKilled"] = "Bu karakter zaten kalıcı-öldürüldü!";
CW_TURKISH["CharacterAlreadyTied"] = "Bu karakter zaten bağlı!";
CW_TURKISH["CharacterTooFarAway"] = "Bu karakter çok uzakta!";
CW_TURKISH["CannotTieThoseFacingYou"] = "Sana bakan karakteri bağlayamazsın!";
CW_TURKISH["AlreadyTyingCharacter"] = "Zaten bir karakteri bağlıyorsun!";
CW_TURKISH["CannotDoThisWhenScanner"] = "Bir tarayıcıyken eşya düşüremezsin!";
CW_TURKISH["CannotDoThisWhenTied"] = "Bağlıyken bunu yapamazsın!";
CW_TURKISH["NotRankedHighEnoughForClass"] = "Bu sınıf için yeterince yüksek rütbeli değilsin!";
CW_TURKISH["RankedTooHighForClass"] = "Bu sınıf için çok yüksek bir rütbedesiniz!";
CW_TURKISH["YouSetRadioFrequencyTo"] = "Bu sabit radyonun argümanını #1 olarak ayarladınız.";
CW_TURKISH["RadioArgumentsMustBeBetween"] = "Radyo frekansı 101.1 ile 199.9 arasında olmalıdır!";
CW_TURKISH["RadioArgumentsMustBeLike"] = "Radyo frekansı XXX.X'e benzemelidir!";
CW_TURKISH["CannotUseAnotherSecondary"] = "Başka bir ikincil silah kullanamazsınız!";
CW_TURKISH["CannotUseAnotherPrimary"] = "Başka bir birincil silah kullanamazsın!";
CW_TURKISH["CannotUseAnotherMelee"] = "Başka bir yakın dövüş silahı kullanamazsın!";
CW_TURKISH["NeedToSetFrequencyFirst"] = "Önce radyo frekansını ayarlamanız gerekir.!";
CW_TURKISH["YouCannotDoThatRightNow"] = "Şu anda bunu yapamazsınız!";
CW_TURKISH["YouDoNotOwnARadio"] = "Bir radyonuz yok!";
CW_TURKISH["YouDoNotOwnAZipTie"] = "Bağlama ipin yok!";
CW_TURKISH["YouAreNotAdministrator"] = "Yönetici değilsin!";
CW_TURKISH["CannotSearchMovingCharacter"] = "Hareketli bir karakteri arayamazsınız!";
CW_TURKISH["CharacterIsNotTied"] = "Şahısı arayabilmeniz için önce o şahısın bağlı olması gerekir.!";
CW_TURKISH["YouCannotOpenRation"] = "Bu erzağı açamazsın!";
CW_TURKISH["NotInCWU"] = "Sivil İşçiler Sendikasında değilsiniz!";
CW_TURKISH["YouSetYourRadioFrequencyTo"] = "Radyo frekansını #1 yaptın.";
CW_TURKISH["CannotHaveCombineLock"] = "Hedef combine kilidine sahip değil!";
CW_TURKISH["AlreadyHasCombineLock"] = "Hedef combine kilidine sahip!";
CW_TURKISH["YouDoNotOwnHealthVial"] = "Sağlık Şişeye sahip değilsin!";
CW_TURKISH["YouDoNotOwnHealthKit"] = "Sağlık Kitine sahip değilsin!";
CW_TURKISH["YouDoNotOwnBandage"] = "Bandaja sahip değilsin!";
CW_TURKISH["NotValidMedicalItem"] = "Bu doğrulanmış bir tıbbi eşya değil!";
CW_TURKISH["CannotSendRequestUntil"] = "#2 saniyeliğine istek gönderemezsin!";
CW_TURKISH["YouDoNotOwnRequestDevice"] = "Herhangi bir istek cihazın yok!";
CW_TURKISH["YouAreCurrentlyTying"] = "Şuanda bir karakteri bağlıyorsun!";
CW_TURKISH["YouAreNotCombine"] = "Bunu yapabilmek için Combine olmalısın!";
CW_TURKISH["CannotViewEditOwnData"] = "Kendi verilerinizi görüntüleyemezsiniz veya düzenleyemezsiniz!";
CW_TURKISH["YouAddedVendingMachine"] = "Bir otomat ekledin.";
CW_TURKISH["YouAddedRationDispenser"] = "Bir erzak dispanseri ekledin.";
CW_TURKISH["CannotBeBreached"] = "Bu eşya ihlal edilemez!";
CW_TURKISH["AlreadyHasBreach"] = "Bu eşya zaten ihlal edildi!";
CW_TURKISH["YouAreFollowing"] = "Şuanda #1 takip ediyorsun.";
CW_TURKISH["NoCharactersNearYou"] = "Yakınınızda karakter yok!";
CW_TURKISH["YouAreNotAScanner"] = "Bunu yapmak için bir Tarayıcı olmanız gerekir!";
CW_TURKISH["StatusBeingTiedUp"] = "Şahısın elleri bağlanıyor.";
CW_TURKISH["StatusBeenTiedUp"] = "Şahısın elleri bağlandı.";
CW_TURKISH["StatusBeingUntied"] = "Şahısın elleri çözülüyor.";
CW_TURKISH["StatusUnconscious"] = "Şahıs bilinçdışı.";
CW_TURKISH["StatusCriticalCondition"] = "Şahıs kritik durumda.";
CW_TURKISH["PressUseToUntie"] = "Şahısın ipini çözmek için :+use: bas.";
CW_TURKISH["OptionPermaKill"] = "Kalıcı-Öldür";
CW_TURKISH["OptionCustomClass"] = "Özel Sınıf";
CW_TURKISH["OptionCustomClassSet"] = "Ayarla";
CW_TURKISH["OptionCustomClassTake"] = "Al";
CW_TURKISH["OptionCustomClassHelp"] = "Özel sınıflarını neye ayarlamak istersiniz?";
CW_TURKISH["OptionServerWhitelist"] = "Sunucu Beyaz Listesi";
CW_TURKISH["OptionServerWhitelistAdd"] = "Ekle";
CW_TURKISH["OptionServerWhitelistAddHelp"] = "Hangi kişiyi beyaz listeye eklemek istersiniz?";
CW_TURKISH["OptionServerWhitelistRemove"] = "Sil";
CW_TURKISH["OptionServerWhitelistRemoveHelp"] = "Hangi kişiyi beyaz listeden kaldırmak istersiniz?";
CW_TURKISH["RebuildCitizenManifest"] = "Vatandaş manifestosu yeniden oluşturuluyor...";
CW_TURKISH["UpdateExternalAttributes"] = "Harici #1 güncelleniyor...";
CW_TURKISH["DownloadLostBiosignal"] = "Kayıp biyosinyal indiriliyor...";
CW_TURKISH["DownloadTraumaPacket"] = "Travma paketi indiriliyor...";
CW_TURKISH["ProtectionTeamBodilyHarm"] = "UYARI! #1 adresindeki koruma ekibi birimi fiziksel travmaya maruz kaldı...";
CW_TURKISH["DownloadRecentObbjectives"] = "Geçmiş hedefler indiriliyor...";
CW_TURKISH["DownloadRequestPacket"] = "İstek paketi indiriliyor...";
CW_TURKISH["ErrorShuttingDown"] = "HATA! Kapatılıyor...";
CW_TURKISH["PhysicalTraumaDetected"] = "UYARI! Fiziksel vücut travması algılandı...";
CW_TURKISH["PhysicalSystemsRestored"] = "Fiziksel vücut sistemleri restore edildi...";
CW_TURKISH["PhysicalSystemsRegenerate"] = "Fiziksel vücut sistemleri yenileniyor...";
CW_TURKISH["ExternalProtectionExhausted"] = "UYARI! Harici koruma tükendi...";
CW_TURKISH["ExternalProtectionDamaged"] = "UYARI! Harici koruma hasar aldı...";
CW_TURKISH["ExternalProtectionRestored"] = "Dış koruma sistemleri restore edildi...";
CW_TURKISH["ExternalProtectionRegenerate"] = "Dış koruma sistemleri yenilendi...";
CW_TURKISH["BiosignalLost"] = "UYARI! #1 adresindeki koruma ekibi biriminin biyosinyali kaybedildi...";
CW_TURKISH["DownloadingLostRadioInfo"] = "Kayıp radyo iletişim bilgileri indiriliyor...";
CW_TURKISH["RadioContactLostForUnit"] = "UYARI! #1 adresindeki birim için radyo bağlantısı kesildi...";
CW_TURKISH["QuizAnswerCollectingItems"] = "Öğeleri ve yükseltmeleri toplama.";
CW_TURKISH["QuizAnswerDevelopingChar"] = "Karakterini geliştirmek.";
CW_TURKISH["QuizAnswerRealLife"] = "Real Life.";
CW_TURKISH["QuizAnswerHalfLife2"] = "Half-Life 2.";
CW_TURKISH["QuizAnswerGoodGrammar"] = "Evet, yapabilirim.";
CW_TURKISH["QuizAnswerBadGrammar"] = "evet yapabilirim";
CW_TURKISH["QuizAnswerYes"] = "Evet.";
CW_TURKISH["QuizAnswerNo"] = "Hayır.";
CW_TURKISH["QuizOption1"] = "Rol oynamanın yavaş tempolu ve rahat olduğunu anlıyor musunuz?";
CW_TURKISH["QuizOption2"] = "Büyük harfleri, noktalama işaretlerini kullanabiliyor musun?";
CW_TURKISH["QuizOption3"] = "Rol oynamak için silaha ihtiyacınız yok, anlıyor musunuz?";
CW_TURKISH["QuizOption4"] = "Rol oynamak için eşyalara ihtiyacınız yok, anlıyor musunuz?";
CW_TURKISH["QuizOption5"] = "Ciddi rol hakkında ne düşünüyorsun?";
CW_TURKISH["QuizOption6"] = "Bu rol hangi evrendeki rol?";
CW_TURKISH["ChatPlayerBroadcast"] = ":color1:#1 yayınlıyor: \"#2\"";
CW_TURKISH["ChatPlayerDispatch"] = ":color1:Mesaj yayınlıyor: \"#1\"";
CW_TURKISH["ChatPlayerRequest"] = ":color1:#1 istiyor: \"#2\"";
CW_TURKISH["YouAlreadyHavePermit"] = "Zaten bu izine sahipsin!";
CW_TURKISH["NotValidPermit"] = "Bu geçerli bir izin değil!";
CW_TURKISH["PermitsNotEnabled"] = "İzin sistemi aktif değil!";
CW_TURKISH["YouAreNotACitizen"] = "Vatandaş değilsin!";
CW_TURKISH["GiveCashVendingMachine"] = "otomat";
CW_TURKISH["CashPermitBuyGeneralGoods"] = "genel mal izni satın alınıyor";
CW_TURKISH["CashPermitBuy"] = "#1 izni satın alınıyor";
CW_TURKISH["CashBusinessPermit"] = "işletme izni satın alınıyor";
CW_TURKISH["CashDestroyGenerator"] = "#1 yok ediliyor";
CW_TURKISH["CashRationPacket"] = "erzak paketi";
CW_TURKISH["HintLife"] = "Hayat";
CW_TURKISH["HintLifeDesc"] = "Karakteriniz sadece insandır, yüksek çıkıntılardan atlamaktan kaçının.";
CW_TURKISH["HintSleep"] = "Uyku";
CW_TURKISH["HintSleepDesc"] = "Uyumayı unutma, karakterin yorulur.";
CW_TURKISH["HintEating"] = "Yemek";
CW_TURKISH["HintEatingDesc"] = "Yemek yemek zorunda değilsin, fakat bu karakterinizin aç olmadığı anlamına gelmez.";
CW_TURKISH["HintFriends"] = "Arkadaşlar";
CW_TURKISH["HintFriendsDesc"] = "Bazı arkadaşlar edinmeye çalışın, sefalet şirketi seviyor.";
CW_TURKISH["HintCurfew"] = "Sokağa Çıkma Yasağı";
CW_TURKISH["HintCurfewDesc"] = "Sokağa Çıkma Yasağı? Canın sıkkın? Bir oda arkadaşı atanmasını isteyin.";
CW_TURKISH["HintPrison"] = "Hapishane";
CW_TURKISH["HintPrisonDesc"] = "Zaman ayırmaya hazır değilseniz, suç işlemeyin.";
CW_TURKISH["HintRebels"] = "İsyancılar";
CW_TURKISH["HintRebelsDesc"] = "Direnişi kovalamayın, Combine sizi bir arada gruplayabilir.";
CW_TURKISH["HintTalking"] = "Konuşmak";
CW_TURKISH["HintTalkingDesc"] = "Combine, konuştuğunuzda hoşlanmaz, fısıldamayı dene.";
CW_TURKISH["HintRations"] = "Erzaklar";
CW_TURKISH["HintRationsDesc"] = "Erzaklar, onlar atıştırmalarla dolu çantalar. Görgülü davran.";
CW_TURKISH["HintCombine"] = "Combine";
CW_TURKISH["HintCombineDesc"] = "Bir combine ile sakın bozuşma, dünyayı 7 saatte alt edebilirler.";
CW_TURKISH["HintJumping"] = "Zıplama";
CW_TURKISH["HintJumpingDesc"] = "Tavşan gibi sıçramak medeniyetsizdir ve Combine size şok çubuğu ile hatırlatır.";
CW_TURKISH["HintPunching"] = "Yumruk";
CW_TURKISH["HintPunchingDesc"] = "Birisine yumruk atmak istediğine dair bir his var mı? Yapma.";
CW_TURKISH["HintCompliance"] = "İtaat";
CW_TURKISH["HintComplianceDesc"] = "Combine'a itaat etmek, yaptığınızda memnun olacaksınız.";
CW_TURKISH["HintCombineRaids"] = "Combine Baskınları";
CW_TURKISH["HintCombineRaidsDesc"] = "Combine kapı çaldığında, kıçını yere koy.";
CW_TURKISH["HintRequestDevice"] = "İstek Cihazı";
CW_TURKISH["HintRequestDeviceDesc"] = "Sivil Korumaya mı ihtiyacınız var? Bir istek cihazına yatırım yapın.";
CW_TURKISH["HintCivilProtection"] = "Sivil Koruma";
CW_TURKISH["HintCivilProtectionDesc"] = "Sivil Koruma, uygar toplumu korur, seni değil.";
CW_TURKISH["HintAdmins"] = "Yetkililer";
CW_TURKISH["HintAdminsDesc"] = "Yöneticiler size yardım etmek için buradalar, lütfen onlara saygı gösterin.";
CW_TURKISH["HintAction"] = "Eylem";
CW_TURKISH["HintActionDesc"] = "Aksiyon. Aramayı bırak, sana gelene kadar bekle.";
CW_TURKISH["HintGrammar"] = "Gramar";
CW_TURKISH["HintGrammarDesc"] = "Doğru konuşmaya çalışın ve ifadeleri kullanmayın.";
CW_TURKISH["HintRunning"] = "Koşma";
CW_TURKISH["HintRunningDesc"] = "Gidecek bir yeriniz var mı? Koşmak ister misin? Yapma, medeniyetsiz.";
CW_TURKISH["HintHealing"] = "İyileştirme";
CW_TURKISH["HintHealingDesc"] = "Envanterinizdeki Ver komutunu kullanarak oyuncuları iyileştirebilirsiniz.";
CW_TURKISH["HintF3Hotkey"] = "F3 Tuşu";
CW_TURKISH["HintF3HotkeyDesc"] = "İpi kullanmak için bir karaktere bakarken F3 tuşuna basın.";
CW_TURKISH["HintF4Hotkey"] = "F4 Tuşu";
CW_TURKISH["HintF4HotkeyDesc"] = "Bağlı karakteri aramak için bağlı bir karaktere bakarken F4 tuşuna basın..";
CW_TURKISH["HintAttributes"] = "Attributes";
CW_TURKISH["HintAttributesDesc"] = "Whoring *(name_attributes)* is a permanant ban, we don't recommend it.";
CW_TURKISH["HintFirefights"] = "Firefights";
CW_TURKISH["HintFirefightsDesc"] = "Bir itfaiyecilikle uğraşırken, eğlenceli hale getirmek için kaçırın.";
CW_TURKISH["HintMetagaming"] = "Metagaming";
CW_TURKISH["HintMetagamingDesc"] = "Metagaming, OOC bilgisini karakter olarak kullanmanızdır.";
CW_TURKISH["HintPassiveRP"] = "Passive RP";
CW_TURKISH["HintPassiveRPDesc"] = "Eğer sıkılıyorsanız ve bir eylem yoksa, biraz pasif rol oynamayı deneyin..";
CW_TURKISH["HintDevelopment"] = "Development";
CW_TURKISH["HintDevelopmentDesc"] = "Karakterini geliştir, onlara anlatacakları bir hikaye ver.";
CW_TURKISH["HintPowergaming"] = "Powergaming";
CW_TURKISH["HintPowergamingDesc"] = "Powergaming, eylemlerinizi başkalarına zorladığınızda gerçekleşir.";
CW_TURKISH["ServerWhitelistIdentity"] = "Sunucu Beyaz Liste Kimliği";
CW_TURKISH["ServerWhitelistIdentityDesc"] = "Sunucu beyaz listesi için kullanılan kimlik.\nKimliği yoksa boş bırakın.";
CW_TURKISH["CombineLockOverrides"] = "Combine Lock Overrides";
CW_TURKISH["CombineLockOverridesDesc"] = "Combine kilidinin varsayılan kapı kilitleriyle yer değiştirmesi.";
CW_TURKISH["SmallIntroText"] = "Küçük Giriş Yazısı";
CW_TURKISH["SmallIntroTextDesc"] = "The small text displayed for the introduction.";
CW_TURKISH["BigIntroText"] = "Büyük Giriş Yazısı";
CW_TURKISH["BigIntroTextDesc"] = "Giriş için gösterilen büyük metin.";
CW_TURKISH["KnockoutTime"] = "Baygınlık Süresi";
CW_TURKISH["KnockoutTimeDesc"] = "Bir oyuncunun baygınlık süresi (saniye).";
CW_TURKISH["BusinessCost"] = "İşletme Üçreti";
CW_TURKISH["BusinessCostDesc"] = "Bir iş kurmanın maliyeti.";
CW_TURKISH["CWUPropsEnabled"] = "CWU Propları Aktif";
CW_TURKISH["CWUPropsEnabledDesc"] = "Sivil İşçiler Propları'nın kullanılıp kullanılmayacağı.";
CW_TURKISH["PermitsEnabled"] = "İzinler Aktif";
CW_TURKISH["PermitsEnabledDesc"] = "İzinlerin etkin olup olmadığı.";
CW_TURKISH["DullVision"] = "Dull Vision";
CW_TURKISH["DullVisionDesc"] = "Oyuncuların görüşündeki olumsuzlukları değiştirir.";
CW_TURKISH["RequestFrequencyTitle"] = "Frekans";
CW_TURKISH["RequestFrequencyHelp"] = "Frekansı kaça ayarlamak istersin?";
CW_TURKISH["RequestObjectDescTitle"] = "Eşya Açıklaması";
CW_TURKISH["RequestObjectDescHelp"] = "Bu eşyanın fiziksel açıklaması nedir?";
CW_TURKISH["Item357MagnumBullets"] = ".357 Magnum Mermileri";
CW_TURKISH["Item357MagnumBulletsDesc"] = "Magnum ile dolu küçük bir kutu.";
CW_TURKISH["ItemPulseRifleEnergy"] = "Tüfek Enerjisi";
CW_TURKISH["ItemPulseRifleEnergyDesc"] = "Mavi parıltılı bir kartuş yayıyor.";
CW_TURKISH["ItemPulseRifleOrb"] = "Tüfek Küresi";
CW_TURKISH["ItemPulseRifleOrbDesc"] = "Turuncu bir parıltı yayan tuhaf bir eşya.";
CW_TURKISH["ItemShotgunShells"] = "Pompalı Kovanı";
CW_TURKISH["ItemShotgunShellsDesc"] = "Kovanlarla dolu bir kırmızı kutu.";
CW_TURKISH["Item9mmPistolBullets"] = "9mm Tabanca Mermileri";
CW_TURKISH["Item9mmPistolBulletsDesc"] = "9mm tabanca mermileri ile dolu küçük bir kutu.";
CW_TURKISH["ItemRPGMissile"] = "RPG Roketi";
CW_TURKISH["ItemRPGMissileDesc"] = "Turuncu ve beyaz renkli bir roket, bunu düşürürsem ne olur?";
CW_TURKISH["ItemSMGBullets"] = "SMG Mermileri";
CW_TURKISH["ItemSMGBulletsDesc"] = "Çok fazla mermi ile dolu ağır bir kap.";
CW_TURKISH["ItemMP7Grenade"] = "MP7 Bombası";
CW_TURKISH["ItemMP7GrenadeDesc"] = "Büyük bir mermi biçimli eşya.";
CW_TURKISH["ItemCrossbowBolts"] = "Yaylı Tüfek Okları";
CW_TURKISH["ItemCrossbowBoltsDesc"] = "Bir demir cıvata seti, kaplaması paslanıyor.";
CW_TURKISH["ItemAntidepressants"] = "Anti Depresan";
CW_TURKISH["ItemAntidepressantsDesc"] = "Direniş tarafından geliştirilen bir kutu hap.";
CW_TURKISH["ItemBackpack"] = "Sırt Çantası";
CW_TURKISH["ItemBackpackDesc"] = "Bir püskü sırt çantası, çok tutacak gibi görünmüyor.";
CW_TURKISH["ItemBandage"] = "Badaj";
CW_TURKISH["ItemBandageDesc"] = "Bir bandaj rulo, akıllıca kullan..";
CW_TURKISH["ItemBeer"] = "Bira";
CW_TURKISH["ItemBeerDesc"] = "Sıvı dolu bir cam şişe, komik bir kokuya sahiptir.";
CW_TURKISH["ItemBleach"] = "Çamaşır Suyu";
CW_TURKISH["ItemBleachDesc"] = "Bir şişe çamaşır suyu, bu tehlikeli bir şey.";
CW_TURKISH["ItemBoxedBackpack"] = "Kutulu Sırt Çantası";
CW_TURKISH["ItemBoxedBackpackDesc"] = "Kahverengi bir kutu, içeriğini ortaya çıkarmak için açın.";
CW_TURKISH["ItemBoxedBag"] = "Kutulu Çanta";
CW_TURKISH["ItemBoxedBagDesc"] = "Kahverengi bir kutu, içeriğini ortaya çıkarmak için açın.";
CW_TURKISH["ItemBreach"] = "İhlal";
CW_TURKISH["ItemBreachDesc"] = "Asma kilit gibi görünen küçük bir cihaz.";
CW_TURKISH["ItemBreensWater"] = "Breen'in Suyu";
CW_TURKISH["ItemBreensWaterDesc"] = "Mavi bir alüminyum kutu, salladığınızda parlar.";
CW_TURKISH["ItemChineseTakeout"] = "Çin Yemeği";
CW_TURKISH["ItemChineseTakeoutDesc"] = "Bir tasfiye karton, soğuk erişte ile dolu.";
CW_TURKISH["ItemCitizenSupplements"] = "Vatandaş Sevkiyatı";
CW_TURKISH["ItemCitizenSupplementsDesc"] = "Kalaylı bir kutu, salladığınızda parlar.";
CW_TURKISH["ItemCombineLock"] = "Combine Kilidi";
CW_TURKISH["ItemCombineLockDesc"] = "Bir kapıyı etkin bir şekilde kilitlemek için kullanılan combine cihazı.";
CW_TURKISH["ItemFlash"] = "Flash";
CW_TURKISH["ItemFlashDesc"] = "Kirli bir toz borusu, bunun bir el bombası olması gerekiyordu?";
CW_TURKISH["ItemSmoke"] = "Duman";
CW_TURKISH["ItemSmokeDesc"] = "Kirli bir toz borusu, bunun bir el bombası olması gerekiyordu?";
CW_TURKISH["ItemFlash"] = "Flash";
CW_TURKISH["ItemFlashDesc"] = "Kirli bir toz borusu, bunun bir el bombası olması gerekiyordu?";
CW_TURKISH["ItemHandheldRadio"] = "Telsiz";
CW_TURKISH["ItemHandheldRadioDesc"] = "Frekans alıcısı olan parlak bir el radyosu.";
CW_TURKISH["ItemHealthKit"] = "Sağlık Kiti";
CW_TURKISH["ItemHealthKitDesc"] = "İlaçla dolu beyaz bir paket.";
CW_TURKISH["ItemHealthVial"] = "Sağlık Şişesi";
CW_TURKISH["ItemHealthVialDesc"] = "Yeşil sıvı ile dolu garip bir şişe, dikkatli olun.";
CW_TURKISH["ItemLargeSoda"] = "Büyük Soda";
CW_TURKISH["ItemLargeSodaDesc"] = "Plastik bir şişe, oldukça büyük ve sıvı ile dolu.";
CW_TURKISH["ItemMedicUniform"] = "Doktor Üniforması";
CW_TURKISH["ItemMedicUniformDesc"] = "Manşonun üzerinde tıbbi bir amblem bulunan tek tip bir direnç.";
CW_TURKISH["ItemMelon"] = "Karpuz";
CW_TURKISH["ItemMelonDesc"] = "Yeşil bir meyve, sert bir dış kabuğa sahiptir.";
CW_TURKISH["ItemMetropoliceSupplements"] = "Metropolis Sevkiyatı";
CW_TURKISH["ItemMetropoliceSupplementsDesc"] = "Kalaylı bir kutu, salladığınızda parlar.";
CW_TURKISH["ItemMilkCarton"] = "Süt Kartonu";
CW_TURKISH["ItemMilkCartonDesc"] = "Lezzetli sütle dolu bir karton.";
CW_TURKISH["ItemMilkJugs"] = "Süt Sürahisi";
CW_TURKISH["ItemMilkJugsDesc"] = "Lezzetli sütle dolu bir sürahi.";
CW_TURKISH["ItemParacetamol"] = "Parasetamol";
CW_TURKISH["ItemParacetamolDesc"] = "Sivil Koruma tarafından üretilen düşük kalibreli parasetamol.";
CW_TURKISH["ItemRation"] = "Konteynır";
CW_TURKISH["ItemRationDesc"] = "Mor bir kap, bu sefer sana ne mallar verdiler?";
CW_TURKISH["ItemRequestDevice"] = "İstek Cihazı";
CW_TURKISH["ItemRequestDeviceDesc"] = "Bir kırmızı düğmeli, radyo benzeri küçük bir cihaz.";
CW_TURKISH["ItemResistanceUniform"] = "Direniş Üniforması";
CW_TURKISH["ItemResistanceUniformDesc"] = "Kolunda sarı bir sembol ile tek tip bir üniforma.";
CW_TURKISH["ItemSmallBag"] = "Küçük Torba";
CW_TURKISH["ItemSmallBagDesc"] = "Küçük püskü bir çanta.";
CW_TURKISH["ItemSmoke"] = "Duman";
CW_TURKISH["ItemSmokeDesc"] = "Kirli bir toz borusu, bunun bir el bombası olması gerekiyordu?";
CW_TURKISH["ItemSmoothBreensWater"] = "Breen'in pürüzsüz suyu";
CW_TURKISH["ItemSmoothBreensWaterDesc"] = "Kırmızı bir alüminyum kutu, salladığınızda parlar.";
CW_TURKISH["ItemSpecialBreensWater"] = "Breen'in Özel Suyu";
CW_TURKISH["ItemSpecialBreensWaterDesc"] = "Sarı bir alüminyum kutu, salladığınızda parlar.";
CW_TURKISH["ItemSprayCan"] = "Sprey Kutusu";
CW_TURKISH["ItemSprayCanDesc"] = "Boya ile dolu basit bir sprey kutusu.";
CW_TURKISH["ItemStationaryRadio"] = "İstasyon Radyosu";
CW_TURKISH["ItemStationaryRadioDesc"] = "Antika bir radyo, bunun hala işe yarayacağını düşünüyor musunuz??";
CW_TURKISH["ItemSteroids"] = "Steroidler";
CW_TURKISH["ItemSteroidsDesc"] = "Sivil Koruma tarafından üretilen düşük kalibreli steroidler.";
CW_TURKISH["ItemSuitcase"] = "Bavul";
CW_TURKISH["ItemSuitcaseDesc"] = "Her zamanki şeyleri, yedek kıyafetleri ve bazı yiyecekleri içerir.";
CW_TURKISH["ItemVegetableOil"] = "Sebze Yağı";
CW_TURKISH["ItemVegetableOilDesc"] = "Bir şişe bitkisel yağ, çok lezzetli değil.";
CW_TURKISH["Item357Magnum"] = ".357 Magnum";
CW_TURKISH["Item357MagnumDesc"] = "Küçük bir tabanca, kaplanmış gümüş paslanıyor.";
CW_TURKISH["ItemPulseRifle"] = "Tüfek";
CW_TURKISH["ItemPulseRifleDesc"] = "Dünya üzerinde hazırlanmış gibi görünmeyen bir silah.";
CW_TURKISH["ItemCrossbow"] = "Yaylı Tüfek";
CW_TURKISH["ItemCrossbowDesc"] = "Çeşitli hurda malzemelerden yapılmış bir silah.";
CW_TURKISH["ItemGrenade"] = "Bomba";
CW_TURKISH["ItemGrenadeDesc"] = "Kirli bir toz borusu, bunun bir el bombası olması gerekiyordu.?";
CW_TURKISH["Item9mmPistol"] = "9mm Tabanca";
CW_TURKISH["Item9mmPistolDesc"] = "Donuk gri renkte kaplanmış küçük bir tabanca.";
CW_TURKISH["ItemPowerNode"] = "Güç Düğümü";
CW_TURKISH["ItemPowerNodeDesc"] = "Küresel şekilli bir nesne, ondan yayılan mavi ışık.";
CW_TURKISH["ItemRPG"] = "RPG";
CW_TURKISH["ItemRPGDesc"] = "Büyük yeşil bir silah, geri tepmemesi umsan iyi olur.";
CW_TURKISH["ItemShotgun"] = "Pompalı";
CW_TURKISH["ItemShotgunDesc"] = "Donuk gri renkte kaplanmış, orta büyüklükte bir silah.";
CW_TURKISH["ItemMP7"] = "MP7";
CW_TURKISH["ItemMP7Desc"] = "Koyu gri renkte kaplanmış kompakt bir silah, uygun bir tutamağı var.";
CW_TURKISH["ItemWhiskey"] = "Viski";
CW_TURKISH["ItemWhiskeyDesc"] = "Kahverengi renkli bir viski şişesi, dikkatli olun!";
CW_TURKISH["ItemZipTie"] = "İp";
CW_TURKISH["ItemZipTieDesc"] = "Thomas ve Betts ile birlikte turuncu renkli fermuar.";
CW_TURKISH["CharacterPermanentlyKilled"] = "BU KARAKTER KALICI ÖLDÜRÜLDÜ";
CW_TURKISH["GoToCharScreenToMakeNew"] = "Karakter menüsüne git ve yeni bir tane yap.";
CW_TURKISH["YouAreBeingTiedUpCenter"] = "ELLERİN BAĞLANIYOR";
CW_TURKISH["YouHaveBeenTiedUpCenter"] = "ELLERİN BAĞLANDI";
CW_TURKISH["DexterityDesc"] = "Genel hızını etkiler, örneğin: hızlı ip bağlama, çözme.";
CW_TURKISH["EnduranceDesc"] = "Genel direncini etkiler, örneğin: aldığın hasar.";
CW_TURKISH["MedicalDesc"] = "Genel tıbbi yeteneğini etkiler, örneğin: tıbbi kitlerden aldığın can.";
CW_TURKISH["StrengthDesc"] = "Genel gücünü etkilet, örneğin: ne kadar güçlü vurduğun.";
CW_TURKISH["AcrobaticsDesc"] = "Atlayabileceğiniz yüksekliği etkiler.";
CW_TURKISH["AgilityDesc"] = "Genel hızınızı etkiler, örneğin: ne kadar hızlı koştuğun.";
CW_TURKISH["PurchasePermitGeneralGoodsHelp"] = "İşletmenize mal eklemek için izin alın.";
CW_TURKISH["BusinessCreateHelpText"] = "Bir işletme oluştur, izin satın almanı sağlar.";
CW_TURKISH["PurchasePermitCustomHelp"] = "İşletmenize #1 eklemek için izin satın alın.";
CW_TURKISH["CreateBusiness"] = "İşletme kur";
CW_TURKISH["PermitsTitle"] = "İşletme İzinleri";
CW_TURKISH["PlayerInfoCash"] = "Para: #2";
CW_TURKISH["PlayerInfoWages"] = "Ücret: #2";
CW_TURKISH["PlayerInfoName"] = "#1";
CW_TURKISH["PlayerInfoClass"] = "#1";
CW_TURKISH["CmdStorageGiveCash"] = "Depoya para koy.";
CW_TURKISH["CmdStorageTakeCash"] = "Depodan para al.";
CW_TURKISH["CmdGiveCash"] = "Baktığın karaktere para ver.";
CW_TURKISH["CmdDropCash"] = "Baktığın yöne para bırak.";
CW_TURKISH["CmdSetCash"] = "Bir karakterin parasını ayarla.";
CW_TURKISH["CashAmountSingular"] = "#1";
CW_TURKISH["CashAmount"] = "#1 Para";
CW_TURKISH["Cash"] = "Paralar";
|
object_tangible_storyteller_prop_pr_ch9_pillar_corellia_02 = object_tangible_storyteller_prop_shared_pr_ch9_pillar_corellia_02:new {
}
ObjectTemplates:addTemplate(object_tangible_storyteller_prop_pr_ch9_pillar_corellia_02, "object/tangible/storyteller/prop/pr_ch9_pillar_corellia_02.iff")
|
addEventHandler('onClientPlayerJoin', getRootElement(),function()
if (#getElementsByType("player")>50) then return end
local t=string.format("Na serwer wchodzi %s.", string.gsub(getPlayerName(source),"#%x%x%x%x%x%x",""))
outputChatBox( "» "..t, 255,100,100)
end)
addEventHandler('onClientPlayerQuit', root,function(reason)
if (#getElementsByType("player")>50) then return end
-- if getElementData(source,"dbid") then
outputChatBox( "× " .. string.gsub(getPlayerName(source),"#%x%x%x%x%x%x","") .. " opuścił/a serwer.", 255,100,100)
-- end
end) |
local Version = require("Quadtastic.Version")
-- Check simple format
do
local s = "v1.2.4"
local v = Version(s)
assert(type(v.major) == "number")
assert(v.major == 1)
assert(type(v.minor) == "number")
assert(v.minor == 2)
assert(type(v.patch) == "number")
assert(v.patch == 4)
end
-- Check format that includes `git decribe` information
do
local s = "v1.2.4-12-aszxc123"
local v = Version(s)
assert(v.major == 1)
assert(v.minor == 2)
assert(v.patch == 4)
end
-- Check that parsing fails if no patch version is given
do
local s = "v1.2"
local success, more = pcall(Version, s)
assert(not success)
end
-- Check that parsing fails if no patch or minor version is given
do
local s = "v1"
local success, more = pcall(Version, s)
assert(not success)
end
-- Check to_string method
do
local s = "v1.2.4"
local v = Version(s)
assert("1.2.4" == Version.to_string(v))
assert("1.2.4" == string.format("%s", v))
end
-- Check equality
do
local s1 = "v1.2.4"
local s2 = "1.2.4-123-zxc"
local v1 = Version(s1)
local v2 = Version(s2)
assert(v1 == v2)
assert(Version.equals(v1, v2))
end
-- Check inequality
do
local s1 = "v1.2.4"
local s2 = "1.2.5-123-zxc"
local s3 = "1.3.4-123-zxc"
local s4 = "v2.2.4"
local v1 = Version(s1)
local v2 = Version(s2)
local v3 = Version(s3)
local v4 = Version(s4)
assert(v1 ~= v2)
assert(v1 ~= v3)
assert(v1 ~= v4)
assert(v2 ~= v3)
assert(v2 ~= v4)
assert(v3 ~= v4)
end
-- Check comparator
do
local s1 = "v1.2.4"
local s2 = "1.2.5-123-zxc"
local s3 = "1.3.4-123-zxc"
local s4 = "v2.2.4"
local v1 = Version(s1)
local v2 = Version(s2)
local v3 = Version(s3)
local v4 = Version(s4)
assert(v1 < v2)
assert(v2 > v1)
assert(v1 <= v2)
assert(v2 >= v1)
assert(v1 < v3)
assert(v3 > v1)
assert(v1 <= v3)
assert(v3 >= v1)
assert(v1 < v4)
assert(v4 > v1)
assert(v1 <= v4)
assert(v4 >= v1)
assert(v2 < v3)
assert(v3 > v2)
assert(v2 <= v3)
assert(v3 >= v2)
assert(v2 < v4)
assert(v4 > v2)
assert(v2 <= v4)
assert(v4 >= v2)
assert(v3 < v4)
assert(v4 > v3)
assert(v3 <= v4)
assert(v4 >= v3)
end
|
require('pgproc').bind('test')
print(test.fun('world!')['fun'])
print(test.create('{ "some" : "json" }')['create'])
|
--- === plugins.finalcutpro.fullscreen.disableesc ===
---
--- Disables the ESC key when Final Cut Pro is in fullscreen mode.
local require = require
local eventtap = require "hs.eventtap"
local keycodes = require "hs.keycodes"
local app = require "cp.app"
local config = require "cp.config"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local tools = require "cp.tools"
local mod = {}
--- plugins.finalcutpro.fullscreen.disableesc.enabled <cp.prop: boolean>
--- Variable
--- Is the Disable ESC Key Function enabled?
mod.enabled = config.prop("fcp.disableEscKey", false)
--- plugins.finalcutpro.fullscreen.disableesc.fcpActiveFullScreen <cp.prop: boolean; read-only; live>
--- Variable
--- If `true` FCP is full-screen and the frontmost app.
mod.fcpActiveFullScreen = fcp:primaryWindow().isFullScreen:AND(app.frontmostApp:IS(fcp.app)):AND(fcp.isModalDialogOpen:IS(false))
:watch(function(enabled)
if mod.enabled() and enabled then
if mod._eventtap == nil then
mod._eventtap = eventtap.new({eventtap.event.types.keyDown}, function(object)
if object:getKeyCode() == keycodes.map.escape then
tools.playErrorSound()
return true
end
end):start()
end
else
if mod._eventtap then
mod._eventtap:stop()
mod._eventtap = nil
end
end
end)
local plugin = {
id = "finalcutpro.fullscreen.disableesc",
group = "finalcutpro",
dependencies = {
["finalcutpro.preferences.manager"] = "prefs",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Setup Menubar Preferences Panel:
--------------------------------------------------------------------------------
if deps and deps.prefs and deps.prefs.panel then
deps.prefs.panel
--------------------------------------------------------------------------------
-- Add Preferences Checkbox:
--------------------------------------------------------------------------------
:addCheckbox(1.2,
{
label = i18n("ignoreESCKeyWhenFinalCutProIsFullscreen"),
onchange = function(_, params) mod.enabled(params.checked) end,
checked = mod.enabled,
}
)
end
return mod
end
function plugin.postInit()
mod.fcpActiveFullScreen:update()
end
return plugin
|
-------------------------- DEEP STORAGE ----------------------------
-- Entity --
dsE = {}
dsE.type = "container"
dsE.name = "DeepStorage"
dsE.icon = "__Mobile_Factory_Graphics__/graphics/icons/DeepStorageI.png"
dsE.icon_size = 256
dsE.flags = {"placeable-neutral", "player-creation"}
dsE.minable = {mining_time = 0.8, result = "DeepStorage"}
dsE.max_health = 200
dsE.corpse = "small-remnants"
dsE.open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 }
dsE.close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 }
dsE.resistances ={}
dsE.collision_box = {{-1.75, -1.45}, {1.75, 1.2}}
dsE.selection_box = {{-2.4, -1.7}, {2.4, 1.7}}
dsE.fast_replaceable_group = nil
dsE.next_upgrade = nil
dsE.inventory_size = 0
dsE.vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }
dsE.picture =
{
layers =
{
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DeepStorageE.png",
priority = "low",
width = 600,
height = 600,
--shift = util.by_pixel(-0.5, -0.5),
scale = 1/4
},
{
filename = "__Mobile_Factory_Graphics__/graphics/entity/DeepStorageS.png",
priority = "very-low",
width = 620,
height = 608,
draw_as_shadow = true,
shift = util.by_pixel(4, 2),
scale = 1/4
}
}
}
dsE.circuit_wire_connection_point = circuit_connector_definitions["chest"].points
dsE.circuit_connector_sprites = circuit_connector_definitions["chest"].sprites
dsE.circuit_wire_max_distance = default_circuit_wire_max_distance
data:extend{dsE}
-- Item --
local dsI = {}
dsI.type = "item-with-tags"
dsI.name = "DeepStorage"
dsI.icon = "__Mobile_Factory_Graphics__/graphics/icons/DeepStorageI.png"
dsI.icon_size = 256
dsI.place_result = "DeepStorage"
dsI.subgroup = "DataSerialization"
dsI.order = "c"
dsI.stack_size = 5
data:extend{dsI}
-- Recipe --
local dsR = {}
dsR.type = "recipe"
dsR.name = "DeepStorage"
dsR.energy_required = 2
dsR.enabled = false
dsR.ingredients =
{
{"CrystalizedCircuit", 8},
{"MachineFrame3", 2}
}
dsR.result = "DeepStorage"
data:extend{dsR}
-- Technologie --
local dsT = {}
dsT.name = "DeepStorage"
dsT.type = "technology"
dsT.icon = "__Mobile_Factory_Graphics__/graphics/icons/DeepStorageI.png"
dsT.icon_size = 256
dsT.unit = {
count=20,
time=60,
ingredients={
{"DimensionalSample", 50},
{"DimensionalCrystal", 1}
}
}
dsT.prerequisites = {"ControlCenter", "MatterSerialization"}
dsT.effects = {
{type="nothing", effect_description={"description.DeepStorage"}},
{type="unlock-recipe", recipe="DeepStorage"}
}
data:extend{dsT} |
print('session.storage')
session = box.session
dump = function(data) return "'" .. require('json').encode(data) .. "'" end
type(session.id())
session.unknown_field
type(session.storage)
session.storage.abc = 'cde'
session.storage.abc
all = getmetatable(session).aggregate_storage
dump(all)
--# create connection second to default
--# set connection second
type(session.storage)
type(session.storage.abc)
session.storage.abc = 'def'
session.storage.abc
--# set connection default
session.storage.abc
--# set connection second
dump(all[session.id()])
--# set connection default
dump(all[session.id()])
tres1 = {}
tres2 = {}
for k,v in pairs(all) do table.insert(tres1, v.abc) end
--# drop connection second
require('fiber').sleep(.01)
for k,v in pairs(all) do table.insert(tres2, v.abc) end
table.sort(tres1)
table.sort(tres2)
dump(tres1)
dump(tres2)
getmetatable(session).aggregate_storage = {}
session = nil
|
local a=require("cc.expect")require(settings.get("ghu.base").."core/apis/ghu")local b=require("am.ui")local c=require("am.event")local d=require("am.core")local e=require("am.progress.helpers")local f=require("am.log")local g=require("am.progress.quarry")local h=require("am.progress.collect")local i=require("am.progress.colonies")local j={}local k={}local l=nil;local m=250;local function n(o,p)if not p then return b.Frame(b.a.Anchor(1,1),{id=string.format("progressFrame.%d",o.id),fillHorizontal=true,fillVertical=true,border=0,backgroundColor=colors.black,textColor=colors.white})end;if l==nil then l=b.TabbedFrame(b.a.Anchor(1,1),{id="progressFrame",fillHorizontal=true,fillVertical=true,border=0,backgroundColor=colors.black,textColor=colors.white,primaryTabId=tostring(o.id),showTabs=true,tabFillColor=colors.gray,tabTextColor=colors.black,activeTabFillColor=colors.black,activeTabTextColor=colors.yellow,tabPadTop=1,tabPadBottom=0})return l.tabs[1]end;return l:createTab(tostring(o.id))end;local function q(o,r,s,p)a.expect(1,o,"table")a.expect(2,s,"table","nil")a.expect(3,r,"table","nil")a.expect(4,p,"boolean","nil")local t=s~=nil and r~=nil;if s~=nil then b.h.requireOutput(s)end;if p==nil then p=false end;local u=k[o.id]local v=false;if t then if u~=nil then local w=u.output;if b.h.isFrameScreen(w)then w=b.h.getFrameScreen(w).output end;if not u.names[r.name]or not b.h.isSameScreen(w,s)then k[o.id]=nil;u=nil end end;if u==nil then if r.name==c.c.Event.Progress.quarry or r.name==c.c.Event.Progress.collect or r.name==c.c.Event.Progress.tree or r.name==c.c.Event.Colonies.status_poll then local x=n(o,p)local y=s;if p and l~=nil then y=l:makeScreen(s)end;if r.name==c.c.Event.Progress.quarry then u=g(o,r,y,x)elseif r.name==c.c.Event.Progress.collect or r.name==c.c.Event.Progress.tree then u=h(o,r,y,x)elseif r.name==c.c.Event.Colonies.status_poll then u=i(o,r.status.id,y,x)u.progress.status=r.status end end;if u~=nil then u:createUI()k[o.id]=u;if l~=nil then l:setActive(s,#l.tabs)if#l.tabs==1 then s.clear()l:render(s)end end end;v=u~=nil end end;return u,v end;local function z(s)for A,u in pairs(k)do local w=u.output;if b.h.isFrameScreen(w)then w=b.h.getFrameScreen(w).output end;if b.h.isSameScreen(s,w)then return{id=A}end end;return nil end;local function B(o,C)a.expect(1,o,"table")a.expect(2,C,"table")local u=q(o)if u~=nil then u:updatePosition(o,C)end end;local function D(o,E)a.expect(1,o,"table")a.expect(2,E,"string")local u=q(o)if u~=nil then u:updateStatus(o,E)end end;local function F(o,r,s,p)a.expect(1,o,"table")a.expect(2,r,"table")a.expect(3,s,"table","nil")a.expect(4,p,"boolean","nil")if s==nil then s=term else b.h.requireOutput(s)end;if p==nil then p=false end;local u,v=q(o,r,s,p)if u~=nil and not v then u:update(o,r)end end;local function G(r,H)if l~=nil then l:handle(term,r,table.unpack(H))else for I,u in pairs(k)do u:handle(c.getComputer(),r,H)end end end;local function J(o,r,H)local K=os.epoch("utc")local L=nil;if b.c.l.Events.Always[r]then G(r,H)return elseif b.c.l.Events.UI[r]then local M=d.split(H[1].objId,".")if M[1]=="progressFrame"then L={id=tonumber(M[2])}end elseif b.c.l.Events.Terminal[r]then L=z(term)elseif b.c.l.Events.Monitor[r]then L=z(peripheral.wrap(H[1]))elseif r==c.c.Event.Pathfind.position then B(o,H[1].position)return end;if l~=nil and r==b.c.e.Events.tab_change and H[1].objId==l.id then local N=l:getTab(H[1].newTabId)for A,u in pairs(k)do if u.frame.id==N.id then u:update({id=A},nil,true)break end end end;if L~=nil then o=L end;if l~=nil then l:handle(term,r,table.unpack(H))else local u,I=q(o)if u~=nil then u:handle(o,r,H)end end;local O=os.epoch("utc")-K;if O>m then if b.c.l.Events.UI[r]then f.warning(string.format("UI Event %s took too long to process (%s): %s",r,O,f.format(H[1])))else f.warning(string.format("Event %s took too long to process (%s)",r,O))end end end;j.updateStatus=D;j.updatePosition=B;j.print=F;j.handle=J;j.itemStrings=e.itemStrings;return j
|
--[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
-- github_repository class
local github_repository = {}
local github_repository_mt = {
__name = "github_repository";
__index = github_repository;
}
local function cast_github_repository(t)
return setmetatable(t, github_repository_mt)
end
local function new_github_repository(_class, _links, default_branch, description, name, permissions, private, full_name)
return cast_github_repository({
["_class"] = _class;
["_links"] = _links;
["defaultBranch"] = default_branch;
["description"] = description;
["name"] = name;
["permissions"] = permissions;
["private"] = private;
["fullName"] = full_name;
})
end
return {
cast = cast_github_repository;
new = new_github_repository;
}
|
return function()
return {
on_attach = function(client)
client.resolved_capabilities.document_formatting = false
client.resolved_capabilities.document_range_formatting = false
end,
}
end
|
return require(script.Parent.Parent.Parent.Proxy)
|
local json_encode = require("cjson.safe").new().encode
local protocols = {
ec2 = true,
json = true,
query = true,
["rest-xml"] = true,
["rest-json"] = true,
}
local function poor_mans_xml_encoding(output, shape, shape_name, data, indent)
local indent = indent or 0
local prefix = string.rep(" ", indent)
local element = shape.locationName or shape_name
local xmlns = ""
if (shape.xmlNamespace or {}).uri then
xmlns = (' xmlns="%s"'):format(shape.xmlNamespace.uri)
end
if shape.type == "structure" or
shape.type == "list" or
shape.type == "map" then
-- nested structures
output[#output+1] = prefix .. '<' .. element .. xmlns .. ">"
if shape.type == "structure" then
for name, member in pairs(shape.members) do
if data[name] then
poor_mans_xml_encoding(output, member, name, data[name], indent + 1)
end
end
elseif shape.type == "list" then
for i, member_data in ipairs(data or {}) do
poor_mans_xml_encoding(output, shape.member, "unknown", member_data, indent + 1)
end
else -- shape.type == "map"
error("protocol 'rest-xml' hasn't implemented the 'map' type")
end
output[#output+1] = prefix .. '</' .. element .. ">"
else
-- just a scalar value
output[#output+1] = prefix .. '<' .. element .. xmlns .. ">" ..
tostring(data) .. '</' .. element .. ">"
end
end
-- implement AWS api protocols.
-- returns a request table;
-- * method; the HTTP method to use
-- * path; possibly containing rendered values
-- * query; hash-table with query arguments
-- * body; string with formatted body
-- * headers; hash table with headers
--
-- Input parameters:
-- * operation table
-- * config: config table for instantiated service
-- * params: parameters for the call
local function build_request(operation, config, params)
-- print(require("pl.pretty").write(config))
-- print(require("pl.pretty").write(operation))
if not protocols[config.protocol or ""] then
error("Bad config, field protocol is invalid, got: '" .. tostring(config.protocol) .. "'")
end
local request = {
path = (operation.http or {}).requestUri or "",
method = (operation.http or {}).method,
query = {},
headers = {
["X-Amz-Target"] = (config.signingName or config.targetPrefix) .. "." .. operation.name,
},
body = {},
}
-- inject parameters in the right places; path/query/header/body
-- this assumes they all live on the top-level of the structure, is this correct??
for name, member_config in pairs(operation.input.members) do
local param_value = params[name]
-- TODO: date-time value should be properly formatted???
if param_value ~= nil then
-- a parameter value is provided
local location = member_config.location
local locationName = member_config.locationName
-- print(name," = ", param_value, ": ",location, " (", locationName,")")
if location == "uri" then
local place_holder = "{" .. locationName .. "}"
request.path = request.path:gsub(place_holder, param_value)
elseif location == "querystring" then
request.query[locationName] = param_value
elseif location == "header" then
request.headers[locationName] = param_value
else
if config.protocol == "query" then
-- no location specified, but protocol is query, so it goes into query
request.query[name] = param_value
else
-- nowhere else to go, so put it in the body (for json and xml)
request.body[name] = param_value
end
end
end
end
-- format the body
if not next(request.body) then
-- No body values left, remove table
request.body = nil
else
-- encode the body
if config.protocol == "ec2" then
error("protocol 'ec2' not implemented yet")
elseif config.protocol == "rest-xml" then
local xml_data = {
'<?xml version="1.0" encoding="UTF-8"?>',
}
-- encode rest of the body data here
poor_mans_xml_encoding(xml_data, operation.input, "input", request.body)
-- TODO: untested, assuming "application/xml" as the default type here???
request.headers["Content-Type"] = request.headers["Content-Type"] or "application/xml"
request.body = table.concat(xml_data, "\n")
else
-- assuming remaining protocols "rest-json", "json", "query" to be safe to json encode
local version = config.jsonVersion or '1.0'
request.headers["Content-Type"] = request.headers["Content-Type"] or "application/x-amz-json-" .. version
request.body = json_encode(request.body)
end
request.headers["Content-Length"] = #request.body
end
return request
end
return build_request
|
function Server_Created(game, settings)
local overriddenBonuses = {};
for _, bonus in pairs(game.Map.Bonuses) do
--skip negative bonuses unless AllowNegative was checked
if (bonus.Amount > 0 or Mod.Settings.AllowNegative) then
local rndAmount = math.random(-Mod.Settings.RandomizeAmount, Mod.Settings.RandomizeAmount);
if (rndAmount ~= 0) then --don't do anything if we're not changing the bonus. We could leave this check off and it would work, but it show up in Settings as an overridden bonus when it's not.
local newValue = bonus.Amount + rndAmount;
-- don't take a positive or zero bonus negative unless AllowNegative was checked.
if (newValue < 0 and not Mod.Settings.AllowNegative) then
newValue = 0;
end
-- -1000 to +1000 is the maximum allowed range for overridden bonuses, never go beyond that
if (newValue < -1000) then newValue = -1000 end;
if (newValue > 1000) then newValue = 1000 end;
overriddenBonuses[bonus.ID] = newValue;
end
end
end
settings.OverriddenBonuses = overriddenBonuses;
end
|
#!/usr/bin/lua5.1
nexthop="bulcs"
localpath="/srv/www/lights/"
local forwarder=false
package.path = localpath .. "lib/?.lua;" .. package.path
local file,err = io.open( localpath .. "switches.txt", "r" )
if file~=nil then
forwarder=false or forwarder
local tmpfile,err = io.open( "/tmp/switches.txt", "r" )
if tmpfile~=nil then
tmpfile:close()
else
instr = file:read("*a")
outfile = io.open("/tmp/switches.txt", "w")
outfile:write(instr)
outfile:close()
end
file:close()
else
forwarder=true
end
local CGI = require( "CGI" )
CGI:response():setHeader('Expires: Sat, 1 Jan 2005 00:00:00 GMT;Cache-Control: no-cache, must-revalidate;Pragma: no-cache;')
local adress = (CGI:request():parameter("adress")~=nil) and CGI:request():parameter("adress") or "02"
local state = (CGI:request():parameter("state")~=nil) and CGI:request():parameter("state") or "0"
request = function (rU)
local answer
if (pcall (require, "socket")) and (rU~=nil) then
local http = require("socket.http")
answer = http.request(rU)
else
answer = [[
No answer from ]] .. nexthop
end
return answer
end
local requestURL
if forwarder then
if (CGI:request():parameter("adress")~=nil) and (CGI:request():parameter("state")~=nil) then
requestURL = "http://" .. nexthop .. "/lights/cgi-bin/states.lua?state=" .. state .. "&adress=" .. adress
elseif (CGI:request():parameter("adress")~=nil) then
requestURL = "http://" .. nexthop .. "/lights/cgi-bin/states.lua?adress=" .. adress
else
requestURL = "http://" .. nexthop .. "/lights/cgi-bin/states.lua"
end
CGI:print()(request(requestURL))
else
require( "tablesave" )
local switches = table.load( "/tmp/switches.txt" )
if (CGI:request():parameter("adress")~=nil) and (CGI:request():parameter("state")~=nil) then
for k,v in pairs(switches) do
if (adress==v.adress) then
v.state=state
if (v.module=="rfmsend") then
if (state=="1") then
os.execute("sudo nice -20 " .. localpath .. "modules/rfmsend/rfmsend -a " .. adress .. " -s " .. v.oncommand)
elseif (state=="0") then
os.execute("sudo nice -20 " .. localpath .. "modules/rfmsend/rfmsend -a " .. adress .. " -s " .. v.offcommand)
end
elseif (v.module=="cmd") then
if (state=="1") then
os.execute(v.oncommand)
elseif (state=="0") then
os.execute(v.offcommand)
end
elseif (v.module=="cluster") then
if (state=="1") then
--TODO
elseif (state=="0") then
--TODO
end
else
os.execute("echo " .. adress .. " -s " .. v.offcommand .."> /tmp/test.tst")
end
end
end
--requestURL = "http://" .. ethersex .. "/ecmd?fs20%20send%200xCCCC%200x" .. adress .. "%200x" .. state .. "0"
--request(requestURL)
--os.execute("sudo " .. localpath .. "modules/rfmsend/rfmsend -a " .. adress .. " -s " .. state .. "0")
table.save( switches, "/tmp/switches.txt" )
end
local json = require ("dkjson")
if (CGI:request():parameter("adress")~=nil) then
for k,v in pairs(switches) do
if (adress==v.adress) then
CGI:print()(json.encode (v, { indent = true }))
end
end
else
local inventory = {}
for k,v in pairs(switches) do
inventory[k] = v.adress
end
CGI:print()(json.encode (inventory, { indent = true }))
end
-- table.save( switches, "/tmp/switches.txt" )
end
|
#!/usr/bin/env tarantool
local listen = os.getenv('TNT_LISTEN_URI')
box.cfg {
listen = (listen == '' or listen == nil) and 3301 or listen,
log_level = 6,
wal_mode = 'none',
snap_dir = '/tmp'
}
box.schema.user.grant('guest', 'read,write,execute,create,drop,alter', 'universe', nil, {if_not_exists = true})
queue = require('queue')
function try_drop_tube(name)
if queue.tube[name] then
queue.tube[name]:drop()
end
end
function create_tube(name, type, opts)
try_drop_tube(name)
return queue.create_tube(name, type, opts)
end
|
-- compatibility wrapper
fx_version 'adamant'
game 'common'
dependency 'basic-gamemode' |
-- WARNING: DO NOT USE THIS SCRIPT ITS CURRENTLY EXPERIMENTAL
if game.PlaceId ~= 263135585 then print("run this in galaxy beta you monkey 🐒") return end
local character = game.Players.LocalPlayer.Character or game.Players.LocalPlayer.CharacterAdded:Wait()
character.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
local YourTeam = game.Players.LocalPlayer.Team
local YourMiner = game.Players.LocalPlayer.ActiveShip.Value
local rs = game:GetService("RunService")
local ship = workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner))
if not YourMiner or not ship then print("Please spawn a ship!") return end
local shippoint = workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner)).CenterPoint
local basepoint = game.workspace.Bases:FindFirstChild("Mega Base").Model.CenterPoint
if ship.Configuration:FindFirstChild("NoWarp") ~= null then
ship.Configuration.NoWarp.Value = false
end
local args = {
[1] = "Teleport",
[2] = workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner)).PilotSeat
}
workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner)).ButtonPress:FireServer(unpack(args))
wait(1)
shippoint.BodyGyro.CFrame = CFrame.new(shippoint.Position, basepoint.Position)
repeat
ship.PilotSeat.Throttle = 1
rs.Heartbeat:Wait()
until ship.PilotSeat.Velocity.magnitude >= ship.PilotSeat.MaxSpeed-5
ship.PilotSeat.Throttle = 0
local args = {
[1] = "ShipWarp"
}
workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner)).ButtonPress:FireServer(unpack(args))
while wait() do
local distance = (shippoint.Position - basepoint.Position).Magnitude
if distance <= 1000 then
local funnything = false
coroutine.resume(coroutine.create(function()
wait(1)
funnything = true
end))
while funnything == false do
ship.PilotSeat.Throttle = -1
wait()
end
ship.PilotSeat.Throttle = 0
wait(1)
local args = {
[1] = "ShipDock"
}
workspace.Ships:FindFirstChild(tostring(YourTeam)):FindFirstChild(tostring(YourMiner)).ButtonPress:FireServer(unpack(args))
break
end
end
|
local threads = require 'threads'
local nthread = 4
local njob = 100
local pool = threads.Threads(
nthread,
function(threadid)
print('starting a new thread/state number ' .. threadid)
end
)
local jobid = 0
local result -- DO NOT put this in get
local function get()
-- fill up the queue as much as we can
-- this will not block
while jobid < njob and pool:acceptsjob() do
jobid = jobid + 1
pool:addjob(
function(jobid)
print(string.format('thread ID %d is performing job %d', __threadid, jobid))
return string.format("job output from job %d", jobid)
end,
function(jobres)
result = jobres
end,
jobid
)
end
-- is there still something to do?
if pool:hasjob() then
pool:dojob() -- yes? do it!
return result
end
end
local jobdone = 0
repeat
-- get something asynchronously
local res = get()
-- do something with res (if any)
if res then
print(res)
jobdone = jobdone + 1
end
until not res -- until there is nothing remaining
assert(jobid == 100)
assert(jobdone == 100)
print('PASSED')
pool:terminate()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.