content
stringlengths 5
1.05M
|
---|
return {
Sgyd = 1,
Assy = 2,
};
|
-- This file is part of the Luau programming language and is licensed under MIT License; see LICENSE.txt for details
print('testing lua_exception')
-- Verify that no exception is generated
function empty_function()
end
function pass_number_to_error()
-- Verify the error value of 42 is part of the exception's string.
error(42)
end
function pass_string_to_error()
-- Verify the error value of "string argument" is part of the exception's string.
error("string argument")
end
function pass_table_to_error()
-- Pass a table to `error`. A table is used since it is won't be
-- convertable to a string using `lua_tostring`.
error({field="value"})
end
function infinite_recursion_error()
-- Generate a stack overflow error
infinite_recursion_error()
end
function large_allocation_error()
-- Create a table that will require more memory than the test's memory
-- allocator will allow.
table.create(1000000)
end
return('OK')
|
insulate("HashSet Test | ", function()
local hashSet = nil
setup(function()
hashSet = require("HashSet"):new()
end)
before_each(function()
hashSet:clear()
end)
randomize()
test("isEmpty()", function()
assert.is_true(hashSet:isEmpty())
end)
test("clear(); checking size is 0", function()
hashSet:clear()
assert.is_true(hashSet:isEmpty())
end)
test("size(); check if empty HashSet is 0", function()
hashSet:clear()
assert.is_true(hashSet:size() == 0)
end)
test("add 1; size should be 1, isEmpty should be false", function()
hashSet:add("elem1")
assert.is.equal(1, hashSet:size())
assert.is_false(hashSet:isEmpty())
end)
test("add element then see if the hashset contains it", function()
local e = "elem1"
assert.is_false(hashSet:contains(e))
hashSet:add(e)
assert.is_true(hashSet:contains(e))
end)
test("add multiple DUPLICATES; size should be 1, isEmpty should be false", function()
math.randomseed(os.time())
local numTimes = math.random(10, 20)
for _ = 1, numTimes do hashSet:add("elem") end
assert.is.equal(1, hashSet:size())
assert.is_false(hashSet:isEmpty())
end)
test("add multiple non-duplicates; size should be 1, isEmpty should be false", function()
math.randomseed(os.time())
local numTimes = math.random(10, 20)
for i = 1, numTimes do hashSet:add("elem" .. i) end
assert.is.equal(numTimes, hashSet:size())
assert.is_false(hashSet:isEmpty())
end)
test("Add 5 elements then return an iterator", function()
local expectedSet = {
elem3 = "elem3",
elem1 = "elem1",
elem4 = "elem4",
elem5 = "elem5",
elem2 = "elem2",
}
for key, _ in pairs(expectedSet) do hashSet:add(key) end
local iter = hashSet:iterator()
local i = 1
for elem in iter do
assert.is_true(expectedSet[elem] ~= nil)
i = i + 1
end
end)
test("add 1 then remove 1, size == 0 and hashset should be empty", function()
hashSet:add("elem1")
hashSet:remove("elem1")
assert.is_true(hashSet:isEmpty())
assert.is.equal(0, hashSet:size())
end)
test("add 1 then remove 1 then readd it, size == 1 and hashset should not be empty", function()
hashSet:add("elem1")
hashSet:remove("elem1")
hashSet:add("elem1")
hashSet:add("elem1")
assert.is_false(hashSet:isEmpty())
assert.is.equal(1, hashSet:size())
end)
test("Remove from empty list; Size should still be 0, list should still be empty", function()
hashSet:remove("elem1")
assert.is_true(hashSet:isEmpty())
assert.is.equal(0, hashSet:size())
end)
test("Add 1, remove it, then try to remove again", function()
assert.is_true(hashSet:add("elem1"))
assert.is_true(hashSet:remove("elem1"))
assert.is_true(hashSet:isEmpty())
assert.is.equal(0, hashSet:size())
assert.is_false(hashSet:remove("elem1"))
assert.is_true(hashSet:isEmpty())
assert.is.equal(0, hashSet:size())
end)
test("Add 3, remove 1, size should be 2", function()
assert.is_true(hashSet:add("elem1"))
assert.is_false(hashSet:add("elem1"))
assert.is_true(hashSet:add("elem2"))
assert.is_true(hashSet:add("elem3"))
assert.is_true(hashSet:remove("elem2"))
assert.is.equal(2, hashSet:size())
end)
end)
|
-- Example: FPS and delta-time
function love.draw()
-- Draw the current FPS.
love.graphics.print("FPS: " .. love.timer.getFPS(), 50, 50)
-- Draw the current delta-time. (The same value
-- is passed to update each frame).
love.graphics.print("dt: " .. love.timer.getDelta(), 50, 100)
end
|
return {'salisch','salvadoraan','salvadoraans','salade','saladeschaal','salam','salamander','salamanderkachel','salamanders','salami','salamipolitiek','salamitactiek','salangaan','salariaat','salaris','salarisaanpassing','salarisachterstand','salarisactie','salarisadministratie','salarisbetaling','salariscategorie','salarischeque','salariseis','salarisgarantieregeling','salarisgarantieregelingen','salarisgrens','salarisgrenzen','salarisgroei','salarisgroep','salarisherziening','salarisklasse','salariskorting','salariskosten','salarisniveau','salarisontwikkeling','salarisplafond','salarisregeling','salarisschaal','salarisschijf','salarisstaat','salarisstijging','salarisstrook','salarisstructuur','salarissysteem','salaristabel','salarisverbetering','salarisvergelijking','salarisverhoging','salarisverlaging','salarisvermindering','salarisverschil','salarieren','salariering','salbutamol','salderen','saldi','saldibalans','saldilijst','saldo','saldobedrag','saldobedragen','saldobetaling','saldobiljet','salesiaan','salesmanager','salespromotor','salet','saletjonker','salicyl','salicylzuur','salie','saliemelk','saline','salmagundi','salmi','salmiak','salmiakdrop','salmonella','salmonellabacterie','salmonellabesmetting','salmonellavergiftiging','salomonsoordeel','salomonszegel','salon','salonameublement','salonboot','saloncommunist','salonfahig','salonheld','salonmuziek','salonorkest','salonrijtuig','salonsocialist','salonstuk','salontafel','salontafelboek','salonwagen','saloon','saloondeur','salpeter','salpeterzuur','salsa','salsaband','salsamuziek','salto','salueren','salut','saluut','saluutschot','salvarsan','salvia','salvo','saloeki','saladbar','salamkramp','salarisslip','salesianer','salkvaccin','salpeterzout','salarisverwerking','saladebar','saladebuffet','salarisadministrateur','salarisbedrag','salarisgebouw','salarisgesprek','salarisnummer','salarispakket','salarisrekening','salonsocialisme','salarisindicatie','saldering','salarisbeleid','salima','salland','sallander','sallands','salomo','salomonseilanden','salween','sal','salah','salar','saleh','salem','salih','salim','salina','sally','salma','salman','salome','salomon','salome','saloua','salvador','salvatore','salden','salm','salverda','salemink','sala','salentijn','salters','salimans','salemans','salari','salij','salhi','salama','salmi','saleem','sale','salische','salades','salamandertje','salamandertjes','salamis','salanganen','salarieerde','salarieert','salarisaanpassingen','salarisberekeningen','salarisbetalingen','salariscategorieen','salarischeques','salariseisen','salarisgegevens','salarisgroepen','salarisklassen','salarismaatregelen','salarisonderhandelingen','salarisregelingen','salarisschalen','salarissen','salarisstaten','salarisstijgingen','salaristabellen','salarisverhogingen','salarisverschillen','saldeer','saldeerde','saldeerden','saldeert','saldibalansen','saldilijsten','saldos','saldobetalingen','saldobiljetten','saldocijfers','salesianen','salesmanagers','saletjonkers','saletten','salinen','salines','salmiakpastilles','salomonsoordelen','salomonszegels','salonboten','salonhelden','salonnetje','salonnetjes','salonrijtuigen','salons','salontafels','salontafeltje','salontafeltjes','salonwagens','salpeterzure','saltos','salueer','salueerde','salueerden','salueert','saluerend','saluerende','saluutschoten','salvias','salvos','salvootje','salvadoraanse','salvadoranen','saladeschalen','salamanderkachels','saloncommunisten','salonfahige','salonsocialisten','saloondeuren','saloons','salviaatje','saloekis','saladbars','salarisslips','salarisverlagingen','salespromotors','salmonellas','sallandse','sals','salahs','salars','salehs','salems','salihs','salims','salimas','salinas','sallys','salmas','salmans','salomes','salomons','salomes','salouas','salvadors','salvatores','salarisadministraties','salarisstroken','salarisstrookje','salarisstrookjes','salarissystemen','salarisstructuren','salarisniveaus','salarisadministrateurs','salarisbedragen','salarisontwikkelingen','salarisplafonds','salarisverbeteringen','salarisgesprekken','salarisindicaties'}
|
EditLadder = EditLadder or class(EditUnit)
function EditLadder:editable(unit) return unit:ladder() ~= nil end
function EditLadder:update_positions() self:selected_unit():ladder():set_config() end
function EditLadder:build_menu(units)
local ladder_options = self:Group("Ladder")
self._width = self:NumberBox("Width[cm]", callback(self, self, "set_unit_data_parent"), units[1]:ladder():width(), {floats = 0, min = 0, help = "Sets the width of the ladder in cm", group = ladder_options})
self._height = self:NumberBox("Height[cm]", callback(self, self, "set_unit_data_parent"), units[1]:ladder():height(), {floats = 0, min = 0, help = "Sets the height of the ladder in cm", group = ladder_options})
units[1]:set_config()
end
function EditLadder:set_unit_data()
local unit = self:selected_unit()
unit:ladder():set_width(self._width:Value())
unit:ladder():set_height(self._height:Value())
end
function EditLadder:update(t, dt)
for _, unit in ipairs(self._selected_units) do
if unit:ladder() then
unit:ladder():debug_draw()
end
end
end
|
-- plugins will be installed to the cache directory
plugin_home = vim.fn.stdpath('cache') .. '/tmux.nvim'
vim_plug_url = 'https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim'
vim_plug = plugin_home .. '/plug.vim'
-- install vim-plug automatically if needed
if vim.fn.filereadable(vim_plug) == 0 then
vim.cmd(
'silent !curl -fLo ' .. vim_plug .. ' --create-dirs ' .. vim_plug_url
)
end
vim.opt.runtimepath:append(plugin_home)
vim.fn['plug#begin'](plugin_home)
vim.fn['plug#']('spywhere/tmux.nvim')
vim.fn['plug#end']()
-- install or update plugins as needed
if vim.fn.isdirectory(plugin_home .. '/tmux.nvim') == 0 then
vim.cmd('PlugInstall --sync | q')
else
vim.cmd('PlugUpdate --sync | q')
end
local tmux = require('tmux')
local cmds = require('tmux.commands')
-- some configurations go here
-- may be changing the default prefix key?
-- tmux.prefix('<C-a>')
-- may be binding a new key?
-- tmux.bind('|', cmds.split_window { 'v' } )
-- tmux.bind('-', cmds.split_window { 'h' } )
tmux.start() -- this will start a terminal session
|
require('gitsigns').setup {
numhl = true,
current_line_blame = true,
sign_priority = 5,
word_diff = false,
}
|
local request = require 'http.functional.request'
local writer = require 'http.functional.response'
local json = require 'core.encoding.json'
local describe, it, assert = describe, it, assert
local function test_cases(app)
assert.not_nil(app)
it('responds with bad request status code and errors', function()
local w, req = writer.new(), request.new {method = 'POST'}
app(w, req)
assert.equals(400, w.status_code)
assert.same({['Content-Type'] = 'application/json'}, w.headers)
assert(json.decode(table.concat(w.buffer)))
end)
it('accepts a valid input', function()
local w = writer.new()
local req = request.new {
method = 'POST',
body = {
author = 'jack', message = 'hello'
}
}
app(w, req)
assert.is_nil(w.status_code)
end)
end
describe('demos.http.form', function()
test_cases(require 'demos.http.form')
end)
describe('demos.web.form', function()
test_cases(require 'demos.web.form')
end)
|
-- don't want to leave these in a real script, but it is a handy tool.
function describeElement(element)
local tag = '<' .. element.tag .. ' '
for key, value in pairs(element.attributes) do
local val = (type(value) == 'table' and '(table)') or value
tag = tag .. key .. '=' .. val .. ' '
end
broadcastToAll(tag .. ' />')
end
function findElement(id, uiCollection)
for _, element in pairs(uiCollection) do
if element.attributes.id == id then return element end
if element.children and #element.children > 0 then
local foundElement = findElement(id, element.children)
if foundElement then return foundElement end
end
end
end
function debugElement(id)
describeElement(findElement(id, UI.getXmlTable()))
end
|
package("cef")
set_homepage("https://bitbucket.org/chromiumembedded")
set_description("Chromium Embedded Framework (CEF). A simple framework for embedding Chromium-based browsers in other applications.")
set_license("BSD-3-Clause")
local buildver = {
["88.2.1"] = "88.2.1+g0b18d0b+chromium-88.0.4324.146",
["88.2.9"] = "88.2.9+g5c8711a+chromium-88.0.4324.182",
["90.5.3"] = "90.5.3+gaf0e862+chromium-90.0.4430.72",
["91.1.22"] = "91.1.22+gc67b5dd+chromium-91.0.4472.124"
}
if is_plat("windows") then
add_urls("https://cef-builds.spotifycdn.com/cef_binary_$(version).tar.bz2", {version = function (version)
return format("%s_windows%s", buildver[tostring(version)], (is_arch("x64") and "64" or "32"))
end})
if is_arch("x64") then
add_versions("91.1.22", "a01dd3f996061a8d0ddc1a2ab211340f9b3bb890eef3606329579b43101607dc")
add_versions("90.5.3", "d92abe3e3d3aa2aa7bf25669fe7cb59a0232ee9eb14ad4f1ea60334f9485d0ef")
add_versions("88.2.9", "86c01e38e7b7d59fed8a1e1ab2c3bfbcc1db42e21f8a6e6feb4061b2af7b1b7d")
add_versions("88.2.1", "8ed01da6327258536c61ada46e14157149ce727e7729ec35a30b91b3ad3cf555")
else
add_versions("91.1.22", "9f9ab6787f2d35024238aceab5d1eccf49e19e8bfe2519ca96610fe2bbe82ad1")
add_versions("90.5.3", "8e49009a543273319ae51d58e1b78a1695f3864c5773cdfdf7f5994810d0874d")
add_versions("88.2.9", "90c15421d6d7b970ca839b746d8e85c09f449ae37d87d07f42dd45dfe16df455")
add_versions("88.2.1", "f608e4028478d4c87541c679f5cfe42bda0d459a80ee26acfe93f634c25e96ab")
end
add_configs("vs_runtime", {description = "Set vs compiler runtime.", default = "MT", type = "string", readonly = true})
end
add_configs("shared", {description = "Build shared library.", default = true, type = "boolean", readonly = true})
if is_plat("windows") then
add_syslinks("user32", "advapi32", "shlwapi", "comctl32", "rpcrt4")
end
add_includedirs(".", "include")
on_install("windows", function (package)
local distrib_type = package:debug() and "Debug" or "Release"
os.cp(path.join(distrib_type, "*.lib"), package:installdir("lib"))
os.cp(path.join(distrib_type, "*.dll"), package:installdir("bin"))
os.cp(path.join(distrib_type, "swiftshader", "*.dll"), package:installdir("bin", "swiftshader"))
os.cp(path.join(distrib_type, "*.bin"), package:installdir("bin"))
os.cp("Resources/*", package:installdir("bin"))
os.cp(path.join(package:scriptdir(), "port", "xmake.lua"), "xmake.lua")
import("package.tools.xmake").install(package)
end)
on_test(function (package)
assert(package:has_cxxfuncs("CefEnableHighDPISupport", {includes = "cef_app.h"}))
end)
|
module ('base', package.seeall)
require 'lux.object'
drawable = lux.object.new {}
drawable.__init = {
color = {255, 255, 255, 255}
}
|
-- MIT License
--
-- Copyright (c) [year] [fullname]
--
-- 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 base64 = require'nvim-lsp-clangd-highlight/base64_decode'
local highlight = require'vim/highlight'
local M = {}
M.enabled = true
M.debug = false
local clangd_scopes = {}
local clangd_namespace = vim.api.nvim_create_namespace("vim_lsp_clangd_references")
local clangd_kind_to_highlight_group_map = {
-- https://github.com/clangd/coc-clangd/blob/28e8d303b723716240e680090c86535582e7894f/src/semantic-highlighting.ts#L125
-- https://github.com/llvm/llvm-project/blob/4e3a44d42eace1924c9cba3b7c1ea9cdbbd6cb48/clang-tools-extra/clangd/SemanticHighlighting.cpp#L584
["entity.name.function.cpp"] = "ClangdFunction",
["entity.name.function.method.cpp"] = "ClangdMemberFunction",
["entity.name.function.method.static.cpp"] = "ClangdStaticMemberFunction",
["variable.other.cpp"] = "ClangdVariable",
["variable.other.local.cpp"] = "ClangdLocalVariable",
["variable.parameter.cpp"] = "ClangdParameter",
["variable.other.field.cpp"] = "ClangdField",
["variable.other.field.static.cpp"] = "ClangdStaticField",
["entity.name.type.class.cpp"] = "ClangdClass",
["entity.name.type.enum.cpp"] = "ClangdEnum",
["variable.other.enummember.cpp"] = "ClangdEnumConstant",
["entity.name.type.typedef.cpp"] = "ClangdTypedef",
["entity.name.type.dependent.cpp"] = "ClangdDependentType",
["entity.name.other.dependent.cpp"] = "ClangdDependentName",
["entity.name.namespace.cpp"] = "ClangdNamespace",
["entity.name.type.template.cpp"] = "ClangdTemplateParameter",
["entity.name.type.concept.cpp"] = "ClangdConcept",
["storage.type.primitive.cpp"] = "ClangdPrimitive",
["entity.name.function.preprocessor.cpp"] = "ClangdMacro",
["meta.disabled"] = "ClangdInactiveCode",
}
local function clangd_decode_kind(scope)
local result = clangd_kind_to_highlight_group_map[scope]
if not result then
return 'ClangdUnknown'
end
return result
end
local function highlight_references(bufnr,references)
vim.validate { bufnr = {bufnr, 'n', true} }
for _,ref in ipairs(references) do
if M.debug then
print(bufnr, ref.kind, vim.inspect(ref.range))
end
highlight.range(bufnr, clangd_namespace, ref.kind, ref.range.start_pos, ref.range.end_pos)
end
end
local function clear_references(bufnr)
vim.validate { bufnr = {bufnr, 'n', true} }
vim.api.nvim_buf_clear_namespace(bufnr, clangd_namespace, 0, -1)
end
local function highlight(_,result,_,_)
if M.debug then
print("Highlight called")
end
if not result or not M.enabled then
return
end
local uri = result.textDocument.uri
if M.debug then
print("Uri: " .. uri)
end
local file = ""
if vim.fn.exists('win32') then
-- uri starts with file:// and then the path but path always starts with /
-- On windows we don't want to start the path with starting "/"
-- This ends up giving us path like /C:/rest/of/the/path
file = string.gsub(uri, 'file:///' , "")
-- nvim_buf_get_name will return paths with "\" separators
file = string.gsub(file, '/', '\\')
else
file = string.gsub(uri, 'file://' , "")
end
for _,bufnum in ipairs(vim.api.nvim_list_bufs()) do
local buf_name = vim.api.nvim_buf_get_name(bufnum)
if M.debug then
print(buf_name,file)
end
if file==buf_name then
if M.debug then
print("Highlighting buffer")
end
local references = {}
local references_index = 1
for _, token in ipairs(result.lines) do
local uint32array = base64.base64toUInt32Array(token.tokens)
for j = 1,uint32array.size,2 do
local start_character_index = uint32array.data[j]
local length = bit.rshift(uint32array.data[j+1], 16)
local scope_index = bit.band(uint32array.data[j+1], 0xffff)+1
local ref = {
range = {
start_pos = {token.line, start_character_index},
end_pos = {token.line, start_character_index + length}
},
kind = clangd_decode_kind(clangd_scopes[scope_index][1])
}
vim.api.nvim_buf_clear_namespace(bufnum, clangd_namespace, token.line, token.line)
references[references_index] = ref
references_index = references_index + 1
end
end
-- clear_references(bufnum)
highlight_references(bufnum, references)
end
end
end
function M.on_init(config)
clangd_scopes = config.server_capabilities.semanticHighlighting.scopes
config.handlers['textDocument/semanticHighlighting'] = highlight
if M.debug then
print("On init called")
end
end
function M.clear_highlight()
local buf_number = vim.api.nvim_get_current_buf()
clear_references(buf_number)
end
function M.reload()
M.clear_highlight()
vim.api.nvim_command(":e")
end
function M.enable()
M.enabled = true
M.reload()
end
function M.disable()
M.enabled = false
M.clear_highlight()
end
return M
|
-- premake5.lua
-- ChotuEditor Project
workspace "Platform"
architecture "x64"
configurations{
"Debug",
"Release"
}
startproject "Test"
flags{
"MultiProcessorCompile",
"FloatFast"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
project "Platform_Detection"
location "Platform_Detection"
kind "StaticLib"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs{
"%{prj.name}/src"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "on"
systemversion "latest"
filter "configurations:Debug"
defines "CR_DEBUG"
symbols "on"
filter "configurations:Release"
defines "CR_RELEASE"
optimize "on"
project "Test"
location "Test"
kind "ConsoleApp"
language "C++"
targetdir ("bin/" .. outputdir .. "/%{prj.name}")
objdir ("bin-int/" .. outputdir .. "/%{prj.name}")
files{
"%{prj.name}/src/**.h",
"%{prj.name}/src/**.cpp"
}
includedirs{
"Platform_Detection/src"
}
links{
"Platform_Detection"
}
filter "system:windows"
cppdialect "C++17"
staticruntime "on"
systemversion "latest"
filter "configurations:Debug"
defines "CR_DEBUG"
symbols "on"
filter "configurations:Release"
defines "CR_RELEASE"
optimize "on"
|
dbg=require "debugger"
function swap(t,i,j)
local temp=t[i]
t[i]=t[j]
t[j]=temp
end
--this is string comparator
--INPUT: x,y are strings
function comp(x,y)
if x ==nil or y==nil then return false end
if x<y then return -1
elseif x == y then return 0
elseif x > y then return 1
else return false
end
end
function partition(t,left,right,comp)
local x=t[right]
local i=left-1
for j=left,right-1 do
if comp(t[j],x)<=0 then
i=i+1
swap(t,i,j)
end
end
swap(t,i+1,right)
return i+1
end
function qsort(t,left,right,comp)
dbg()
if comp(left,right)<=0 then
local q=partition(t,left,right,comp)
qsort(t,left,q-1,comp)
qsort(t,q+1,right,comp)
end
end
function printTab(t)
for i=1,#t do
io.write(t[i]," ")
end
io.write("\n");
end
function main()
local l={10,-1,3,6,8,0,2,-5}
printTab(l)
qsort(l,1,#l,comp)
printTab(l)
local l2={'b','d','f','z','a','w','j','i'}
printTab(l2)
qsort(l2,1,#l2,comp)
printTab(l2)
end
main()
|
--Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--Children folder includes
-- Server Objects
includeFile("tangible/component/bio/base_bio_component_clothing_casual.lua")
includeFile("tangible/component/bio/base_bio_component_clothing_field.lua")
includeFile("tangible/component/bio/base_bio_component_clothing_formal.lua")
includeFile("tangible/component/bio/base_bio_component_food.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_charisma.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_charisma_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_entertainer.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_entertainer_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_medic.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_medic_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_taming.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_taming_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_training.lua")
includeFile("tangible/component/bio/bio_component_clothing_casual_training_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_armor.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_armor_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_bleeding.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_bleeding_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_camo.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_camo_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_cover.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_cover_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_defense.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_defense_2.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_intimidate.lua")
includeFile("tangible/component/bio/bio_component_clothing_field_intimidate_2.lua")
includeFile("tangible/component/bio/bio_component_food_heavy.lua")
includeFile("tangible/component/bio/bio_component_food_heavy_filling.lua")
includeFile("tangible/component/bio/bio_component_food_heavy_flavor.lua")
includeFile("tangible/component/bio/bio_component_food_heavy_nutrition.lua")
includeFile("tangible/component/bio/bio_component_food_heavy_quantity.lua")
includeFile("tangible/component/bio/bio_component_food_light.lua")
includeFile("tangible/component/bio/bio_component_food_light_filling.lua")
includeFile("tangible/component/bio/bio_component_food_light_flavor.lua")
includeFile("tangible/component/bio/bio_component_food_light_nutrition.lua")
includeFile("tangible/component/bio/bio_component_food_light_quantity.lua")
includeFile("tangible/component/bio/bio_component_food_medium.lua")
includeFile("tangible/component/bio/bio_component_food_medium_filling.lua")
includeFile("tangible/component/bio/bio_component_food_medium_flavor.lua")
includeFile("tangible/component/bio/bio_component_food_medium_nutrition.lua")
includeFile("tangible/component/bio/bio_component_food_medium_quantity.lua")
|
if !ItemUsable then
require_relative 'sh_item_usable'
end
class 'ItemAmmo' extends 'ItemUsable'
ItemAmmo.name = 'Ammunition Base'
ItemAmmo.description = 'An item that contains some ammo.'
ItemAmmo.category = 'item.category.ammo'
ItemAmmo.model = 'models/items/boxsrounds.mdl'
ItemAmmo.background_color = Color(200, 200, 70)
ItemAmmo.use_text = 'item.option.load'
ItemAmmo.ammo_class = 'Pistol'
ItemAmmo.ammo_count = 16
ItemAmmo.max_uses = 1
function ItemAmmo:use(player)
player:GiveAmmo(self.ammo_count, self.ammo_class)
end
|
Locales['fi'] = {
-- cloakroom
['cloakroom_menu'] = 'cloakroom',
['cloakroom_prompt'] = 'press ~INPUT_CONTEXT~ to open the ~y~cloakroom~s~.',
['wear_citizen'] = 'citizen wear',
['wear_work'] = 'taxi wear',
-- garage
['spawner_prompt'] = 'press ~INPUT_CONTEXT~ to open the ~y~garage~s~.',
['store_veh'] = 'paina ~INPUT_CONTEXT~ laittaaksesi auto talliin',
['spawn_veh'] = 'spawnaa ajoneuvo',
['spawnpoint_blocked'] = 'there is a vehicle blocking the spawnpoint!',
['only_taxi'] = 'Voit vain tallettaa taxeja',
['taking_service'] = 'Aloitetaan työ: Taxi/Uber',
['full_service'] = 'täysi palvelu: ',
['amount_invalid'] = 'virheellinen summa',
['press_to_open'] = 'paina ~INPUT_CONTEXT~ avataksesi valikko',
['billing'] = 'Laskutus',
['billing_sent'] = 'the bill has been registered!',
['invoice_amount'] = 'laskun määrä',
['no_players_near'] = 'ei pelaajia lähellä',
['start_job'] = 'start / stop driving NPC jobs',
['drive_search_pass'] = 'Ajele ympäriinsä etsi uusia ~y~asiakkaita',
['customer_found'] = 'Sinä ~g~löysit~s~ asiakkaan, aja lähemmäksi',
['client_unconcious'] = 'Sinun asiakkaasi on ~r~tajuton~s~. Etsi uusi.',
['arrive_dest'] = 'Sinä ~g~saavuit~s~ kohteeseen',
['take_me_to_near'] = '~s~Vie minut ~y~ %s~s~, lähellä~y~ %s',
['take_me_to'] = '~s~Vie minut~y~ %s',
['close_to_client'] = 'Olet asiakkaan lähellä, mene lähemmäksi',
['return_to_veh'] = 'Mene takaisin ajoneuvoon, jatkaaksesi töitä',
['must_in_taxi'] = 'Sinun pitää olla taxissa että voit alottaa työn',
['must_in_vehicle'] = 'Sinun pitää olla ajoneuvossa että voit alottaa työn',
['have_earned'] = 'Sinä tienasit ~g~€%s~s~',
['comp_earned'] = '- Yrityksesi tienasi ~g~€%s~s~\n- Sinä tienasit ~g~€%s~s~',
['deposit_stock'] = 'Talleta varastoon',
['take_stock'] = 'ota varastosta',
['boss_actions'] = 'pomon toiminnot',
['mission_complete'] = 'tehtävä suoritettu',
['quantity'] = 'määrä',
['quantity_invalid'] = 'virheellinen Määrä',
['inventory'] = 'reppu',
['taxi_client'] = 'taxi Asiakas',
['have_withdrawn'] = 'sinä nostit ~y~x%s~s~ ~b~%s~s~',
['have_deposited'] = 'sinä talletit ~y~x%s~s~ ~b~%s~s~',
['player_cannot_hold'] = 'sinulla ~r~ei ole~s~ enempää ~y~vapaata tilaa~s~ repussasi!',
['blip_taxi'] = 'taxi',
['phone_taxi'] = 'taxi',
}
|
assert:set_parameter("TableFormatLevel", 5) -- when displaying tables, set a bigger default depth
------------------------
-- START TEST HELPERS --
------------------------
local client, balancer
local helpers = require "spec.test_helpers"
local gettime = helpers.gettime
local sleep = helpers.sleep
local dnsSRV = function(...) return helpers.dnsSRV(client, ...) end
local dnsA = function(...) return helpers.dnsA(client, ...) end
local dnsAAAA = function(...) return helpers.dnsAAAA(client, ...) end
-- creates a hash table with "address:port" keys and as value the number of indices
local function count_indices(balancer)
local r = {}
local continuum = balancer:_get_continuum()
for _, address in pairs(continuum) do
local key = tostring(address.ip)
if key:find(":",1,true) then
--print("available: ", address.available)
key = "["..key.."]:"..address.port
else
key = key..":"..address.port
end
r[key] = (r[key] or 0) + 1
end
return r
end
-- copies the wheel to a list with ip, port and hostname in the field values.
-- can be used for before/after comparison
local copyWheel = function(b)
local copy = {}
local continuum = b:_get_continuum()
for i, address in pairs(continuum) do
copy[i] = i.." - "..address.ip.." @ "..address.port.." ("..address.host.hostname..")"
end
return copy
end
----------------------
-- END TEST HELPERS --
----------------------
describe("[consistent_hashing]", function()
local snapshot
setup(function()
_G.package.loaded["resty.dns.client"] = nil -- make sure module is reloaded
balancer = require "resty.dns.balancer.consistent_hashing"
client = require "resty.dns.client"
end)
before_each(function()
assert(client.init {
hosts = {},
resolvConf = {
"nameserver 8.8.8.8"
},
})
snapshot = assert:snapshot()
end)
after_each(function()
snapshot:revert() -- undo any spying/stubbing etc.
collectgarbage()
collectgarbage()
end)
it("ringbalancer with a running timer gets GC'ed", function()
local b = balancer.new({
dns = client,
wheelSize = 15,
requery = 0.1,
})
assert(b:addHost("this.will.not.be.found", 80, 10))
local tracker = setmetatable({ b }, {__mode = "v"})
local t = 0
while t<10 do
if t>0.5 then -- let the timer do its work, only dismiss after 0.5 seconds
-- luacheck: push no unused
b = nil -- mark it for GC
-- luacheck: pop
end
sleep(0.1)
collectgarbage()
if not next(tracker) then
break
end
t = t + 0.1
end
assert(t < 10, "timeout while waiting for balancer to be GC'ed")
end)
describe("getting targets", function()
it("gets an IP address and port number; consistent hashing", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
})
dnsA({
{ name = "getkong.org", address = "5.6.7.8" },
})
local b = balancer.new({
hosts = {
{name = "mashape.com", port = 123, weight = 10},
{name = "getkong.org", port = 321, weight = 5},
},
dns = client,
wheelSize = (1000),
})
-- run down the wheel, hitting all indices once
local res = {}
for n = 1, 1500 do
local addr, port, host = b:getPeer(false, nil, tostring(n))
res[addr..":"..port] = (res[addr..":"..port] or 0) + 1
res[host..":"..port] = (res[host..":"..port] or 0) + 1
end
-- weight distribution may vary up to 10% when using ketama algorithm
assert.is_true(res["1.2.3.4:123"] > 900)
assert.is_true(res["1.2.3.4:123"] < 1100)
assert.is_true(res["5.6.7.8:321"] > 450)
assert.is_true(res["5.6.7.8:321"] < 550)
-- hit one index 15 times
res = {}
local hash = tostring(6) -- just pick one
for _ = 1, 15 do
local addr, port, host = b:getPeer(false, nil, hash)
res[addr..":"..port] = (res[addr..":"..port] or 0) + 1
res[host..":"..port] = (res[host..":"..port] or 0) + 1
end
assert(15 == res["1.2.3.4:123"] or nil == res["1.2.3.4:123"], "mismatch")
assert(15 == res["mashape.com:123"] or nil == res["mashape.com:123"], "mismatch")
assert(15 == res["5.6.7.8:321"] or nil == res["5.6.7.8:321"], "mismatch")
assert(15 == res["getkong.org:321"] or nil == res["getkong.org:321"], "mismatch")
end)
it("evaluate the change in the continuum", function()
local res1 = {}
local res2 = {}
local res3 = {}
local b = balancer.new({
hosts = {
{name = "10.0.0.1", port = 1, weight = 100},
{name = "10.0.0.2", port = 2, weight = 100},
{name = "10.0.0.3", port = 3, weight = 100},
{name = "10.0.0.4", port = 4, weight = 100},
{name = "10.0.0.5", port = 5, weight = 100},
},
dns = client,
wheelSize = 5000,
})
for n = 1, 10000 do
local addr, port = b:getPeer(false, nil, n)
res1[n] = { ip = addr, port = port }
end
b:addHost("10.0.0.6", 6, 100)
for n = 1, 10000 do
local addr, port = b:getPeer(false, nil, n)
res2[n] = { ip = addr, port = port }
end
local dif = 0
for n = 1, 10000 do
if res1[n].ip ~= res2[n].ip or res1[n].port ~= res2[n].port then
dif = dif + 1
end
end
-- increasing the number of addresses from 5 to 6 should change 49% of
-- targets if we were using a simple distribution, like an array.
-- anyway, we should be below than 20%.
assert((dif/100) < 49, "it should be better than a simple distribution")
assert((dif/100) < 20, "it is still to much change ")
b:addHost("10.0.0.7", 7, 100)
b:addHost("10.0.0.8", 8, 100)
for n = 1, 10000 do
local addr, port = b:getPeer(false, nil, n)
res3[n] = { ip = addr, port = port }
end
dif = 0
local dif2 = 0
for n = 1, 10000 do
if res1[n].ip ~= res3[n].ip or res1[n].port ~= res3[n].port then
dif = dif + 1
end
if res2[n].ip ~= res3[n].ip or res2[n].port ~= res3[n].port then
dif2 = dif2 + 1
end
end
-- increasing the number of addresses from 5 to 8 should change 83% of
-- targets, and from 6 to 8, 76%, if we were using a simple distribution,
-- like an array.
-- either way, we should be below than 40% and 25%.
assert((dif/100) < 83, "it should be better than a simple distribution")
assert((dif/100) < 40, "it is still to much change ")
assert((dif2/100) < 76, "it should be better than a simple distribution")
assert((dif2/100) < 25, "it is still to much change ")
end)
it("gets an IP address and port number; consistent hashing skips unhealthy addresses", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
})
dnsA({
{ name = "getkong.org", address = "5.6.7.8" },
})
local b = balancer.new({
hosts = {
{name = "mashape.com", port = 123, weight = 100},
{name = "getkong.org", port = 321, weight = 50},
},
dns = client,
wheelSize = 1000,
})
-- mark node down
assert(b:setAddressStatus(false, "1.2.3.4", 123, "mashape.com"))
-- do a few requests
local res = {}
for n = 1, 160 do
local addr, port, host = b:getPeer(false, nil, n)
res[addr..":"..port] = (res[addr..":"..port] or 0) + 1
res[host..":"..port] = (res[host..":"..port] or 0) + 1
end
assert.equal(nil, res["1.2.3.4:123"]) -- address got no hits, key never gets initialized
assert.equal(nil, res["mashape.com:123"]) -- host got no hits, key never gets initialized
assert.equal(160, res["5.6.7.8:321"])
assert.equal(160, res["getkong.org:321"])
end)
it("does not hit the resolver when 'cache_only' is set", function()
local record = dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
})
local b = balancer.new({
hosts = { { name = "mashape.com", port = 80, weight = 5 } },
dns = client,
wheelSize = 10,
})
record.expire = gettime() - 1 -- expire current dns cache record
dnsA({ -- create a new record
{ name = "mashape.com", address = "5.6.7.8" },
})
-- create a spy to check whether dns was queried
spy.on(client, "resolve")
local hash = "a value to hash"
local cache_only = true
local ip, port, host = b:getPeer(cache_only, nil, hash)
assert.spy(client.resolve).Not.called_with("mashape.com",nil, nil)
assert.equal("1.2.3.4", ip) -- initial un-updated ip address
assert.equal(80, port)
assert.equal("mashape.com", host)
end)
end)
describe("setting status triggers address-callback", function()
it("for IP addresses", function()
local count_add = 0
local count_remove = 0
local b
b = balancer.new({
hosts = {}, -- no hosts, so balancer is empty
dns = client,
wheelSize = 10,
callback = function(balancer, action, address, ip, port, hostname)
assert.equal(b, balancer)
if action == "added" then
count_add = count_add + 1
elseif action == "removed" then
count_remove = count_remove + 1
elseif action == "health" then --luacheck: ignore
-- nothing to do
else
error("unknown action received: "..tostring(action))
end
if action ~= "health" then
assert.equals("12.34.56.78", ip)
assert.equals(123, port)
assert.equals("12.34.56.78", hostname)
end
end
})
b:addHost("12.34.56.78", 123, 100)
ngx.sleep(0.1)
assert.equal(1, count_add)
assert.equal(0, count_remove)
b:removeHost("12.34.56.78", 123)
ngx.sleep(0.1)
assert.equal(1, count_add)
assert.equal(1, count_remove)
end)
it("for 1 level dns", function()
local count_add = 0
local count_remove = 0
local b
b = balancer.new({
hosts = {}, -- no hosts, so balancer is empty
dns = client,
wheelSize = 10,
callback = function(balancer, action, address, ip, port, hostname)
assert.equal(b, balancer)
if action == "added" then
count_add = count_add + 1
elseif action == "removed" then
count_remove = count_remove + 1
elseif action == "health" then --luacheck: ignore
-- nothing to do
else
error("unknown action received: "..tostring(action))
end
if action ~= "health" then
assert.equals("12.34.56.78", ip)
assert.equals(123, port)
assert.equals("mashape.com", hostname)
end
end
})
dnsA({
{ name = "mashape.com", address = "12.34.56.78" },
{ name = "mashape.com", address = "12.34.56.78" },
})
b:addHost("mashape.com", 123, 100)
ngx.sleep(0.1)
assert.equal(2, count_add)
assert.equal(0, count_remove)
b:removeHost("mashape.com", 123)
ngx.sleep(0.1)
assert.equal(2, count_add)
assert.equal(2, count_remove)
end)
it("for 2+ level dns", function()
local count_add = 0
local count_remove = 0
local b
b = balancer.new({
hosts = {}, -- no hosts, so balancer is empty
dns = client,
wheelSize = 10,
callback = function(balancer, action, address, ip, port, hostname)
assert.equal(b, balancer)
if action == "added" then
count_add = count_add + 1
elseif action == "removed" then
count_remove = count_remove + 1
elseif action == "health" then --luacheck: ignore
-- nothing to do
else
error("unknown action received: "..tostring(action))
end
if action ~= "health" then
assert(ip == "mashape1.com" or ip == "mashape2.com")
assert(port == 8001 or port == 8002)
assert.equals("mashape.com", hostname)
end
end
})
dnsA({
{ name = "mashape1.com", address = "12.34.56.1" },
})
dnsA({
{ name = "mashape2.com", address = "12.34.56.2" },
})
dnsSRV({
{ name = "mashape.com", target = "mashape1.com", port = 8001, weight = 5 },
{ name = "mashape.com", target = "mashape2.com", port = 8002, weight = 5 },
})
b:addHost("mashape.com", 123, 100)
ngx.sleep(0.1)
assert.equal(2, count_add)
assert.equal(0, count_remove)
b:removeHost("mashape.com", 123)
ngx.sleep(0.1)
assert.equal(2, count_add)
assert.equal(2, count_remove)
end)
end)
describe("wheel manipulation", function()
it("wheel updates are atomic", function()
-- testcase for issue #49, see:
-- https://github.com/Kong/lua-resty-dns-client/issues/49
local order_of_events = {}
local b
b = balancer.new({
hosts = {}, -- no hosts, so balancer is empty
dns = client,
wheelSize = 10,
callback = function(balancer, action, ip, port, hostname)
table.insert(order_of_events, "callback")
-- this callback is called when updating. So yield here and
-- verify that the second thread does not interfere with
-- the first update, yielded here.
ngx.sleep(0.1)
end
})
dnsA({
{ name = "mashape1.com", address = "12.34.56.78" },
})
dnsA({
{ name = "mashape2.com", address = "123.45.67.89" },
})
local t1 = ngx.thread.spawn(function()
table.insert(order_of_events, "thread1 start")
b:addHost("mashape1.com")
table.insert(order_of_events, "thread1 end")
end)
local t2 = ngx.thread.spawn(function()
table.insert(order_of_events, "thread2 start")
b:addHost("mashape2.com")
table.insert(order_of_events, "thread2 end")
end)
ngx.thread.wait(t1)
ngx.thread.wait(t2)
ngx.sleep(0.1)
assert.same({
[1] = 'thread1 start',
[2] = 'thread1 end',
[3] = 'thread2 start',
[4] = 'thread2 end',
[5] = 'callback',
[6] = 'callback',
[7] = 'callback',
}, order_of_events)
end)
it("equal weights and 'fitting' indices", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
local b = balancer.new({
hosts = {"mashape.com"},
dns = client,
wheelSize = 1000,
})
local expected = {
["1.2.3.4:80"] = 80,
["1.2.3.5:80"] = 80,
}
assert.are.same(expected, count_indices(b))
end)
it("DNS record order has no effect", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.1" },
{ name = "mashape.com", address = "1.2.3.2" },
{ name = "mashape.com", address = "1.2.3.3" },
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
{ name = "mashape.com", address = "1.2.3.6" },
{ name = "mashape.com", address = "1.2.3.7" },
{ name = "mashape.com", address = "1.2.3.8" },
{ name = "mashape.com", address = "1.2.3.9" },
{ name = "mashape.com", address = "1.2.3.10" },
})
local b = balancer.new({
hosts = {"mashape.com"},
dns = client,
wheelSize = 1000,
})
local expected = count_indices(b)
dnsA({
{ name = "mashape.com", address = "1.2.3.8" },
{ name = "mashape.com", address = "1.2.3.3" },
{ name = "mashape.com", address = "1.2.3.1" },
{ name = "mashape.com", address = "1.2.3.2" },
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
{ name = "mashape.com", address = "1.2.3.6" },
{ name = "mashape.com", address = "1.2.3.9" },
{ name = "mashape.com", address = "1.2.3.10" },
{ name = "mashape.com", address = "1.2.3.7" },
})
b = balancer.new({
hosts = {"mashape.com"},
dns = client,
wheelSize = 1000,
})
assert.are.same(expected, count_indices(b))
end)
it("changing hostname order has no effect", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.1" },
})
dnsA({
{ name = "getkong.org", address = "1.2.3.2" },
})
local b = balancer.new {
hosts = {"mashape.com", "getkong.org"},
dns = client,
wheelSize = 1000,
}
local expected = count_indices(b)
b = balancer.new({
hosts = {"getkong.org", "mashape.com"}, -- changed host order
dns = client,
wheelSize = 1000,
})
assert.are.same(expected, count_indices(b))
end)
it("adding a host", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
dnsAAAA({
{ name = "getkong.org", address = "::1" },
})
local b = balancer.new({
hosts = { { name = "mashape.com", port = 80, weight = 5 } },
dns = client,
wheelSize = 2000,
})
b:addHost("getkong.org", 8080, 10 )
local expected = {
["1.2.3.4:80"] = 80,
["1.2.3.5:80"] = 80,
["[::1]:8080"] = 160,
}
assert.are.same(expected, count_indices(b))
end)
it("removing the last host", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
dnsAAAA({
{ name = "getkong.org", address = "::1" },
})
local b = balancer.new({
dns = client,
wheelSize = 1000,
})
b:addHost("mashape.com", 80, 5)
b:addHost("getkong.org", 8080, 10)
b:removeHost("getkong.org", 8080)
b:removeHost("mashape.com", 80)
end)
it("weight change updates properly", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
dnsAAAA({
{ name = "getkong.org", address = "::1" },
})
local b = balancer.new({
dns = client,
wheelSize = 1000,
})
b:addHost("mashape.com", 80, 10)
b:addHost("getkong.org", 80, 10)
local count = count_indices(b)
-- 2 hosts -> 320 points
-- resolved to 3 addresses with same weight -> 106 points each
assert.same({
["1.2.3.4:80"] = 106,
["1.2.3.5:80"] = 106,
["[::1]:80"] = 106,
}, count)
b:addHost("mashape.com", 80, 25)
count = count_indices(b)
-- 2 hosts -> 320 points
-- 1 with 83% of weight resolved to 2 addresses -> 133 points each addr
-- 1 with 16% of weight resolved to 1 address -> 53 points
assert.same({
["1.2.3.4:80"] = 133,
["1.2.3.5:80"] = 133,
["[::1]:80"] = 53,
}, count)
end)
it("weight change ttl=0 record, updates properly", function()
-- mock the resolve/toip methods
local old_resolve = client.resolve
local old_toip = client.toip
finally(function()
client.resolve = old_resolve
client.toip = old_toip
end)
client.resolve = function(name, ...)
if name == "mashape.com" then
local record = dnsA({
{ name = "mashape.com", address = "1.2.3.4", ttl = 0 },
})
return record
else
return old_resolve(name, ...)
end
end
client.toip = function(name, ...)
if name == "mashape.com" then
return "1.2.3.4", ...
else
return old_toip(name, ...)
end
end
-- insert 2nd address
dnsA({
{ name = "getkong.org", address = "9.9.9.9", ttl = 60*60 },
})
local b = balancer.new({
hosts = {
{ name = "mashape.com", port = 80, weight = 50 },
{ name = "getkong.org", port = 123, weight = 50 },
},
dns = client,
wheelSize = 100,
ttl0 = 2,
})
local count = count_indices(b)
assert.same({
["mashape.com:80"] = 160,
["9.9.9.9:123"] = 160,
}, count)
-- update weights
b:addHost("mashape.com", 80, 150)
count = count_indices(b)
-- total weight: 200
-- 2 hosts: 320 points
-- 75%: 240, 25%: 80
assert.same({
["mashape.com:80"] = 240,
["9.9.9.9:123"] = 80,
}, count)
end)
it("weight change for unresolved record, updates properly", function()
local record = dnsA({
{ name = "really.really.really.does.not.exist.thijsschreijer.nl", address = "1.2.3.4" },
})
dnsAAAA({
{ name = "getkong.org", address = "::1" },
})
local b = balancer.new({
dns = client,
wheelSize = 1000,
requery = 0.1,
})
b:addHost("really.really.really.does.not.exist.thijsschreijer.nl", 80, 10)
b:addHost("getkong.org", 80, 10)
local count = count_indices(b)
assert.same({
["1.2.3.4:80"] = 160,
["[::1]:80"] = 160,
}, count)
-- expire the existing record
record.expire = 0
record.expired = true
-- do a lookup to trigger the async lookup
client.resolve("really.really.really.does.not.exist.thijsschreijer.nl", {qtype = client.TYPE_A})
sleep(1) -- provide time for async lookup to complete
b:_hit_all() -- hit them all to force renewal
count = count_indices(b)
assert.same({
--["1.2.3.4:80"] = 0, --> failed to resolve, no more entries
["[::1]:80"] = 320,
}, count)
-- update the failed record
b:addHost("really.really.really.does.not.exist.thijsschreijer.nl", 80, 20)
-- reinsert a cache entry
dnsA({
{ name = "really.really.really.does.not.exist.thijsschreijer.nl", address = "1.2.3.4" },
})
sleep(2) -- wait for timer to re-resolve the record
count = count_indices(b)
-- 66%: 213 points
-- 33%: 106 points
assert.same({
["1.2.3.4:80"] = 213,
["[::1]:80"] = 106,
}, count)
end)
it("weight change SRV record, has no effect", function()
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
dnsSRV({
{ name = "gelato.io", target = "1.2.3.6", port = 8001, weight = 5 },
{ name = "gelato.io", target = "1.2.3.6", port = 8002, weight = 5 },
})
local b = balancer.new({
dns = client,
wheelSize = 1000,
})
b:addHost("mashape.com", 80, 10)
b:addHost("gelato.io", 80, 10) --> port + weight will be ignored
local count = count_indices(b)
local state = copyWheel(b)
-- 33%: 106 points
-- 16%: 53 points
assert.same({
["1.2.3.4:80"] = 106,
["1.2.3.5:80"] = 106,
["1.2.3.6:8001"] = 53,
["1.2.3.6:8002"] = 53,
}, count)
b:addHost("gelato.io", 80, 20) --> port + weight will be ignored
count = count_indices(b)
assert.same({
["1.2.3.4:80"] = 106,
["1.2.3.5:80"] = 106,
["1.2.3.6:8001"] = 53,
["1.2.3.6:8002"] = 53,
}, count)
assert.same(state, copyWheel(b))
end)
it("renewed DNS A record; no changes", function()
local record = dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
dnsA({
{ name = "getkong.org", address = "9.9.9.9" },
})
local b = balancer.new({
hosts = {
{ name = "mashape.com", port = 80, weight = 5 },
{ name = "getkong.org", port = 123, weight = 10 },
},
dns = client,
wheelSize = 100,
})
local state = copyWheel(b)
record.expire = gettime() -1 -- expire current dns cache record
dnsA({ -- create a new record (identical)
{ name = "mashape.com", address = "1.2.3.4" },
{ name = "mashape.com", address = "1.2.3.5" },
})
-- create a spy to check whether dns was queried
spy.on(client, "resolve")
-- call all, to make sure we hit the expired one
-- invoke balancer, to expire record and re-query dns
b:_hit_all()
assert.spy(client.resolve).was_called_with("mashape.com",nil, nil)
assert.same(state, copyWheel(b))
end)
it("renewed DNS AAAA record; no changes", function()
local record = dnsAAAA({
{ name = "mashape.com", address = "::1" },
{ name = "mashape.com", address = "::2" },
})
dnsA({
{ name = "getkong.org", address = "9.9.9.9" },
})
local b = balancer.new({
hosts = {
{ name = "mashape.com", port = 80, weight = 5 },
{ name = "getkong.org", port = 123, weight = 10 },
},
dns = client,
wheelSize = 100,
})
local state = copyWheel(b)
record.expire = gettime() -1 -- expire current dns cache record
dnsAAAA({ -- create a new record (identical)
{ name = "mashape.com", address = "::1" },
{ name = "mashape.com", address = "::2" },
})
-- create a spy to check whether dns was queried
spy.on(client, "resolve")
-- call all, to make sure we hit the expired one
-- invoke balancer, to expire record and re-query dns
b:_hit_all()
assert.spy(client.resolve).was_called_with("mashape.com",nil, nil)
assert.same(state, copyWheel(b))
end)
it("renewed DNS SRV record; no changes", function()
local record = dnsSRV({
{ name = "gelato.io", target = "1.2.3.6", port = 8001, weight = 5 },
{ name = "gelato.io", target = "1.2.3.6", port = 8002, weight = 5 },
{ name = "gelato.io", target = "1.2.3.6", port = 8003, weight = 5 },
})
dnsA({
{ name = "getkong.org", address = "9.9.9.9" },
})
local b = balancer.new({
hosts = {
{ name = "gelato.io" },
{ name = "getkong.org", port = 123, weight = 10 },
},
dns = client,
wheelSize = 100,
})
local state = copyWheel(b)
record.expire = gettime() -1 -- expire current dns cache record
dnsSRV({ -- create a new record (identical)
{ name = "gelato.io", target = "1.2.3.6", port = 8001, weight = 5 },
{ name = "gelato.io", target = "1.2.3.6", port = 8002, weight = 5 },
{ name = "gelato.io", target = "1.2.3.6", port = 8003, weight = 5 },
})
-- create a spy to check whether dns was queried
spy.on(client, "resolve")
-- call all, to make sure we hit the expired one
-- invoke balancer, to expire record and re-query dns
b:_hit_all()
assert.spy(client.resolve).was_called_with("gelato.io",nil, nil)
assert.same(state, copyWheel(b))
end)
it("low weight with zero-indices assigned doesn't fail", function()
-- depending on order of insertion it is either 1 or 0 indices
-- but it may never error.
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
})
dnsA({
{ name = "getkong.org", address = "9.9.9.9" },
})
balancer.new({
hosts = {
{ name = "mashape.com", port = 80, weight = 99999 },
{ name = "getkong.org", port = 123, weight = 1 },
},
dns = client,
wheelSize = 1000,
})
-- Now the order reversed (weights exchanged)
dnsA({
{ name = "mashape.com", address = "1.2.3.4" },
})
dnsA({
{ name = "getkong.org", address = "9.9.9.9" },
})
balancer.new({
hosts = {
{ name = "mashape.com", port = 80, weight = 1 },
{ name = "getkong.org", port = 123, weight = 99999 },
},
dns = client,
wheelSize = 1000,
})
end)
it("SRV record with 0 weight doesn't fail resolving", function()
-- depending on order of insertion it is either 1 or 0 indices
-- but it may never error.
dnsSRV({
{ name = "gelato.io", target = "1.2.3.6", port = 8001, weight = 0 },
{ name = "gelato.io", target = "1.2.3.6", port = 8002, weight = 0 },
})
local b = balancer.new({
hosts = {
-- port and weight will be overridden by the above
{ name = "gelato.io", port = 80, weight = 99999 },
},
dns = client,
wheelSize = 100,
})
local ip, port = b:getPeer(false, nil, "test")
assert.equal("1.2.3.6", ip)
assert(port == 8001 or port == 8002, "port expected 8001 or 8002")
end)
it("recreate Kong issue #2131", function()
-- erasing does not remove the address from the host
-- so if the same address is added again, and then deleted again
-- then upon erasing it will find the previous erased address object,
-- and upon erasing again a nil-referencing issue then occurs
local ttl = 1
local record
local hostname = "dnstest.mashape.com"
-- mock the resolve/toip methods
local old_resolve = client.resolve
local old_toip = client.toip
finally(function()
client.resolve = old_resolve
client.toip = old_toip
end)
client.resolve = function(name, ...)
if name == hostname then
record = dnsA({
{ name = hostname, address = "1.2.3.4", ttl = ttl },
})
return record
else
return old_resolve(name, ...)
end
end
client.toip = function(name, ...)
if name == hostname then
return "1.2.3.4", ...
else
return old_toip(name, ...)
end
end
-- create a new balancer
local b = balancer.new({
hosts = {
{ name = hostname, port = 80, weight = 50 },
},
dns = client,
wheelSize = 1000,
ttl0 = 1,
})
sleep(1.1) -- wait for ttl to expire
-- fetch a peer to reinvoke dns and update balancer, with a ttl=0
ttl = 0
b:getPeer(false, nil, "value") --> force update internal from A to SRV
sleep(1.1) -- wait for ttl0, as provided to balancer, to expire
-- restore ttl to non-0, and fetch a peer to update balancer
ttl = 1
b:getPeer(false, nil, "value") --> force update internal from SRV to A
sleep(1.1) -- wait for ttl to expire
-- fetch a peer to reinvoke dns and update balancer, with a ttl=0
ttl = 0
b:getPeer(false, nil, "value") --> force update internal from A to SRV
end)
end)
end)
|
--[[
TODO:
Only show speedometer if distance to road < 15 (play around with this threshold)
]]--
local currentVehicle = {}
local nodeBlip
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if (IsPlayerDrivingVehicle()) then
local playerCoords = GetEntityCoords(PlayerPedId())
local streetHash = GetStreetNameAtCoord(table.unpack(playerCoords))
local streetLimit = SpeedLimits[tostring(streetHash)]
local foundVehicleNode, closestNodeCoords = GetClosestVehicleNode(playerCoords.x, playerCoords.y, playerCoords.z, 0, 3.0)
local distanceToNode;
distanceToNode = GetDistanceBetweenCoords(
playerCoords.x, playerCoords.y, playerCoords.z,
closestNodeCoords.x, closestNodeCoords.y, closestNodeCoords.z
);
if (streetLimit and foundVehicleNode and distanceToNode <= 20) then
RenderHud(streetLimit)
end
Debug()
end
end
end)
function IsPlayerDrivingVehicle()
local isDriver = false
local isInVehicle = false
local ped = GetPlayerPed(-1)
local vehicle = {}
if (IsPedInAnyVehicle(ped)) then
isInVehicle = true
vehicle = GetVehiclePedIsIn(ped, false)
isDriver = GetPedInVehicleSeat(vehicle, -1) == ped
currentVehicle = vehicle
else
currentVehicle = {}
end
return isInVehicle and isDriver
end
function Debug()
RemoveBlip(nodeBlip)
local playerCoords = GetEntityCoords(PlayerPedId())
local vehicleCoords = GetEntityCoords(currentVehicle)
SetTextScale(0, 0.25)
SetTextDropShadow(1, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Player Coords:')
DrawText(0.005, 0.35)
SetTextScale(0, 0.25)
SetTextDropShadow(1, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('x: ' .. playerCoords.x .. ' y: ' .. playerCoords.y .. ' z: ' .. playerCoords.z)
DrawText(0.01, 0.375)
SetTextScale(0, 0.25)
SetTextDropShadow(1, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString(IsPointOnRoad(table.unpack(playerCoords)) and 'On Road' or 'Not On Road')
DrawText(0.01, 0.4)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Vehicle Coords:')
DrawText(0.005, 0.43)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('x: ' .. vehicleCoords.x .. ' y: ' .. vehicleCoords.y .. ' z: ' .. vehicleCoords.z)
DrawText(0.01, 0.455)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString(IsPointOnRoad(table.unpack(vehicleCoords)) and 'On Road' or 'Not On Road')
DrawText(0.01, 0.48)
local roadKey = GetStreetNameAtCoord(table.unpack(playerCoords))
local roadName = GetStreetNameFromHashKey(roadKey)
local _, roadCoords = GetClosestRoad(table.unpack(playerCoords), 1.0, 1)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Nearest Road:')
DrawText(0.005, 0.51)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString(roadName .. ' - ' .. roadKey)
DrawText(0.01, 0.535)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('x: ' .. roadCoords.x .. ' y: ' .. roadCoords.y .. ' z: ' .. roadCoords.z)
DrawText(0.01, 0.56)
local found, nodeCoords = GetClosestVehicleNode(playerCoords.x, playerCoords.y, playerCoords.z, 0, 3.0)
if (DoesBlipExist(nodeBlip)) then
SetBlipCoords(nodeBlip, table.unpack(nodeCoords))
else
nodeBlip = AddBlipForCoord(table.unpack(nodeCoords))
SetBlipSprite(nodeBlip, 524)
end
-- blip = AddBlipForCoord(table.unpack(nodeCoords))
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Nearest Vehicle Node:')
DrawText(0.005, 0.59)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Found? ' .. (found and 'Y' or 'N'))
DrawText(0.01, 0.615)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('x: ' .. nodeCoords.x .. ' y: ' .. nodeCoords.y .. ' z: ' .. nodeCoords.z)
DrawText(0.01, 0.64)
SetTextScale(0, 0.25)
SetTextDropShadow(0, 0, 0, 0, 255)
SetTextEntry("STRING")
AddTextComponentString('Distance From Player: ' .. GetDistanceBetweenCoords(
playerCoords.x, playerCoords.y, nodeCoords.z,
nodeCoords.x, nodeCoords.y, nodeCoords.z
))
DrawText(0.01, 0.665)
end
function RenderHud(limit)
SetTextCentre(true)
SetTextColour(0,0,0,255)
SetTextFont(2)
SetTextScale(0, 0.275)
SetTextEntry("STRING")
AddTextComponentString("SPEED")
DrawText(0.145, 0.921)
SetTextCentre(true)
SetTextColour(0, 0, 0, 255)
SetTextFont(2)
SetTextScale(0, 0.6)
SetTextEntry("STRING")
AddTextComponentString(limit)
DrawText(0.145, 0.9315)
DrawRect(
0.145,
0.945,
0.021,
0.0425,
255,
255,
255,
150
)
end
|
local path = (...):gsub(".init$", "") .. "."
require(path .. "cdef")
local M = require(path .. "master")
local ffi = require("ffi")
-- search for fmod shared libraries in package.cpath
local paths = {
fmod = package.searchpath("libfmod", package.cpath),
fmodstudio = package.searchpath("libfmodstudio", package.cpath)
}
assert(paths.fmod and paths.fmodstudio, "FMOD shared libraries not found!")
-- pretend to load libfmod through Lua (it's going to fail but not raise any errors)
-- so that its location is known when loading libfmodstudio through ffi
package.loadlib(paths.fmod, "")
M.C = ffi.load(paths.fmodstudio)
require(path .. "enums")
require(path .. "constants")
require(path .. "wrap")
require(path .. "errors")
return M
|
modifier_dire_zombie_rage_aura = class({})
function modifier_dire_zombie_rage_aura:OnCreated(params)
self.ms_buff_pct = self:GetAbility():GetSpecialValueFor("ms_buff_pct")
self.as_speed = self:GetAbility():GetSpecialValueFor("as_speed")
if IsServer() then
self.efx = EFX("particles/econ/items/lycan/ti9_immortal/lycan_ti9_immortal_howl_buff.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent(), {})
end
end
function modifier_dire_zombie_rage_aura:OnDestroy()
if IsServer() then
DEFX(self.efx, false)
end
end
function modifier_dire_zombie_rage_aura:DeclareFunctions()
return {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
end
function modifier_dire_zombie_rage_aura:GetModifierAttackSpeedBonus_Constant()
return self.as_speed
end
function modifier_dire_zombie_rage_aura:GetModifierMoveSpeedBonus_Percentage(params)
return self.ms_buff_pct
end
function modifier_dire_zombie_rage_aura:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("damage_bonus")
end
|
local SPUtil = require(game.ReplicatedStorage.Shared.SPUtil)
local CurveUtil = require(game.ReplicatedStorage.Shared.CurveUtil)
local NoteBase = require(game.ReplicatedStorage.Local.NoteBase)
local NoteResult = require(game.ReplicatedStorage.Shared.NoteResult)
local SFXManager = require(game.ReplicatedStorage.Local.SFXManager)
local DebugOut = require(game.ReplicatedStorage.Local.DebugOut)
local TriggerNoteEffect = require(game.ReplicatedStorage.Effects.TriggerNoteEffect)
local HoldingNoteEffect = require(game.ReplicatedStorage.Effects.HoldingNoteEffect)
local FlashEvery = require(game.ReplicatedStorage.Shared.FlashEvery)
local SPList = require(game.ReplicatedStorage.Shared.SPList)
local test = nil
local teest = nil
local test1 = 0.25
local test2 = 0.65
local test3 = 1.5
local NoteSize = 2
local leftID = nil
local upID = nil
local downID = nil
local rightID = nil
local ModManager = require(game.ReplicatedStorage.ModManager)
local _left = "rbxassetid://"
local _up = "rbxassetid://"
local _down = "rbxassetid://"
local _right = "rbxassetid://"
-- local BODY_WIDTH = 1.5
-- local BODY_LENGTH = 50
-- local HEAD_SIZE = 3
local HeldNote = {}
HeldNote.Type = "HeldNote"
HeldNote.State = {
Pre = 0;
Holding = 1;
HoldMissedActive = 2;
Passed = 3;
DoRemove = 4;
}
function HeldNote:new(
_game,
track_index,
slot_index,
creation_time_ms,
hit_time_ms,
duration_time_ms,
new_color,
snap_enabled,
id,
amods
)
if not amods then
amods = {}
end
--local amods = ModManager:GetActivatedMods()
local scrollmode = {Value=2}
local self = NoteBase:NoteBase()
self.id = id
self.Type = HeldNote.Type
local _note_obj = nil
local cur_color = new_color
local _body = nil
local _head = nil
local _tail = nil
local _head_outline = nil
local _head_decal = nil
local _tail_decal = nil
local _tail_outline = nil
local _body_outline_left = nil
local _body_outline_right = nil
local t_override = false
local _body_adorn, _head_adorn, _tail_adorn, _head_outline_adorn, _tail_outline_adorn, _body_outline_left_adorn, _body_outline_right_adorn, _body_2D_part
local snapped = snap_enabled
local _game_audio_manager_get_current_time_ms = 0
local _track_index = track_index
local _state = HeldNote.State.Pre
local _did_trigger_head = false
local _did_trigger_tail = false
local function is_local_slot()
return slot_index == _game:get_local_game_slot()
end
local __get_start_position = nil
local function get_start_position()
if __get_start_position == nil then
__get_start_position = _game:get_tracksystem(slot_index):get_track(track_index):get_start_position()
end
return __get_start_position
end
local __get_end_position = nil
local function get_end_position()
if __get_end_position == nil then
__get_end_position = _game:get_tracksystem(slot_index):get_track(track_index):get_end_position()
end
return __get_end_position
end
local function get_head_position()
return SPUtil:vec3_lerp(
get_start_position(),
get_end_position(),
(_game_audio_manager_get_current_time_ms - creation_time_ms) / (hit_time_ms - creation_time_ms)
)
end
local function get_tail_hit_time()
return hit_time_ms + duration_time_ms
end
local function tail_visible()
return not (get_tail_hit_time() > _game_audio_manager_get_current_time_ms + _game._audio_manager:get_note_prebuffer_time_ms())
end
local function get_tail_t()
local tail_show_time = _game_audio_manager_get_current_time_ms - get_tail_hit_time() + _game._audio_manager:get_note_prebuffer_time_ms()
return tail_show_time / _game._audio_manager:get_note_prebuffer_time_ms()
end
local function get_tail_position()
if not tail_visible() then
return get_start_position()
else
local tail_t = get_tail_t()
return SPUtil:vec3_lerp(
get_start_position(),
get_end_position(),
tail_t
)
end
end
local _i_update_visual = -1
local function update_visual(dt_scale)
if 2 == 1 then
test = test3
teest = test3
else
test = test1
teest = test2
end
local power_bar_active = _game._players._slots:get(slot_index)._power_bar_active
local head_pos = get_head_position()
local tail_pos = get_tail_position()
_head.CFrame = CFrame.new(head_pos) * CFrame.Angles(0, math.rad(90), 0)
_tail.CFrame = CFrame.new(tail_pos) * CFrame.Angles(0, math.rad(90), 0)
--_head_adorn.CFrame = CFrame.new(_head.CFrame:vectorToObjectSpace(head_pos)) + Vector3.new(0,-0.35,0)
--_tail_adorn.CFrame = CFrame.new(_tail.CFrame:vectorToObjectSpace(tail_pos)) + Vector3.new(0,-0.35,0)
_head_outline_adorn.CFrame = CFrame.new(_head_outline.CFrame:vectorToObjectSpace(head_pos + Vector3.new(0,-0.65)))
_tail_outline_adorn.CFrame = CFrame.new(_tail_outline.CFrame:vectorToObjectSpace(tail_pos + Vector3.new(0,-0.65)))
if _did_trigger_head then
if _game_audio_manager_get_current_time_ms > hit_time_ms then
head_pos = get_end_position()
end
end
local tail_to_head = head_pos - tail_pos
if _state == HeldNote.State.Pre then
_head_adorn.Transparency = 0
_head_outline_adorn.Transparency = 0
else
_head_adorn.Transparency = 1
_head_outline_adorn.Transparency = 1
end
if _state == HeldNote.State.Passed and _did_trigger_tail then
_tail_adorn.Transparency = 1
_tail_outline_adorn.Transparency = 1
_body_2D_part.Transparency = 1
else
if tail_visible() then
_tail_adorn.Transparency = 0
_tail_outline_adorn.Transparency = 0
else
_tail_adorn.Transparency = 1
_body_2D_part.Transparency = 1
_tail_outline_adorn.Transparency = 1
end
end
local head_t = (_game_audio_manager_get_current_time_ms - creation_time_ms) / (hit_time_ms - creation_time_ms)
for i, mod in pairs(amods) do
if mod.UpdateHeldNote then
local p = mod:UpdateHeldNote({
HeadAlpha=head_t;
TailAlpha=get_tail_t();
Track=_track_index;
OriginalColor=new_color;
CurrentColor=cur_color;
HeadPosition=head_pos;
HeadSize=_head.Size;
Id=id
})
if p ~= nil then
if p.color then
cur_color=p.color
end
if p.visible ~= nil then
if p.visible == false then
_body_adorn.Transparency = 1
end
end
if p.transparency then
t_override = true
_body_outline_left_adorn.Transparency = p.transparency
_body_outline_right_adorn.Transparency = p.transparency
_body_2D_part.Transparency = p.transparency
_body_adorn.Transparency = p.transparency
_head_adorn.Transparency = p.transparency
if _head_decal then
_head_decal.Transparency = p.transparency
end
_head_outline.Transparency = p.transparency
if _tail_decal then
_tail_decal.Transparency = p.transparency
end
_tail_adorn.Transparency = p.transparency
_tail_outline.Transparency = p.transparency
_tail_outline_adorn.Transparency = p.transparency
end
if p.h_transparency then
t_override = true
_head_adorn.Transparency = p.h_transparency
if _head_decal then
_head_decal.Transparency = p.h_transparency
end
_head_outline.Transparency = p.h_transparency
end
if p.t_transparency then
t_override = true
if _tail_decal then
_tail_decal.Transparency = p.t_transparency
end
_tail_adorn.Transparency = p.t_transparency
_tail_outline.Transparency = p.t_transparency
_tail_outline_adorn.Transparency = p.t_transparency
end
if p.b_transparency then
t_override = true
_body_outline_left_adorn.Transparency = p.b_transparency
_body_outline_right_adorn.Transparency = p.b_transparency
_body_2D_part.Transparency = p.b_transparency
_body_adorn.Transparency = p.b_transparency
end
end
end
end
do
_note_obj.Body:SetPrimaryPartCFrame(
CFrame.Angles(0, SPUtil:deg_to_rad(SPUtil:dir_ang_deg(tail_to_head.x,-tail_to_head.z) + 90), 0)
)
local body_pos = (tail_to_head * 0.5) + tail_pos
local body_size = CurveUtil:YForPointOf2PtLine(
Vector2.new(0,test),
Vector2.new(1,teest),
SPUtil:clamp(head_t,0,1)
)
if scrollmode.Value == 1 then
if _head_decal then _head_decal.Color3 = cur_color end
if _body_2D_part then _body_2D_part.Color = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75) end
if _tail_decal then _tail_decal.Color3 = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75) end
_body_2D_part.CFrame = CFrame.new(body_pos) * CFrame.Angles(0,math.rad(-45),0)
_body_2D_part.Size = Vector3.new(3.2, 0.05, tail_to_head.magnitude)
if not t_override then
_body_2D_part.Transparency = 0
end
_body_adorn.Transparency = 1
else
_body_adorn.CFrame = CFrame.new(_body.CFrame:vectorToObjectSpace(body_pos) + Vector3.new(0,-0.35,0))
end
local body_radius = body_size
_body_adorn.Height = tail_to_head.magnitude
_body_adorn.Radius = body_radius
_body_adorn.Color3 = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75)
_tail_adorn.Color3 = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75)
_head_adorn.Color3 = cur_color
_body_outline_left_adorn.CFrame = CFrame.new(_body_outline_left.CFrame:vectorToObjectSpace(
body_pos
) + Vector3.new(-body_radius * 1.15,0,0))
_body_outline_right_adorn.CFrame = CFrame.new(_body_outline_right.CFrame:vectorToObjectSpace(
body_pos
) + Vector3.new(body_radius * 1.15,0,0))
_body_outline_left_adorn.Height = _body_adorn.Height
_body_outline_right_adorn.Height = _body_adorn.Height
_body_outline_left_adorn.Radius = body_size * 0.1
_body_outline_right_adorn.Radius = body_size * 0.1
end
do
local head_size = CurveUtil:YForPointOf2PtLine(
Vector2.new(0,1.15 / 3.0),
Vector2.new(1,2.55 / 3.0),
SPUtil:clamp(head_t,0,1)
)
local tail_size = CurveUtil:YForPointOf2PtLine(
Vector2.new(0,1.15 / 3.0),
Vector2.new(1,2.55 / 3.0),
SPUtil:clamp(get_tail_t(),0,1)
)
if scrollmode.Value == 1 then
_head_adorn.Transparency = 1
_tail_adorn.Transparency = 1
_head_outline_adorn.Transparency = 1
_body_outline_left_adorn.Transparency = 1
_body_outline_right_adorn.Transparency = 1
_tail_outline_adorn.Transparency = 1
_head_outline_adorn.Transparency = 1
else
_head_adorn.Radius = 1.450 * head_size
_tail_adorn.Radius = 1.450 * tail_size
_head_outline_adorn.Radius = 1.65 * head_size
_tail_outline_adorn.Radius = 1.65 * tail_size
end
end
_i_update_visual = _i_update_visual + 1
if _i_update_visual > 3 then
_i_update_visual = 0
end
local target_transparency = 0
local imm = false
if _state == HeldNote.State.HoldMissedActive then
target_transparency = 0
_body_outline_left_adorn.Transparency = 1
_body_outline_right_adorn.Transparency = 1
_head.Decal.Transparency = 1
elseif _state == HeldNote.State.Passed and _did_trigger_tail then
target_transparency = 1
imm = true
_body_outline_left_adorn.Transparency = 1
_body_outline_right_adorn.Transparency = 1
_body_2D_part.Transparency = 1
_head.Decal.Transparency = 1
else
target_transparency = 0.2
if t_override then
return
end
end
if imm and scrollmode.Value ~= 1 then
_body_adorn.Transparency = target_transparency
elseif scrollmode.Value ~= 1 then
_body_adorn.Transparency = target_transparency
end
end
local _beat_trigger_index = 1
local _beat_triggers_at = SPList:new()
function self:cons()
_game_audio_manager_get_current_time_ms = _game._audio_manager:get_current_time_ms()
_note_obj = _game._object_pool:depool(self.Type)
if _note_obj == nil then
_note_obj = _game:get_game_protos().HeldNoteAdornProto:Clone()
_note_obj.Body:SetPrimaryPartCFrame(CFrame.new(Vector3.new()) * SPUtil:part_cframe_rotation(_note_obj.Body.PrimaryPart))
_note_obj.Body.BodyOutlineLeft.CFrame = _note_obj.Body.PrimaryPart.CFrame
_note_obj.Body.BodyOutlineRight.CFrame = _note_obj.Body.PrimaryPart.CFrame
_note_obj.Head:SetPrimaryPartCFrame(CFrame.new(Vector3.new()) * SPUtil:part_cframe_rotation(_note_obj.Head.PrimaryPart))
_note_obj.Tail:SetPrimaryPartCFrame(CFrame.new(Vector3.new()) * SPUtil:part_cframe_rotation(_note_obj.Tail.PrimaryPart))
_note_obj.Head.Head.Decal.Color3 = Color3.new(1,1,1)
end
_body = _note_obj.Body.Body
_body_adorn = _body.Adorn
_head = _note_obj.Head.Head
_head_adorn = _head.Adorn
_body_2D_part = _body["2D"]
_tail = _note_obj.Tail.Tail
_tail_adorn = _tail.Adorn
_head_outline = _note_obj.Head.HeadOutline
_head_outline_adorn = _head_outline.Adorn
_tail_outline = _note_obj.Tail.TailOutline
_tail_outline_adorn = _tail_outline.Adorn
_body_outline_left = _note_obj.Body.BodyOutlineLeft
_body_outline_left_adorn = _body_outline_left.Adorn
_body_outline_right = _note_obj.Body.BodyOutlineRight
_body_outline_right_adorn = _body_outline_right.Adorn
_head_adorn.Color3 = cur_color
if snapped then
_body_adorn.Color3 = Color3.new(0.4,0.4,0.4)
_tail_adorn.Color3 = Color3.new(0.4,0.4,0.4)
else
_body_adorn.Color3 = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75)
_tail_adorn.Color3 = Color3.new(cur_color.r/1.75,cur_color.g/1.75,cur_color.b/1.75)
end
if scrollmode.Value == 1 then
_tail_outline_adorn.Transparency = 1
_head_outline_adorn.Transparency = 1
_body_outline_left_adorn.Transparency = 1
_body_outline_right_adorn.Transparency = 1
_body_adorn.Transparency = 1
else
_tail_outline_adorn.Color3 = Color3.new(0,0,0)
_head_outline_adorn.Color3 = Color3.new(0,0,0)
_body_outline_left_adorn.Color3 = Color3.new(0,0,0)
_body_outline_right_adorn.Color3 = Color3.new(0,0,0)
end
_state = HeldNote.State.Pre
update_visual(1)
_note_obj.Parent = _game:get_game_element()
do
_beat_trigger_index = 1
_beat_triggers_at:clear()
local beat_trigger_incr = _game._audio_manager:get_beat_duration() * 0.5
for i=beat_trigger_incr,duration_time_ms,beat_trigger_incr do
if i + beat_trigger_incr <= duration_time_ms then
_beat_triggers_at:push_back(
hit_time_ms + i
)
end
end
end
if scrollmode.Value == 1 then
_head_decal = _head.Decal
_body_adorn.Transparency = 1
_tail_decal = _tail.Decal
_head_adorn.Transparency = 1
_tail_adorn.Transparency = 1
_head_adorn.Transparency = 1
if _track_index == 1 then
_head.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_tail.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_left = "rbxassetid://" .. leftID.Value
_head_decal.Texture = _left
_head_decal.Transparency = 0
_tail_decal.Texture = _left
_tail_decal.Transparency = 1
elseif _track_index == 2 then
_head.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_tail.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_up = "rbxassetid://" .. upID.Value
_head_decal.Texture = _up
_head_decal.Transparency = 0
_tail_decal.Texture = _up
_tail_decal.Transparency = 1
elseif _track_index == 3 then
_head.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_tail.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_down = "rbxassetid://" .. downID.Value
_head_decal.Texture = _down
_head_decal.Transparency = 0
_tail_decal.Texture = _down
_tail_decal.Transparency = 1
elseif _track_index == 4 then
_head.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_tail.Size = Vector3.new(NoteSize.Value / 100 ,0.05, NoteSize.Value / 100)
_right = "rbxassetid://" .. rightID.Value
_head_decal.Texture = _right
_head_decal.Transparency = 0
_tail_decal.Texture = _right
_tail_decal.Transparency = 1
end
end
end
local function update_beat(_game)
if is_local_slot() == false then
return
end
local cur_time = _game_audio_manager_get_current_time_ms
for i=_beat_trigger_index,_beat_triggers_at:count() do
local trigger_time = _beat_triggers_at:get(i)
if cur_time + 5 >= trigger_time then
if _state == HeldNote.State.Holding then
_game._world_effect_manager:notify_hold_tick(_game,slot_index,track_index)
end
_beat_trigger_index = _beat_trigger_index + 1
else
break
end
end
end
local _hold_flash = FlashEvery:new(0.15)
_hold_flash:flash_now()
local _dt_scale_sum = 0
local _has_notified_held_note_begin = false
--[[Override--]] function self:update(dt_scale, _game)
SPUtil:profilebegin("HeldNote:update")
_game_audio_manager_get_current_time_ms = _game._audio_manager:get_current_time_ms()
SPUtil:profilebegin("HeldNote:visual_update")
if slot_index == _game:get_local_game_slot() then
update_visual(dt_scale)
else
_dt_scale_sum = _dt_scale_sum + dt_scale
if _game:get_frame_count() % 4 == (slot_index - 1) % 4 then
update_visual(_dt_scale_sum)
_dt_scale_sum = 0
end
end
SPUtil:profileend()
update_beat(_game)
if _has_notified_held_note_begin == false then
if hit_time_ms < _game_audio_manager_get_current_time_ms then
_game._audio_manager:notify_held_note_begin(hit_time_ms)
_has_notified_held_note_begin = true
end
end
if _state == HeldNote.State.Holding then
_game._world_effect_manager:notify_frame_hold(_game,slot_index,track_index)
end
if _state == HeldNote.State.Pre then
if _game_audio_manager_get_current_time_ms > (hit_time_ms - _game._audio_manager.NOTE_REMOVE_TIME) then
_game._score_manager:register_hit(
_game,
NoteResult.Miss,
slot_index,
_track_index,
{ PlaySFX = false; PlayHoldEffect = false; TimeMiss = true; }
)
if is_local_slot() then
_game._effects:add_effect(HoldingNoteEffect:new(
_game,
get_head_position(),
NoteResult.Okay
))
end
_state = HeldNote.State.HoldMissedActive
end
elseif _state == HeldNote.State.Holding or
_state == HeldNote.State.HoldMissedActive or
_state == HeldNote.State.Passed then
if _state == HeldNote.State.Holding then
_hold_flash:update(dt_scale)
if _hold_flash:do_flash() then
if is_local_slot() then
_game._effects:add_effect(HoldingNoteEffect:new(
_game,
_game:get_tracksystem(slot_index):get_track(track_index):get_end_position(),
NoteResult.Perfect
))
end
end
end
if _game_audio_manager_get_current_time_ms > (get_tail_hit_time() - _game._audio_manager.NOTE_REMOVE_TIME) then
if _state == HeldNote.State.Holding or
_state == HeldNote.State.HoldMissedActive then
if is_local_slot() then
_game._effects:add_effect(HoldingNoteEffect:new(
_game,
get_tail_position(),
NoteResult.Okay
))
end
_game._score_manager:register_hit(
_game,
NoteResult.Miss,
slot_index,
_track_index,
{ PlaySFX = false; PlayHoldEffect = false; TimeMiss = true; }
)
end
_state = HeldNote.State.DoRemove
end
end
SPUtil:profileend()
end
--[[Override--]] function self:should_remove(_game)
return _state == HeldNote.State.DoRemove
end
--[[Override--]] function self:do_remove(_game)
_game._object_pool:repool(self.Type,_note_obj)
_note_obj = nil
end
--[[Override--]] function self:test_hit(_game)
if _state == HeldNote.State.Pre then
local time_to_end = _game_audio_manager_get_current_time_ms - hit_time_ms
local did_hit, note_result = NoteResult:timedelta_to_result(time_to_end, _game)
if did_hit then
return did_hit, note_result
end
return false, NoteResult.Miss
elseif _state == HeldNote.State.HoldMissedActive then
local time_to_end = _game_audio_manager_get_current_time_ms - get_tail_hit_time()
local did_hit, note_result = NoteResult:timedelta_to_result(time_to_end, _game)
if did_hit then
return did_hit, note_result
end
return false, NoteResult.Miss
end
return false, NoteResult.Miss
end
--[[Override--]] function self:on_hit(_game,note_result,i_notes)
print("Holding...")
if _state == HeldNote.State.Pre then
--[[_game._effects:add_effect(TriggerNoteEffect:new(
_game,
get_head_position(),
note_result,
is_local_slot()
))]]
_game._score_manager:register_hit(
_game, note_result, slot_index, _track_index, { PlaySFX = true; PlayHoldEffect = false; IsHeldNoteBegin = true; },
_game_audio_manager_get_current_time_ms - hit_time_ms
)
_did_trigger_head = true
_state = HeldNote.State.Holding
if scrollmode.Value == 1 then
_head_decal.Transparency = 1
end
elseif _state == HeldNote.State.HoldMissedActive then
--[[_game._effects:add_effect(TriggerNoteEffect:new(
_game,
get_tail_position(),
note_result
))]]
_game._score_manager:register_hit(
_game,
note_result,
slot_index,
_track_index,
{ PlaySFX = true; PlayHoldEffect = true; HoldEffectPosition = get_tail_position() },
500
)
_did_trigger_tail = true
if scrollmode.Value == 1 then
_tail_decal.Transparency = 1
end
_state = HeldNote.State.Passed
end
if not _game.is_spectating then
_game._hit_cache:addToCache(
_game._hit_cache:genNewHit(_game._audio_manager:get_current_time_ms(), track_index, "Press", note_result, self.id)
)
end
end
--[[Override--]] function self:test_release(_game)
print("Releasing...")
if _state == HeldNote.State.Holding or _state == HeldNote.State.HoldMissedActive then
local time_to_end = _game_audio_manager_get_current_time_ms - get_tail_hit_time()
local did_hit, note_result = NoteResult:release_timedelta_to_result(time_to_end, _game)
if did_hit then
return did_hit, note_result
end
if _state == HeldNote.State.HoldMissedActive then
return false, NoteResult.Miss
else
return true, NoteResult.Miss
end
end
return false, NoteResult.Miss
end
--[[Override--]] function self:on_release(_game,note_result,i_notes)
if _state == HeldNote.State.Holding or _state == HeldNote.State.HoldMissedActive then
if note_result == NoteResult.Miss then
_game._score_manager:register_hit(
_game, note_result, slot_index, _track_index, { PlaySFX = true; PlayHoldEffect = false; },
get_tail_hit_time() - _game._audio_manager.NOTE_REMOVE_TIME
)
_state = HeldNote.State.HoldMissedActive
else
--[[_game._effects:add_effect(TriggerNoteEffect:new(
_game,
get_tail_position(),
note_result,
is_local_slot()
))]]
_game._score_manager:register_hit(
_game,
note_result,
slot_index,
_track_index,
{ PlaySFX = true; PlayHoldEffect = true; HoldEffectPosition = get_tail_position(); },
hit_time_ms - _game._audio_manager.NOTE_REMOVE_TIME
)
_did_trigger_tail = true
_state = HeldNote.State.Passed
end
if scrollmode.Value == 1 then
_tail_decal.Transparency = 1
end
end
if not _game.is_spectating then
print("Adding hold release to local cache...")
_game._hit_cache:addToCache(
_game._hit_cache:genNewHit(_game._audio_manager:get_current_time_ms(), track_index, "Release", note_result, self.id)
)
end
end
--[[Override--]] function self:get_track_index(_game)
return _track_index
end
self:cons()
return self
end
return HeldNote
|
return {'bob','bob','bobbaan','bobbel','bobbelen','bobbelig','bobbeling','bobben','bobber','bobberen','bobby','bobijn','bobijnen','bobijnklos','bobine','bobo','bobslee','bobsleebaan','bobsleebond','bobsleeen','bobsleeer','bobtail','bobbelgum','bobijnhouder','bobsleeploeg','bobbed','bob','bobbi','bobbie','bobby','bobbink','bobbelde','bobbelden','bobbelige','bobbeliger','bobbelingen','bobbels','bobbelt','bobbeltje','bobbeltjes','bobbers','bobbys','bobde','bobijntje','bobijntjes','bobos','bobt','bobsleeers','bobijnde','bobijnklossen','bobs','bobsleede','bobijnhouders','bobines','bobtails','bobs','bobbis','bobbies','bobbys'}
|
local modem = peripheral.wrap("back")
local ch = 50002
modem.open(ch)
local function send(msg)
modem.transmit(ch-1, ch, msg)
end
local function input()
while true do
local event, key, held = os.pullEvent("key")
if key == keys.up then send("^")
elseif key == keys.down then send("v")
elseif key == keys.left then send("<")
elseif key == keys.right then send(">")
elseif key == keys.w then send("up")
elseif key == keys.s then send("down")
elseif key == keys.leftCtrl or key == keys.rightCtrl then send("atk")
elseif key == keys.leftShift or key == keys.rightShift then send("refuel")
end
end
end
local function log()
while true do
local event, side, _ch, replyCh, msg, dist = os.pullEvent("modem_message")
print(msg)
end
end
parallel.waitForAll(
input,
log
)
|
-- perf
local tconcat = table.concat
local PostgreSqlHelpers = {}
-- build location execute name
function PostgreSqlHelpers.location_for(options)
name = {
'gin',
options.adapter,
options.host,
options.port,
options.database,
}
return tconcat(name, '|')
end
function PostgreSqlHelpers.execute_location_for(options)
name = {
PostgreSqlHelpers.location_for(options),
'execute'
}
return tconcat(name, '|')
end
return PostgreSqlHelpers
|
local number_lerp = assert(foundation.com.number_lerp)
yatm.thermal = yatm.thermal or {}
function yatm.thermal.set_heat(meta, name, amount)
meta:set_float(name, amount)
end
function yatm.thermal.get_heat(meta, name)
return meta:get_float(name)
end
function yatm.thermal.update_heat(meta, name, target_heat, amt, dtime)
local available_heat = yatm.thermal.get_heat(meta, name)
--local delta = amt * dtime
local new_heat = number_lerp(available_heat, target_heat, dtime)
yatm.thermal.set_heat(meta, name, new_heat)
--print("update_heat", "target=" .. target_heat, "amt=" .. amt, "dtime=" .. dtime, "delta=" .. delta, "old_heat=" .. available_heat, "new_heat=" .. new_heat)
return new_heat ~= available_heat
end
|
-- HUD showing player health and name if player is near and visible.
function GM:HUDDrawTargetID()
for k,v in pairs(self:GetActivePlayers()) do
if v == LocalPlayer() then continue end
local distance = self:VecDistance(LocalPlayer():GetPos(), v:GetPos())
if v:Alive() and distance < 600 then
local bone = v:LookupBone("ValveBiped.Bip01_Head1")
if type(bone) != "number" then continue end
local vec, ang = v:GetBonePosition(bone)
local tracedata = {}
tracedata.start = LocalPlayer():GetShootPos()
tracedata.endpos = vec
tracedata.filter = LocalPlayer()
local trace = util.TraceLine(tracedata)
if !trace.HitNonWorld or trace.Entity != v then continue end
local text = v:Nick()
local font = "DR_HudTargetID"
surface.SetFont( font )
local w, h = surface.GetTextSize( text )
vec:Add(Vector(0,0,20))
local TC = vec:ToScreen()
local x = TC.x
local y = TC.y
local alpha = 255
if distance > 345 then
alpha = 255-(distance-345)
end
draw.SimpleTextOutlined( text, font, x, y-3, Color(255,255,255,alpha), TEXT_ALIGN_CENTER,TEXT_ALIGN_CENTER, 1, Color(0,0,0,alpha))
draw.RoundedBox(4, x-31, y+h/2-1, 62, 10, Color(0,0,0,alpha))
draw.RoundedBox(4, x-30, y+h/2, math.max(8,math.Clamp(v:Health(), 0, 100)/100*60), 8, Color(255,0,0,alpha))
end
end
end
|
local config = require 'conf'
if config.development then
serialise = require 'src.development.Serialise'
end
MOUSE = require 'src.utils.Mouse'
KEYS = require 'src.utils.Keys'
ASSETS = require 'src.utils.Assets'
SHADERS = require 'src.utils.Shaders'
-- Modifying from: https://bitbucket.org/rude/love/src/default/src/scripts/boot.lua#lines-578:619
function love.run()
if love.load then
love.load(love.arg.parseGameArguments(arg), arg)
end
if love.timer then
love.timer.step()
end
local dt = 0
return function()
if love.event then
love.event.pump()
for name, a, b, c, d, e, f in love.event.poll() do
if name == 'quit' then
if not love.quit or not love.quit() then
return a or 0
end
end
love.handlers[name](a, b, c, d, e, f)
end
end
if love.timer then
dt = dt + love.timer.step()
end
if love.update then
while dt > 1 / config.tps do
love.update()
MOUSE.updateValues()
KEYS.updateRecentPressed()
dt = dt - (1 / config.tps)
end
end
if love.graphics and love.graphics.isActive() then
love.graphics.origin()
love.graphics.clear(love.graphics.getBackgroundColor())
if love.draw then
love.draw(dt * config.tps)
end
love.graphics.present()
end
if love.timer then
love.timer.sleep(0.001)
end
end
end
|
--[[
A loosely based Material UI module
mui-switch.lua : This is for creating simple toggle switches.
The MIT License (MIT)
Copyright (C) 2016 Anedix Technologies, Inc. All Rights Reserved.
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.
For other software and binaries included in this module see their licenses.
The license and the software must remain in full when copying or distributing.
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.
--]]--
-- mui
local muiData = require( "materialui.mui-data" )
local mathFloor = math.floor
local mathMod = math.fmod
local mathABS = math.abs
local M = muiData.M -- {} -- for module array/table
function M.createToggleSwitch(options)
M.newToggleSwitch(options)
end
function M.newToggleSwitch(options)
if options == nil then return end
local x,y = 160, 240
if options.x ~= nil then
x = options.x
end
if options.y ~= nil then
y = options.y
end
if options.width == nil then
options.width = options.size
end
if options.height == nil then
options.height = options.size
end
local textColorOff = { 1, 1, 1 }
if options.textColorOff ~= nil then
textColorOff = options.textColorOff
end
local textColor = { 1, 1, 1 }
if options.textColor ~= nil then
textColor = options.textColor
end
if options.backgroundColor == nil then
options.backgroundColor = { 0, 0, 1, 0, 0.8 }
end
local isChecked = false
if options.isChecked ~= nil then
isChecked = options.isChecked
end
muiData.widgetDict[options.name] = {}
muiData.widgetDict[options.name]["options"] = options
muiData.widgetDict[options.name]["isChecked"] = isChecked
muiData.widgetDict[options.name].name = options.name
muiData.widgetDict[options.name]["type"] = "ToggleSwitch"
muiData.widgetDict[options.name]["mygroup"] = display.newGroup()
muiData.widgetDict[options.name]["mygroup"]:translate( x, y )
muiData.widgetDict[options.name]["touching"] = false
if options.callBack ~= nil then
muiData.widgetDict[options.name]["callBack"] = options.callBack
end
if options.scrollView ~= nil then
muiData.widgetDict[options.name]["scrollView"] = options.scrollView
muiData.widgetDict[options.name]["scrollView"]:insert( muiData.widgetDict[options.name]["mygroup"] )
end
if options.parent ~= nil then
muiData.widgetDict[options.name]["parent"] = options.parent
muiData.widgetDict[options.name]["parent"]:insert( muiData.widgetDict[options.name]["mygroup"] )
end
local radius = options.height
x = 0
y = 0
muiData.widgetDict[options.name]["mygroup"]["rectmaster"] = display.newRect( x, y, options.width * 1.3, (options.height * 0.75))
muiData.widgetDict[options.name]["mygroup"]["rectmaster"].strokeWidth = 0
muiData.widgetDict[options.name]["mygroup"]["rectmaster"]:setStrokeColor( unpack({1, 0, 0, 1}) )
muiData.widgetDict[options.name]["mygroup"]["rect"] = display.newRect( x, y, options.width * 0.5, options.height * 0.5)
muiData.widgetDict[options.name]["mygroup"]["rect"].strokeWidth = 0
muiData.widgetDict[options.name]["mygroup"]["rect"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[options.name]["mygroup"]["circle1"] = display.newCircle( x - (radius * 0.20), y, radius * 0.25 )
muiData.widgetDict[options.name]["mygroup"]["circle1"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[options.name]["mygroup"]["circle2"] = display.newCircle( x + (radius * 0.20), y, radius * 0.25 )
muiData.widgetDict[options.name]["mygroup"]["circle2"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[options.name]["mygroup"]["circle"] = display.newCircle( x - (radius * 0.25), y, radius * 0.30 )
muiData.widgetDict[options.name]["mygroup"]["circle"]:setFillColor( unpack(options.textColorOff) )
muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["mygroup"]["rectmaster"])
muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["mygroup"]["rect"])
muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["mygroup"]["circle1"])
muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["mygroup"]["circle2"])
muiData.widgetDict[options.name]["mygroup"]:insert(muiData.widgetDict[options.name]["mygroup"]["circle"])
muiData.widgetDict[options.name]["mygroup"]["circle"].name = options.name
M.flipSwitch(options.name, 0)
local rect = muiData.widgetDict[options.name]["mygroup"]["rectmaster"]
rect.muiOptions = options
muiData.widgetDict[options.name]["mygroup"]["rectmaster"]:addEventListener( "touch", M.toggleSwitchTouch )
end
function M.getToggleSwitchProperty(widgetName, propertyName)
local data = nil
if widgetName == nil or propertyName == nil then return data end
if propertyName == "object" then
data = muiData.widgetDict[widgetName]["mygroup"] -- x,y movement
elseif propertyName == "value" then
data = muiData.widgetDict[widgetName]["value"] -- clickable area
elseif propertyName == "layer_1" then
data = muiData.widgetDict[widgetName]["rectmaster"] -- clickable area
elseif propertyName == "layer_2" then
data = muiData.widgetDict[widgetName]["rect"] -- middle area center
elseif propertyName == "layer_3" then
data = muiData.widgetDict[widgetName]["circle1"] -- circle area left
elseif propertyName == "layer_4" then
data = muiData.widgetDict[widgetName]["circle2"] -- circle area right
elseif propertyName == "layer_5" then
data = muiData.widgetDict[widgetName]["circle"] -- circle for moving within switch
end
return data
end
function M.toggleSwitchTouch (event)
local options = nil
if event.target ~= nil then
options = event.target.muiOptions
end
if muiData.dialogInUse == true and options.dialogName ~= nil then return end
M.addBaseEventParameters(event, options)
if ( event.phase == "began" ) then
muiData.interceptEventHandler = M.toggleSwitchTouch
if muiData.interceptOptions == nil then
muiData.interceptOptions = options
end
M.updateUI(event)
if muiData.touching == false and false then
muiData.touching = true
if options.touchpoint ~= nil and options.touchpoint == true then
muiData.widgetDict[options.basename]["radio"][options.name]["myCircle"].x = event.x - muiData.widgetDict[options.basename]["radio"][options.name]["mygroup"].x
muiData.widgetDict[options.basename]["radio"][options.name]["myCircle"].y = event.y - muiData.widgetDict[options.basename]["radio"][options.name]["mygroup"].y
end
transition.to(event.target,{time=500, xScale=1.03, yScale=1.03, transition=easing.continuousLoop})
end
elseif ( event.phase == "ended" ) then
if M.isTouchPointOutOfRange( event ) then
event.phase = "offTarget"
-- event.target:dispatchEvent(event)
-- print("Its out of the button area")
else
event.phase = "onTarget"
if muiData.interceptMoved == false then
event.target = muiData.widgetDict[options.name]["rect"]
if muiData.widgetDict[options.name]["isChecked"] == true then
muiData.widgetDict[options.name]["isChecked"] = false
M.setEventParameter(event, "muiTargetValue", nil)
else
muiData.widgetDict[options.name]["isChecked"] = true
M.setEventParameter(event, "muiTargetValue", options.value)
muiData.widgetDict[options.name]["value"] = options.value
end
M.setEventParameter(event, "muiTargetChecked", muiData.widgetDict[options.name]["isChecked"])
M.flipSwitch(options.name, nil)
M.setEventParameter(event, "muiTarget", muiData.widgetDict[options.name]["rect"])
event.callBackData = options.callBackData
assert( options.callBack )(event)
end
muiData.interceptEventHandler = nil
muiData.interceptOptions = nil
muiData.interceptMoved = false
muiData.touching = false
end
end
end
function M.flipSwitch(widgetName, delay)
if widgetName == nil then return end
if delay == nil then delay = 250 end
local isChecked = muiData.widgetDict[widgetName]["isChecked"]
local xR = muiData.widgetDict[widgetName]["mygroup"]["rect"].contentWidth * 0.75
local x = xR
if isChecked == false then
x = x - (xR * 2)
end
if isChecked == true then
transition.to( muiData.widgetDict[widgetName]["mygroup"]["circle"], { time=delay, x=x, onComplete=M.turnOnSwitch } )
else
transition.to( muiData.widgetDict[widgetName]["mygroup"]["circle"], { time=delay, x=x, onComplete=M.turnOffSwitch } )
end
end
function M.turnOnSwitch(e)
local options = muiData.widgetDict[e.name].options
e:setFillColor( unpack(options.textColor) )
muiData.widgetDict[e.name]["mygroup"]["rect"]:setFillColor( unpack(options.backgroundColor) )
muiData.widgetDict[e.name]["mygroup"]["circle1"]:setFillColor( unpack(options.backgroundColor) )
muiData.widgetDict[e.name]["mygroup"]["circle2"]:setFillColor( unpack(options.backgroundColor) )
muiData.widgetDict[e.name]["isChecked"] = true
end
function M.turnOffSwitch(e)
local options = muiData.widgetDict[e.name].options
e:setFillColor( unpack(options.textColorOff) )
muiData.widgetDict[e.name]["mygroup"]["rect"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[e.name]["mygroup"]["circle1"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[e.name]["mygroup"]["circle2"]:setFillColor( unpack(options.backgroundColorOff) )
muiData.widgetDict[e.name]["isChecked"] = false
end
function M.actionForSwitch(event)
local muiTarget = M.getEventParameter(event, "muiTarget")
local muiTargetValue = M.getEventParameter(event, "muiTargetValue")
local muiTargetChecked = M.getEventParameter(event, "muiTargetChecked")
if muiTargetValue ~= nil then
print("toggle switch value: " .. muiTargetValue)
end
if muiTargetChecked == nil then muiTargetChecked = false end
if muiTargetChecked == true then
print("toggle switch on")
else
print("toggle switch off")
end
end
function M.removeWidgetToggleSwitch(widgetName)
M.removeToggleSwitch(widgetName)
end
function M.removeToggleSwitch(widgetName)
if widgetName == nil then
return
end
if muiData.widgetDict[widgetName] == nil then return end
muiData.widgetDict[widgetName]["mygroup"]["circle"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"]["circle"] = nil
muiData.widgetDict[widgetName]["mygroup"]["circle2"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"]["circle2"] = nil
muiData.widgetDict[widgetName]["mygroup"]["circle1"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"]["circle1"] = nil
muiData.widgetDict[widgetName]["mygroup"]["rect"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"]["rect"] = nil
muiData.widgetDict[widgetName]["mygroup"]["rectmaster"]:removeEventListener("touch", M.toggleSwitchTouch)
muiData.widgetDict[widgetName]["mygroup"]["rectmaster"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"]["rectmaster"] = nil
muiData.widgetDict[widgetName]["mygroup"]:removeSelf()
muiData.widgetDict[widgetName]["mygroup"] = nil
muiData.widgetDict[widgetName] = nil
end
return M
|
--------------------------------
-- @module AnimationCache
-- @extend Ref
-- @parent_module cc
--------------------------------
-- Returns a Animation that was previously added.<br>
-- If the name is not found it will return nil.<br>
-- You should retain the returned copy if you are going to use it.
-- @function [parent=#AnimationCache] getAnimation
-- @param self
-- @param #string name
-- @return Animation#Animation ret (return value: cc.Animation)
--------------------------------
-- Adds a Animation with a name.
-- @function [parent=#AnimationCache] addAnimation
-- @param self
-- @param #cc.Animation animation
-- @param #string name
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
--
-- @function [parent=#AnimationCache] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Adds an animation from an NSDictionary<br>
-- Make sure that the frames were previously loaded in the SpriteFrameCache.<br>
-- param plist The path of the relative file,it use to find the plist path for load SpriteFrames.<br>
-- since v1.1
-- @function [parent=#AnimationCache] addAnimationsWithDictionary
-- @param self
-- @param #map_table dictionary
-- @param #string plist
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Deletes a Animation from the cache.
-- @function [parent=#AnimationCache] removeAnimation
-- @param self
-- @param #string name
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Adds an animation from a plist file.<br>
-- Make sure that the frames were previously loaded in the SpriteFrameCache.<br>
-- since v1.1<br>
-- js addAnimations<br>
-- lua addAnimations
-- @function [parent=#AnimationCache] addAnimationsWithFile
-- @param self
-- @param #string plist
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Purges the cache. It releases all the Animation objects and the shared instance.
-- @function [parent=#AnimationCache] destroyInstance
-- @param self
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Returns the shared instance of the Animation cache
-- @function [parent=#AnimationCache] getInstance
-- @param self
-- @return AnimationCache#AnimationCache ret (return value: cc.AnimationCache)
--------------------------------
-- js ctor
-- @function [parent=#AnimationCache] AnimationCache
-- @param self
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
return nil
|
local map = vim.api.nvim_set_keymap
map("n", "|", "<cmd>vsplit <CR><C-w>w<plug>(wintabs_close)<C-w>w", { noremap = true })
map("n", "<Space>l", "<cmd>nohlsearch<CR><C-l>", { noremap = true, silent = true })
map("n", "Y", "yy", { noremap = true, silent = true })
-- fold text
map("n", "zl", "zo", { noremap = true, silent = true })
map("n", "zL", "zO", { noremap = true, silent = true })
map("x", "zl", "zo", { noremap = true, silent = true })
map("x", "zL", "zO", { noremap = true, silent = true })
map("n", "zh", "zc", { noremap = true, silent = true })
map("n", "zH", "zC", { noremap = true, silent = true })
map("x", "zh", "zc", { noremap = true, silent = true })
map("x", "zH", "zC", { noremap = true, silent = true })
|
--- Corona wrapper for **fipMetadataFind**, a metadata iterator.
-- Usage :
--
-- local freeimage = require("plugin.freeimage")
-- local image
-- -- ...
-- local finder = freeimage.NewMetadataFind()
-- local ok, tag = finder:findFirstMetadata("EXIF_MAIN", image)
--
-- if ok then
-- repeat
-- -- process the tag
-- print(tag:getKey())
--
-- ok, tag = finder:findNextMetadata()
-- until not ok
-- end
--
-- -- the class can be called again with another metadata model
-- ok, tag = finder:findFirstMetadata("EXIF_EXIF", image)
--
-- if ok then
-- repeat
-- -- process the tag
-- print(tag:getKey())
--
-- ok, tag = finder:findNextMetadata()
-- until not ok
-- end
-- @module fipMetadataFind
--
-- 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.
--
-- [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
--
--- Provides information about the first instance of a tag that matches the metadata model specified in the model argument.
-- @function fipMetadataFind:findFirstMetadata
-- @string model Metadata model, cf. @{enums.FREE_IMAGE_MDMODEL}.
-- @tparam fipImage image Input image.
-- @treturn boolean Find succeeded?
-- @treturn fipTag On success, the first tag.
--- Find the next tag, if any, that matches the metadata model argument in a previous call to @{fipMetadataFind:findFirstMetadata}.
-- @function fipMetadataFind:findNextMetadata
-- @treturn boolean Find succeeded?
-- @treturn fipTag On success, the next tag.
--- Indicates whether the iterator is valid for use.
-- @function fipMetadataFind:isValid
-- @treturn boolean Search handle is allocated?
|
include("shared.lua")
SWEP.Author = "Cryotheum"
SWEP.Category = "Minge Defense"
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
SWEP.Instructions = "Left click to swing wrench and heal buildings, right click to pick up buildings to relocate them."
SWEP.PrintName = "Wrench"
SWEP.Purpose = "Hit things."
SWEP.UseHands = true
SWEP.ViewModelFOV = 54
--swep functions
function SWEP:Initialize() self:SharedInitialize() end
function SWEP:OnRemove() if IsValid(self.WrenchEntity) then self.WrenchEntity:Remove() end end
--[[function SWEP:PostDrawViewModel(...) move_view_model(...) end
function SWEP:PreDrawViewModel(...) move_view_model(...) end]]
|
---
---
--- File: lua_connect.lua
--- report for connect action
---
---
---
connect_report = {}
function connect_report.execute( resultList)
connect_report.doTitle( resultList )
connect_report.doBadStores(resultList)
end
function connect_report.doTitle( resultList )
local temp
local count
temp = tgs.reports.filter(resultList , { {"action",tgs.actions.ops.connect} } )
count = tgs.reports.count( temp )
reports.addLine(" ")
reports.addLine("Connect Report for "..count.." Stores ")
reports.addLine(os.date())
reports.addLine(" ")
end
function connect_report.doBadStores( resultList )
local temp
local count
local tempString
temp = tgs.reports.filter(resultList, { {"action",tgs.actions.ops.connect},{"status",false} })
count = tgs.reports.count(temp)
reports.addLine("Stores for which there is no service connectivity "..count )
for i, j in ipairs( temp ) do
for l,m in ipairs( j ) do
if ( m.action == tgs.actions.ops.connect) and ( m.status == false ) then
tempString = string.format("%d %s ",i,m.id )
reports.addLine( tempString)
end
end
end
end
tgs.reports.addReport("CONNECT_REPORT",connect_report )
|
--[[ AscendScripting Script -
This software is provided as free and open source by the
staff of The AscendScripting Team.This script was
written and is protected by the GPL v2. The following
script was released by a AscendScripting Staff Member.
Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
~~End of License Agreement
-- AscendScripting Staff, March 17, 2009. ]]
function SyndicateProwler_OnSpawn(Unit,Event)
Unit:CastSpell(1784)
end
function SyndicateProwler_OnEnterCombat(Unit,Event)
Unit:RegisterEvent("Disarm", 13000, 1)
Unit:RegisterEvent("SinisterStrike", 6000, 1)
end
function Disarm(Unit,Event)
Unit:FullCastSpellOnTarget(6713,plr)
end
function SinisterStrike(Unit,Event)
Unit:FullCastSpellOnTarget(14873,plr)
end
function SyndicateProwler_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function SyndicateProwler_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(2588,18,"SyndicateProwler_OnSpawn")
RegisterUnitEvent(2588,1,"SyndicateProwler_OnEnterCombat")
RegisterUnitEvent(2588,2,"SyndicateProwler_OnLeaveCombat")
RegisterUnitEvent(2588,4,"SyndicateProwler_OnDied")
|
local IUiElement = require("api.gui.IUiElement")
local ISettable = require("api.gui.ISettable")
return class.interface("ISidebarView", { get_sidebar_entries = "function" }, {IUiElement, ISettable})
|
-- Workspace configuration
workspace "E+G Study Project"
architecture "x86_64"
configurations {
"Debug",
"Release"
}
language "C++"
cppdialect "C++17"
defines {
"SDL_MAIN_HANDLED"
}
filter "configurations:Debug"
defines { "ESD_DEBUG" }
symbols "On"
filter "configurations:Release"
defines { "NDEBUG" }
optimize "Full"
flags { "LinkTimeOptimization" }
-- Main project
project "Esdiel"
location "."
kind "ConsoleApp"
warnings "Extra"
targetname "%{prj.name}-%{cfg.system}-%{cfg.buildcfg}"
targetdir "example"
debugdir "example"
objdir "build/%{cfg.system}/%{cfg.buildcfg}/obj"
files {
"%{prj.location}/include/**.hpp",
"%{prj.location}/source/**.cpp",
"%{prj.location}/thirdparty/glad/glad.c"
}
includedirs {
"%{prj.location}/include",
"%{prj.location}/thirdparty/",
"%{prj.location}/thirdparty/SDL2/include"
}
links {
"SDL2main",
"SDL2"
}
filter "system:windows"
libdirs "%{prj.location}/thirdparty/SDL2/lib"
filter "system:linux"
buildoptions { "`sdl2-config --cflags`" }
linkoptions { "`sdl2-config --libs`" }
links { "dl" }
filter {}
|
-- http://lua-users.org/wiki/StringRecipes
local function ends_with(str, ending)
return ending == "" or str:sub(-#ending) == ending
end
if FORMAT:match 'latex' then
function Image(elem)
local src = elem.src
if ends_with(src, '.svg') then
elem.src = src .. '.pdf'
end
return elem
end
end
|
local modifiers = require("colorbuddy.modifiers").modifiers
local util = require("colorbuddy.util")
describe("modifiers", function()
it("should return averages well", function()
-- mix(#15293E, #012549, 50%)
local obj1 = { util.rgb_string_to_hsl("#15293E") }
local obj2 = { util.rgb_string_to_hsl("#012549") }
local hsl1 = {
H = obj1[1],
S = obj1[2],
L = obj1[3],
}
local hsl2 = {
H = obj2[1],
S = obj2[2],
L = obj2[3],
}
local result = modifiers.average(hsl1.H, hsl1.S, hsl1.L, hsl2)
local rgb_result = util.hsl_to_rgb_string(unpack(result))
assert.are.same("#0e2743", rgb_result)
end)
it("should know how to do negatives", function()
local obj1 = { util.rgb_string_to_hsl("#808080") }
assert.are.same("#7f7f7f", util.hsl_to_rgb_string(unpack(modifiers.negative(unpack(obj1)))))
local obj2 = { util.rgb_string_to_hsl("#000000") }
assert.are.same("#ffffff", util.hsl_to_rgb_string(unpack(modifiers.negative(unpack(obj2)))))
local obj3 = { util.rgb_string_to_hsl("#ffffff") }
assert.are.same("#000000", util.hsl_to_rgb_string(unpack(modifiers.negative(unpack(obj3)))))
end)
-- Pending: Some dumb float drift that I don't want to deal w/ right now.
pending("should do complements to nice colors", function()
local original_string = "#325abd"
assert.are.same(
original_string,
util.hsl_to_rgb_string(unpack(modifiers.complement(unpack(modifiers.complement(util.rgb_string_to_hsl(original_string))))))
)
end)
end)
|
--[[
foxBot v1.4 by fox: https://taraxis.com/foxBot-SRB2
Based heavily on VL_ExAI-v2.lua by CobaltBW: https://mb.srb2.org/showthread.php?t=46020
Initially an experiment to run bots off of PreThinkFrame instead of BotTiccmd
This allowed AI to control a real player for use in netgames etc.
Since they're no longer "bots" to the game, it integrates a few concepts from ClassicCoop-v1.3.lua by FuriousFox: https://mb.srb2.org/showthread.php?t=41377
Such as ring-sharing, nullifying damage, etc. to behave more like a true SP bot, as player.bot is read-only
Future TODO?
* Avoid inturrupting players/bots carrying other players/bots due to flying too close
(need to figure out a good way to detect if we're carrying someone)
* Modular rewrite, defining behaviors on hashed functions - this would allow:
* Mod support - AI hooks / overrides for targeting, ability rules, etc.
* Gametype support - definable goals based on current game mode
* Better abstractions - no more monolithic mess / derpy leader system
* Other things to improve your life immeasurably
--------------------------------------------------------------------------------
Copyright (c) 2021 Alex Strout and Shane Ellis
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.
]]
--[[
--------------------------------------------------------------------------------
GLOBAL CONVARS
(see "bothelp" at bottom for a description of each)
--------------------------------------------------------------------------------
]]
local CV_ExAI = CV_RegisterVar({
name = "ai_sys",
defaultvalue = "On",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIDebug = CV_RegisterVar({
name = "ai_debug",
defaultvalue = "-1",
flags = 0,
PossibleValue = {MIN = -1, MAX = 31}
})
local CV_AISeekDist = CV_RegisterVar({
name = "ai_seekdist",
defaultvalue = "512",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = 64, MAX = 1536}
})
local CV_AIIgnore = CV_RegisterVar({
name = "ai_ignore",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
Enemies = 1,
RingsMonitors = 2,
All = 3
}
})
local CV_AICatchup = CV_RegisterVar({
name = "ai_catchup",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIKeepDisconnected = CV_RegisterVar({
name = "ai_keepdisconnected",
defaultvalue = "On",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = CV_OnOff
})
local CV_AIDefaultLeader = CV_RegisterVar({
name = "ai_defaultleader",
defaultvalue = "32",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = -1, MAX = 32}
})
local CV_AIHurtMode = CV_RegisterVar({
name = "ai_hurtmode",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
ShieldLoss = 1,
RingLoss = 2
}
})
local CV_AIStatMode = CV_RegisterVar({
name = "ai_statmode",
defaultvalue = "Off",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {
Off = 0,
Rings = 1,
Lives = 2,
Both = 3
}
})
local CV_AITeleMode = CV_RegisterVar({
name = "ai_telemode",
defaultvalue = "0",
flags = CV_NETVAR|CV_SHOWMODIF,
PossibleValue = {MIN = 0, MAX = UINT16_MAX}
})
local CV_AIShowHud = CV_RegisterVar({
name = "ai_showhud",
defaultvalue = "On",
flags = 0,
PossibleValue = CV_OnOff
})
--[[
--------------------------------------------------------------------------------
GLOBAL TYPE DEFINITIONS
Defines any mobj types etc. needed by foxBot
--------------------------------------------------------------------------------
]]
freeslot(
"MT_FOXAI_POINT"
)
mobjinfo[MT_FOXAI_POINT] = {
spawnstate = S_INVISIBLE,
radius = FRACUNIT,
height = FRACUNIT,
--Sector clipping allowed to properly account for radius in floorz / ceilingz checks
flags = MF_NOGRAVITY|MF_NOTHINK|MF_NOCLIPTHING
}
--[[
--------------------------------------------------------------------------------
GLOBAL HELPER VALUES / FUNCTIONS
Used in various points throughout code
--------------------------------------------------------------------------------
]]
--Global MT_FOXAI_POINTs used in various functions (typically by CheckPos)
--Not thread-safe (no need); could be placed in AI tables (as before), at the cost of more things to sync
local PosCheckerObj = nil
--NetVars!
addHook("NetVars", function(network)
PosCheckerObj = network($)
end)
--Text table used for HUD hook
local hudtext = {}
--Resolve player by number (string or int)
local function ResolvePlayerByNum(num)
if type(num) != "number"
num = tonumber(num)
end
if num != nil and num >= 0 and num < 32
return players[num]
end
return nil
end
--Returns absolute angle (0 to 180)
--Useful for comparing angles
local function AbsAngle(ang)
if ang < 0 and ang > ANGLE_180
return InvAngle(ang)
end
return ang
end
--Destroys mobj and returns nil for assignment shorthand
local function DestroyObj(mobj)
if mobj and mobj.valid
P_RemoveMobj(mobj)
end
return nil
end
--Moves specified poschecker to x, y, z coordinates, optionally with radius and height
--Useful for checking floorz/ceilingz or other properties at some arbitrary point in space
local function CheckPos(poschecker, x, y, z, radius, height)
if poschecker and poschecker.valid
P_TeleportMove(poschecker, x, y, z)
else
poschecker = P_SpawnMobj(x, y, z, MT_FOXAI_POINT)
end
--Optionally set radius and height, resetting to type default if not specified
if not radius then radius = poschecker.info.radius end
poschecker.radius = radius
if not height then height = poschecker.info.height end
poschecker.height = height
return poschecker
end
--Fix bizarre bug where floorz / ceilingz of certain objects is sometimes inaccurate
--(e.g. rings or blue spheres on FOFs - not needed for players or other recently moved objects)
local function FixBadFloorOrCeilingZ(pmo)
--Briefly set MF_NOCLIP so we don't accidentally destroy the object, oops (e.g. ERZ snails in walls)
local oflags = pmo.flags
pmo.flags = $ | MF_NOCLIP
P_TeleportMove(pmo, pmo.x, pmo.y, pmo.z)
pmo.flags = oflags
end
--Returns height-adjusted Z for accurate comparison to FloorOrCeilingZ
local function AdjustedZ(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.z + pmo.height
end
return pmo.z
end
--Returns floorz or ceilingz for pmo based on bmo's flip status
local function FloorOrCeilingZ(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.ceilingz
end
return pmo.floorz
end
--Returns water top or bottom for pmo based on bmo's flip status
local function WaterTopOrBottom(bmo, pmo)
if bmo.eflags & MFE_VERTICALFLIP
return pmo.waterbottom
end
return pmo.watertop
end
--Same as above, but for an arbitrary position in space
--Note this may be inaccurate for player-specific things like standing on goop or on other objects
--(e.g. players above solid objects will report that object's height as their floorz - whereas this will not)
local function FloorOrCeilingZAtPos(bmo, x, y, z, radius, height)
--Work around lack of a P_CeilingzAtPos function
PosCheckerObj = CheckPos(PosCheckerObj, x, y, z, radius, height)
--PosCheckerObj.state = S_LOCKON2
return FloorOrCeilingZ(bmo, PosCheckerObj)
end
--More accurately predict an object's FloorOrCeilingZ by physically shifting it forward and then back
--This terrifies me
local function PredictFloorOrCeilingZ(bmo, pfac)
--Amazingly, this somehow does not trigger sector tags etc.
--Could alternatively use an MF_SOLID PosChecker, ignoring players with a MobjCollide hook
--However, I prefer this for now as it's using the original object's legitimate floor checks
local ox, oy, oz = bmo.x, bmo.y, bmo.z
local oflags = bmo.flags
bmo.flags = $ | MF_NOCLIPTHING
P_TeleportMove(bmo,
bmo.x + bmo.momx * pfac,
bmo.y + bmo.momy * pfac,
bmo.z + bmo.momz * pfac)
local predictfloor = FloorOrCeilingZ(bmo, bmo)
bmo.flags = oflags
P_TeleportMove(bmo, ox, oy, oz)
return predictfloor
end
--P_CheckSight wrapper to approximate sight checks for objects above/below FOFs
--Eliminates being able to "see" targets through FOFs at extreme angles
local function CheckSight(bmo, pmo)
--Allow equal heights so we can see DSZ3 boss
return bmo.floorz <= pmo.ceilingz
and bmo.ceilingz >= pmo.floorz
and P_CheckSight(bmo, pmo)
end
--P_SuperReady but without the shield and PF_JUMPED checks
local function SuperReady(player)
return not player.powers[pw_super]
and not player.powers[pw_invulnerability]
and not player.powers[pw_tailsfly]
and (player.charflags & SF_SUPER)
--and (player.pflags & PF_JUMPED)
--and not (player.powers[pw_shield] & SH_NOSTACK)
and not (maptol & TOL_NIGHTS)
and All7Emeralds(emeralds)
and player.rings >= 50
end
--Silently toggle a convar w/o printing to console
local function ToggleSilent(player, convar)
local cval = CV_FindVar(convar).value --No error checking - use with caution!
COM_BufInsertText(player, convar .. " " .. 1 - cval .. "; " .. convar .. " " .. cval)
end
--[[
--------------------------------------------------------------------------------
AI SETUP FUNCTIONS / CONSOLE COMMANDS
Any AI "setup" logic, including console commands
--------------------------------------------------------------------------------
]]
--Reset (or define) all AI vars to their initial values
local function ResetAI(ai)
ai.think_last = 0 --Last think time
ai.jump_last = 0 --Jump history
ai.spin_last = 0 --Spin history
ai.move_last = 0 --Directional input history
ai.anxiety = 0 --Catch-up counter
ai.panic = 0 --Catch-up mode
ai.panicjumps = 0 --If too many, just teleport
ai.flymode = 0 --0 = No interaction. 1 = Grab Sonic. 2 = Sonic is latched.
ai.spinmode = 0 --If 1, Tails is spinning or preparing to charge spindash
ai.thinkfly = 0 --If 1, Tails will attempt to fly when Sonic jumps
ai.idlecount = 0 --Checks the amount of time without any player inputs
ai.bored = 0 --AI will act independently if "bored".
ai.drowning = 0 --AI drowning panic. 2 = Tails flies for air.
ai.target = nil --Enemy to target
ai.targetjumps = 0 --If too many, abort target
ai.targetcount = 0 --Number of targets in range (used for armageddon shield)
ai.targetnosight = 0 --How long the target has been out of view
ai.playernosight = 0 --How long the player has been out of view
ai.stalltics = 0 --Time that AI has struggled to move
ai.attackwait = 0 --Tics to wait before attacking again
ai.attackoverheat = 0 --Used by Fang to determine whether to wait
ai.cmd_time = 0 --If > 0, suppress bot ai in favor of player controls
ai.pushtics = 0 --Time leader has pushed against something (used to maybe attack it)
ai.longjump = false --AI is making a decently sized leap for an enemy
ai.doteleport = false --AI is attempting to teleport
ai.predictgap = 0 --AI is jumping a gap
--Destroy any child objects if they're around
ai.overlay = DestroyObj($) --Speech bubble overlay - only (re)create this if needed in think logic
ai.overlaytime = 0 --Time overlay has been active
ai.waypoint = DestroyObj($) --Transient waypoint used for navigating around corners
end
--Register follower with leader for lookup later
local function RegisterFollower(leader, bot)
if not leader.ai_followers
leader.ai_followers = {}
end
leader.ai_followers[#bot + 1] = bot
end
--Unregister follower with leader
local function UnregisterFollower(leader, bot)
if not (leader and leader.valid and leader.ai_followers)
return
end
leader.ai_followers[#bot + 1] = nil
if table.maxn(leader.ai_followers) < 1
leader.ai_followers = nil
end
end
--Create AI table for a given player, if needed
local function SetupAI(player)
if player.ai
return
end
--Create table, defining any vars that shouldn't be reset via ResetAI
player.ai = {
leader = nil, --Bot's leader
realleader = nil, --Bot's "real" leader (if temporarily following someone else)
lastrings = player.rings, --Last ring count of bot (used to sync w/ leader)
lastlives = player.lives, --Last life count of bot (used to sync w/ leader)
realrings = player.rings, --"Real" ring count of bot (outside of sync)
realxtralife = player.xtralife, --"Real" xtralife count of bot (outside of sync)
reallives = player.lives, --"Real" life count of bot (outside of sync)
ronin = false, --Headless bot from disconnected client?
timeseed = P_RandomByte() + #player, --Used for time-based pseudo-random behaviors (e.g. via BotTime)
syncrings = false, --Current sync setting for rings
synclives = false, --Current sync setting for lives
lastseenpos = { x = 0, y = 0, z = 0 } --Last seen position tracking
}
ResetAI(player.ai) --Define the rest w/ their respective values
player.ai.playernosight = 3 * TICRATE --For setup only, queue an instant teleport
end
--"Repossess" a bot for player control
local function Repossess(player)
--Reset our original analog etc. prefs
--SendWeaponPref isn't exposed to Lua, so just cycle convars to trigger it
ToggleSilent(player, "flipcam")
if not netgame and #player > 0
ToggleSilent(server, "flipcam2")
end
--Reset our vertical aiming (in case we have vert look disabled)
player.aiming = 0
--Reset anything else
ResetAI(player.ai)
end
--Destroy AI table (and any child tables / objects) for a given player, if needed
local function DestroyAI(player)
if not player.ai
return
end
--Reset pflags etc. for player
Repossess(player)
--Unregister ourself from our (real) leader if still valid
UnregisterFollower(player.ai.realleader, player)
--Kick headless bots w/ no client
--Otherwise they sit and do nothing
if player.ai.ronin
player.quittime = 1
end
--Restore our "real" ring / life counts if synced
if player.ai.syncrings
player.rings = player.ai.realrings
player.xtralife = player.ai.realxtralife
end
if player.ai.synclives
player.lives = player.ai.reallives
if player.lives < 1 and not player.spectator
player.playerstate = PST_REBORN
end
end
--My work here is done
player.ai = nil
collectgarbage()
end
--Get our "top" leader in a leader chain (if applicable)
--e.g. for A <- B <- D <- C, D's "top" leader is A
local function GetTopLeader(bot, basebot)
if bot != basebot and bot.ai
and bot.ai.realleader and bot.ai.realleader.valid
return GetTopLeader(bot.ai.realleader, basebot)
end
return bot
end
--Get our "bottom" follower in a leader chain (if applicable)
--e.g. for A <- B <- D <- C, A's "bottom" follower is C
local function GetBottomFollower(bot, basebot)
--basebot nil on initial call, but automatically set after
if bot != basebot and bot.ai_followers
for k, b in pairs(bot.ai_followers)
--Pick a random node if the tree splits
if P_RandomByte() < 128
or table.maxn(bot.ai_followers) == k
return GetBottomFollower(b, basebot or bot)
end
end
end
return bot
end
--List all bots, optionally excluding bots led by leader
local function SubListBots(player, leader, bot, level)
if bot == leader
return 0
end
local msg = #bot .. " - " .. bot.name
for i = 0, level
msg = " " .. $
end
if bot.ai
if bot.ai.cmd_time
msg = $ .. " \x81(player-controlled)"
end
if bot.ai.ronin
msg = $ .. " \x83(disconnected)"
end
else
msg = $ .. " \x84(player)"
end
if bot.spectator
msg = $ .. " \x87(KO'd)"
end
if bot.quittime
msg = $ .. " \x86(disconnecting)"
end
CONS_Printf(player, msg)
local count = 1
if bot.ai_followers
for _, b in pairs(bot.ai_followers)
count = $ + SubListBots(player, leader, b, level + 1)
end
end
return count
end
local function ListBots(player, leader)
if leader != nil
leader = ResolvePlayerByNum(leader)
if leader and leader.valid
CONS_Printf(player, "\x84 Excluding players/bots led by " .. leader.name)
end
end
local count = 0
for p in players.iterate
if not p.ai
count = $ + SubListBots(player, leader, p, 0)
end
end
CONS_Printf(player, "Returned " .. count .. " nodes")
end
COM_AddCommand("LISTBOTS", ListBots, COM_LOCAL)
--Set player as a bot following a particular leader
--Internal/Admin-only: Optionally specify some other player/bot to follow leader
local function SetBot(player, leader, bot)
local pbot = player
if bot != nil --Must check nil as 0 is valid
pbot = ResolvePlayerByNum(bot)
end
if not (pbot and pbot.valid)
CONS_Printf(player, "Invalid bot! Please specify a bot by number:")
ListBots(player)
return
end
--Make sure we won't end up following ourself
local pleader = ResolvePlayerByNum(leader)
if pleader and pleader.valid
and GetTopLeader(pleader, pbot) == pbot
CONS_Printf(player, pbot.name + " would end up following itself! Please try a different leader:")
ListBots(player, #pbot)
return
end
--Set up our AI (if needed) and figure out leader
SetupAI(pbot)
if pleader and pleader.valid
CONS_Printf(player, "Set bot " + pbot.name + " following " + pleader.name)
if player != pbot
CONS_Printf(pbot, player.name + " set bot " + pbot.name + " following " + pleader.name)
end
elseif pbot.ai.realleader
CONS_Printf(player, "Stopping bot " + pbot.name)
if player != pbot
CONS_Printf(pbot, player.name + " stopping bot " + pbot.name)
end
else
CONS_Printf(player, "Invalid leader! Please specify a leader by number:")
ListBots(player, #pbot)
end
--Valid leader?
if pleader and pleader.valid
--Unregister ourself from our old (real) leader (if applicable)
UnregisterFollower(pbot.ai.realleader, pbot)
--Set the new leader
pbot.ai.leader = pleader
pbot.ai.realleader = pleader
--Register ourself as a follower
RegisterFollower(pleader, pbot)
else
--Destroy AI if no leader set
DestroyAI(pbot)
end
end
COM_AddCommand("SETBOTA", SetBot, COM_ADMIN)
COM_AddCommand("SETBOT", function(player, leader)
SetBot(player, leader)
end, 0)
--Admin-only: Debug command for testing out shield AI
--Left in for convenience, use with caution - certain shield values may crash game
COM_AddCommand("DEBUG_BOTSHIELD", function(player, bot, shield, inv, spd, super, rings, ems, scale)
bot = ResolvePlayerByNum(bot)
shield = tonumber(shield)
if not (bot and bot.valid)
return
elseif shield == nil
CONS_Printf(player, bot.name + " has shield " + bot.powers[pw_shield])
return
end
P_SwitchShield(bot, shield)
local msg = player.name + " granted " + bot.name + " shield " + shield
inv = tonumber(inv)
if inv
bot.powers[pw_invulnerability] = inv
msg = $ + " invulnerability " + inv
end
spd = tonumber(spd)
if spd
bot.powers[pw_sneakers] = spd
msg = $ + " sneakers " + spd
end
super = tonumber(super)
if super and not (bot.charflags & SF_SUPER)
bot.charflags = $ | SF_SUPER
msg = $ + " super ability"
end
rings = tonumber(rings)
if rings
P_GivePlayerRings(bot, rings)
msg = $ + " rings " + rings
end
ems = tonumber(ems)
if ems and not All7Emeralds(emeralds)
local bmo = bot.realmo
if bmo and bmo.valid
local ofs = 32 * bmo.scale + bmo.radius
P_SpawnMobj(bmo.x - ofs, bmo.y - ofs, bmo.z, MT_EMERALD1)
P_SpawnMobj(bmo.x - ofs, bmo.y, bmo.z, MT_EMERALD2)
P_SpawnMobj(bmo.x - ofs, bmo.y + ofs, bmo.z, MT_EMERALD3)
P_SpawnMobj(bmo.x + ofs, bmo.y - ofs, bmo.z, MT_EMERALD4)
P_SpawnMobj(bmo.x + ofs, bmo.y, bmo.z, MT_EMERALD5)
P_SpawnMobj(bmo.x + ofs, bmo.y + ofs, bmo.z, MT_EMERALD6)
P_SpawnMobj(bmo.x, bmo.y - ofs, bmo.z, MT_EMERALD7)
msg = $ + " emeralds"
end
end
scale = tonumber(scale)
if scale
local bmo = bot.realmo
if bmo and bmo.valid
if scale > 0
bmo.destscale = scale * FRACUNIT
msg = $ + " scale " + scale
elseif scale < 0
bmo.destscale = FRACUNIT / abs(scale)
msg = $ + " scale 1/" + abs(scale)
end
end
end
print(msg)
end, COM_ADMIN)
--Debug command for printing out AI objects
COM_AddCommand("DEBUG_BOTAIDUMP", function(player, bot)
bot = ResolvePlayerByNum(bot)
if not (bot and bot.valid and bot.ai)
return
end
CONS_Printf(player, "-- botai " .. bot.name .. " --")
for k, v in pairs(bot.ai)
CONS_Printf(player, k .. " = " .. tostring(v))
end
end, COM_LOCAL)
--[[
--------------------------------------------------------------------------------
AI LOGIC
Actual AI behavior etc.
--------------------------------------------------------------------------------
]]
--Returns true for a specified minimum time within a maximum time period
--Used for pseudo-random behaviors like strafing or attack mixups
--e.g. BotTime(bai, 2, 8) will return true for 2s out of every 8s
local function BotTime(bai, mintime, maxtime)
return (leveltime + bai.timeseed) % (maxtime * TICRATE) < mintime * TICRATE
end
--Teleport a bot to leader, optionally fading out
local function Teleport(bot, fadeout)
if not (bot.valid and bot.ai)
or bot.exiting or (bot.pflags & PF_FULLSTASIS) --Whoops
--Consider teleport "successful" on fatal errors for cleanup
return true
end
--Make sure everything's valid (as this is also called on respawn)
--Check leveltime to only teleport after we've initially spawned in
local leader = bot.ai.leader
if not (leveltime and leader and leader.valid)
return true
end
local bmo = bot.realmo
local pmo = leader.realmo
if not (bmo and bmo.valid and pmo and pmo.valid)
or pmo.health <= 0 --Don't teleport to dead leader!
return true
end
--Leader in a zoom tube or other scripted vehicle?
if leader.powers[pw_carry] == CR_NIGHTSMODE
or leader.powers[pw_carry] == CR_ZOOMTUBE
or leader.powers[pw_carry] == CR_MINECART
or bot.powers[pw_carry] == CR_MINECART
return true
end
--No fadeouts supported in zoom tube or quittime
if bot.powers[pw_carry] == CR_ZOOMTUBE
or bot.quittime
fadeout = false
end
--Teleport override?
if CV_AITeleMode.value
--Probably successful if we're not in a panic and can see leader
return not (bot.ai.panic or bot.ai.playernosight)
end
--Fade out (if needed), teleporting after
if not fadeout
bot.powers[pw_flashing] = TICRATE / 2 --Skip the fadeout time
elseif not bot.powers[pw_flashing]
or bot.powers[pw_flashing] > TICRATE
bot.powers[pw_flashing] = TICRATE
end
if bot.powers[pw_flashing] > TICRATE / 2
return false
end
--Adapted from 2.2 b_bot.c
local z = pmo.z
local zoff = pmo.height + 128 * pmo.scale
if pmo.eflags & MFE_VERTICALFLIP
z = max(z - zoff, pmo.floorz + pmo.height)
else
z = min(z + zoff, pmo.ceilingz - pmo.height)
end
bmo.flags2 = $
& ~MF2_OBJECTFLIP | (pmo.flags2 & MF2_OBJECTFLIP)
& ~MF2_TWOD | (pmo.flags2 & MF2_TWOD)
bmo.eflags = $
& ~MFE_VERTICALFLIP | (pmo.eflags & MFE_VERTICALFLIP)
& ~MFE_UNDERWATER | (pmo.eflags & MFE_UNDERWATER)
--bot.powers[pw_underwater] = leader.powers[pw_underwater] --Don't sync water/space time
--bot.powers[pw_spacetime] = leader.powers[pw_spacetime]
bot.powers[pw_gravityboots] = leader.powers[pw_gravityboots]
bot.powers[pw_nocontrol] = leader.powers[pw_nocontrol]
P_ResetPlayer(bot)
bmo.state = S_PLAY_JUMP --Looks/feels nicer
bot.pflags = $ | P_GetJumpFlags(bot)
--Average our momentum w/ leader's - 1/4 ours, 3/4 theirs
bmo.momx = $ / 4 + pmo.momx * 3/4
bmo.momy = $ / 4 + pmo.momy * 3/4
bmo.momz = $ / 4 + pmo.momz * 3/4
--Zero momy in 2D mode (oops)
if bmo.flags2 & MF2_TWOD
bmo.momy = 0
end
P_TeleportMove(bmo, pmo.x, pmo.y, z)
P_SetScale(bmo, pmo.scale)
bmo.destscale = pmo.destscale
bmo.angle = pmo.angle
--Fade in (if needed)
if bot.powers[pw_flashing] < TICRATE / 2
bot.powers[pw_flashing] = TICRATE / 2
end
return true
end
--Calculate a "desired move" vector to a target, taking into account momentum and angle
local function DesiredMove(bmo, pmo, dist, mindist, leaddist, minmag, grounded, spinning, _2d)
--Calculate momentum for targets that don't set it!
local pmomx = pmo.momx
local pmomy = pmo.momy
if not (pmomx or pmomy or pmo.player) --No need to do this for players
if pmo.ai_momlastposx != nil --Transient last position tracking
--These are TICRATE-dependent, but so are mobj speeds I think
pmomx = ((pmo.x - pmo.ai_momlastposx) + pmo.ai_momlastx) / 2
pmomy = ((pmo.y - pmo.ai_momlastposy) + pmo.ai_momlasty) / 2
end
pmo.ai_momlastposx = pmo.x
pmo.ai_momlastposy = pmo.y
pmo.ai_momlastx = pmomx
pmo.ai_momlasty = pmomy
end
--Figure out time to target
local timetotarget = 0
if not (bmo.player.climbing or bmo.player.spectator)
--Calculate prediction factor based on control state (air, spin)
local pfac = 1 --General prediction mult
if spinning
pfac = $ * 16 --Taken from 2.2 p_user.c (pushfoward >> 4)
elseif not grounded
if spinning
pfac = $ * 8 --Taken from 2.2 p_user.c (pushfoward >> 3)
else
pfac = $ * 4 --Taken from 2.2 p_user.c (pushfoward >> 2)
end
end
if bmo.eflags & MFE_UNDERWATER
pfac = $ * 2 --Close enough
end
--Extrapolate dist out to include Z as well
dist = FixedHypot($, abs(pmo.z - bmo.z))
--Calculate "total" momentum between us and target
--Does not include Z momentum as we don't control that
local tmom = FixedHypot(
bmo.momx - pmomx,
bmo.momy - pmomy
)
--Calculate time, capped to sane values (influenced by pfac)
--Note this is independent of TICRATE
timetotarget = FixedDiv(
min(dist * pfac, 256 * FRACUNIT * pfac),
max(tmom, 32 * FRACUNIT)
)
end
--Figure out movement and prediction angles
--local mang = R_PointToAngle2(0, 0, bmo.momx, bmo.momy)
local px = pmo.x + FixedMul(pmomx - bmo.momx, timetotarget)
local py = pmo.y + FixedMul(pmomy - bmo.momy, timetotarget)
if leaddist
local lang = R_PointToAngle2(0, 0, pmomx, pmomy)
px = $ + FixedMul(cos(lang), leaddist)
py = $ + FixedMul(sin(lang), leaddist)
end
local pang = R_PointToAngle2(bmo.x, bmo.y, px, py)
--Uncomment this for a handy prediction indicator
--PosCheckerObj = CheckPos(PosCheckerObj, px, py, pmo.z)
--PosCheckerObj.state = S_LOCKON1
--Stop skidding everywhere! (commented as this isn't really needed anymore)
--if grounded and not (bmo.player.pflags & PF_SPINNING)
--and AbsAngle(mang - bmo.angle) < ANGLE_157h
--and AbsAngle(mang - pang) > ANGLE_157h
--and bmo.player.speed >= FixedMul(bmo.player.runspeed / 2, bmo.scale)
-- return 0, 0
--end
--2D Mode!
if _2d
local pdist = abs(px - bmo.x) - mindist
if pdist < 0
return 0, 0
end
local mag = min(max(pdist, minmag), 50 * FRACUNIT)
if px < bmo.x
mag = -$
end
return 0, --forwardmove
mag / FRACUNIT --sidemove
end
--Resolve movement vector
pang = $ - bmo.angle
local pdist = R_PointToDist2(bmo.x, bmo.y, px, py) - mindist
if pdist < 0
return 0, 0
end
local mag = min(max(pdist, minmag), 50 * FRACUNIT)
return FixedMul(cos(pang), mag) / FRACUNIT, --forwardmove
FixedMul(sin(pang), -mag) / FRACUNIT --sidemove
end
--Determine if a given target is valid, based on a variety of factors
local function ValidTarget(bot, leader, bpx, bpy, target, maxtargetdist, maxtargetz, flip, ignoretargets, isspecialstage)
if not (target and target.valid and target.health > 0)
or target.state == S_INVISIBLE --Ignore invisible things
return 0
end
--Target type, in preferred order
-- -2 = passive - vehicles
-- -1 = active/passive - priority targets (typically set after rules)
-- 1 = active - enemy etc. (more aggressive engagement rules)
-- 2 = passive - rings etc.
local ttype = 0
--We want an enemy
if (ignoretargets & 1 == 0)
and (target.flags & (MF_BOSS | MF_ENEMY))
and target.type != MT_ROSY --Oops
and (
--Ignore flashing targets unless tagged in CoopOrDie
target.cd_lastattacker
or not (target.flags2 & MF2_FRET)
)
and not (target.flags2 & (MF2_BOSSFLEE | MF2_BOSSDEAD))
ttype = 1
--Or, if melee, a shieldless friendly to buff
elseif bot.charability2 == CA2_MELEE
and target.player and target.player.valid
and bot.revitem == MT_LHRT
and not (
bot.ai.attackwait
or target.player.spectator
or (target.player.powers[pw_shield] & SH_NOSTACK)
or target.player.revitem == MT_LHRT
or target.player.spinitem == MT_LHRT
or target.player.thokitem == MT_LHRT
or SuperReady(target.player)
)
and P_IsObjectOnGround(target)
ttype = 1
--Air bubbles!
elseif target.type == MT_EXTRALARGEBUBBLE
and (
bot.ai.drowning
or (
bot.powers[pw_underwater] > 0
and (
leader.powers[pw_underwater] <= 0
or bot.powers[pw_underwater] < leader.powers[pw_underwater]
)
)
)
ttype = 2
--Rings!
elseif (ignoretargets & 2 == 0)
and (
(target.type >= MT_RING and target.type <= MT_FLINGBLUESPHERE)
or target.type == MT_COIN or target.type == MT_FLINGCOIN
)
if isspecialstage
ttype = -1
else
ttype = 2
end
maxtargetdist = $ / 2 --Rings half-distance
--Monitors!
elseif (ignoretargets & 2 == 0)
and (target.flags & MF_MONITOR) --Skip all these checks otherwise
and not bot.bot --SP bots can't pop monitors
and (
target.type == MT_RING_BOX or target.type == MT_1UP_BOX
or target.type == MT_SCORE1K_BOX or target.type == MT_SCORE10K_BOX
or target.type == MT_MYSTERY_BOX --Sure why not
or target.type > MT_NAMECHECK --Just grab any custom monitor? Probably won't hurt
or (
leader.powers[pw_sneakers] > bot.powers[pw_sneakers]
and (
target.type == MT_SNEAKERS_BOX
or target.type == MT_SNEAKERS_GOLDBOX
)
)
or (
leader.powers[pw_invulnerability] > bot.powers[pw_invulnerability]
and (
target.type == MT_INVULN_BOX
or target.type == MT_INVULN_GOLDBOX
)
)
or (
leader.powers[pw_shield] and not bot.powers[pw_shield]
and (
(target.type >= MT_PITY_BOX and target.type <= MT_ELEMENTAL_BOX)
or (target.type >= MT_FLAMEAURA_BOX and target.type <= MT_ELEMENTAL_GOLDBOX)
or (target.type >= MT_FLAMEAURA_GOLDBOX and target.type <= MT_THUNDERCOIN_GOLDBOX)
)
)
or (
(leader.powers[pw_shield] & SH_FORCE) and (bot.powers[pw_shield] & SH_FORCE)
and (leader.powers[pw_shield] & SH_FORCEHP) > (bot.powers[pw_shield] & SH_FORCEHP)
and (
target.type == MT_FORCE_BOX
or target.type == MT_FORCE_GOLDBOX
)
)
or (
(leader.powers[pw_gravityboots] > bot.powers[pw_gravityboots]
or (leader.realmo.eflags & MFE_VERTICALFLIP) != (bot.realmo.eflags & MFE_VERTICALFLIP))
and (
target.type == MT_GRAVITY_BOX
or target.type == MT_GRAVITY_GOLDBOX
)
)
)
ttype = 1 --Can pull sick jumps for these
--Other powerups
elseif (ignoretargets & 2 == 0)
and not bot.bot --SP bots can't grab these
and (
(
target.type == MT_FIREFLOWER
and (leader.powers[pw_shield] & SH_FIREFLOWER) > (bot.powers[pw_shield] & SH_FIREFLOWER)
)
or (
target.type == MT_STARPOST
and target.health > bot.starpostnum
)
)
ttype = 1
--Vehicles
elseif (
target.type == MT_MINECARTSPAWNER
or (
target.type == MT_ROLLOUTROCK
and leader.powers[pw_carry] == CR_ROLLOUT
and not target.tracer --No driver
)
)
and not bot.powers[pw_carry]
ttype = -2
maxtargetdist = $ * 2 --Vehicles double-distance! (within searchBlockmap coverage)
--Chaos Mode ready emblems? Bit of a hack as foxBot needs better mod support
elseif (
bot.chaos and leader.chaos
and target.info.spawnstate == S_EMBLEM1
and bot.chaos.goal != leader.chaos.goal
)
ttype = 1
else
return 0
end
--Fix occasionally bad floorz / ceilingz values for things
if not target.ai_validfocz
FixBadFloorOrCeilingZ(target)
target.ai_validfocz = true
end
--Consider our height against airborne targets
local bmo = bot.realmo
local bmoz = AdjustedZ(bmo, bmo) * flip
local targetz = AdjustedZ(bmo, target) * flip
local targetgrounded = P_IsObjectOnGround(target)
and (bmo.eflags & MFE_VERTICALFLIP) == (target.eflags & MFE_VERTICALFLIP)
local maxtargetz_height = maxtargetz
if not targetgrounded
maxtargetz_height = $ + bmo.height
end
--Decide whether to engage target or not
if ttype == 1 --Active target, take more risks
if bot.charability2 == CA2_GUNSLINGER
and not (bot.pflags & (PF_JUMPED | PF_BOUNCING))
and abs(targetz - bmoz) > 200 * FRACUNIT
return 0
elseif bot.charability == CA_FLY
and (bot.pflags & PF_THOKKED)
and bmo.state >= S_PLAY_FLY
and bmo.state <= S_PLAY_FLY_TIRED
and (
targetz - bmoz < -maxtargetz
or (
(target.flags & (MF_BOSS | MF_ENEMY))
and (
(bmo.eflags & MFE_UNDERWATER)
or targetgrounded
)
)
)
return 0 --Flying characters should ignore enemies below them
elseif bot.powers[pw_carry]
and abs(targetz - bmoz) > maxtargetz
return 0 --Don't divebomb every target when being carried
elseif targetz - bmoz > maxtargetz_height
and (
bot.charability != CA_FLY
or (bmo.eflags & MFE_UNDERWATER)
or targetgrounded
)
return 0
elseif abs(targetz - bmoz) > maxtargetdist
return 0
elseif bot.powers[pw_carry] == CR_MINECART
return 0 --Don't attack from minecarts
elseif target.cd_lastattacker
and target.info.cd_aispinattack
and target.height * flip + targetz - bmoz < 0
return 0 --Don't engage spin-attack targets above their own height
elseif bmo.tracer
and bot.powers[pw_carry] == CR_ROLLOUT
--Limit range when rolling around
maxtargetdist = $ / 16 + bmo.tracer.radius
bpx = bmo.x
bpy = bmo.y
elseif bot.powers[pw_carry]
--Limit range when being carried
maxtargetdist = $ / 4
bpx = bmo.x
bpy = bmo.y
elseif bot.charability == CA_FLY
and targetz - bmoz > maxtargetz_height
and (
not (
(bot.pflags & PF_THOKKED)
and bmo.state >= S_PLAY_FLY
and bmo.state <= S_PLAY_FLY_TIRED
)
or bmo.momz * flip < 0
)
--Limit range when fly-attacking, unless already flying and rising
maxtargetdist = $ / 2
bpx = bmo.x
bpy = bmo.y
elseif target.cd_lastattacker
and target.cd_lastattacker.player == bot
--Limit range on active self-tagged CoopOrDie targets
if target.cd_frettime
and target == bot.ai.target
return 0 --Switch targets if recently merped
end
ttype = 3 --Rank lower than passive targets
maxtargetdist = $ / 4
bpx = bmo.x
bpy = bmo.y
end
else --Passive target, play it safe
if bot.powers[pw_carry]
return 0
elseif bot.quittime
return 0 --Can't grab most passive things while disconnecting
elseif abs(targetz - bmoz) > maxtargetz_height
and not (bot.ai.drowning and target.type == MT_EXTRALARGEBUBBLE)
return 0
elseif target.cd_lastattacker
and target.cd_lastattacker.player == bot
return 0 --Don't engage passive self-tagged CoopOrDie targets
end
end
--Calculate distance to target, only allowing targets in range
local dist = R_PointToDist2(
--Add momentum to "prefer" targets in current direction
bpx + bmo.momx * 3,
bpy + bmo.momy * 3,
target.x,
target.y
)
if dist > maxtargetdist + bmo.radius + target.radius
return 0
end
--Attempt to prioritize priority CoopOrDie targets
if target.cd_lastattacker
and target.cd_lastattacker.player != bot
and target.info.cd_aipriority
ttype = -1
--Also attempt to prioritize Chaos Mode objectives
elseif target.info.spawntype == "target"
ttype = -1
end
return ttype, dist
end
--Update our last seen position
local function UpdateLastSeenPos(bai, pmo)
bai.lastseenpos.x = pmo.x - pmo.momx
bai.lastseenpos.y = pmo.y - pmo.momy
bai.lastseenpos.z = pmo.z - pmo.momz
end
--Drive bot based on whatever unholy mess is in this function
--This is the "WhatToDoNext" entry point for all AI actions
local function PreThinkFrameFor(bot)
if not bot.valid
return
end
--Find a new leader if ours quit
local bai = bot.ai
if not (bai and bai.leader and bai.leader.valid)
--Reset to realleader if we have one
if bai and bai.leader != bai.realleader
and bai.realleader and bai.realleader.valid
bai.leader = bai.realleader
return
end
--Otherwise find a new leader
--Pick a random leader if default is invalid
local bestleader = CV_AIDefaultLeader.value
if bestleader < 0 or bestleader > 31
or not (players[bestleader] and players[bestleader].valid)
or players[bestleader] == bot
bestleader = -1
for player in players.iterate
if not player.ai --Inspect top leaders only
and not player.quittime --Avoid disconnecting players
and GetTopLeader(player, bot) != bot --Also infers player != bot as base case
--Prefer higher-numbered players to spread out bots more
and (bestleader < 0 or P_RandomByte() < 128)
bestleader = #player
end
end
end
--Follow the bottom feeder of the leader chain
if bestleader > -1
bestleader = #GetBottomFollower(players[bestleader])
end
SetBot(bot, bestleader)
return
end
--Already think this frame?
if bai.think_last == leveltime
return
end
bai.think_last = leveltime
--Make sure AI leader thinks first
local leader = bai.leader
if leader.ai
and leader.ai.think_last != leveltime --Shortcut
PreThinkFrameFor(leader)
end
--Reset leader to realleader if it's no longer valid or spectating
--(we'll naturally find a better leader above if it's no longer valid)
if leader != bai.realleader
and (
not (bai.realleader and bai.realleader.valid)
or not bai.realleader.spectator
)
bai.leader = bai.realleader
return
end
--Is leader spectating? Temporarily follow leader's leader
if leader.spectator
and leader.ai
and leader.ai.leader
and leader.ai.leader.valid
and GetTopLeader(leader.ai.leader, leader) != leader
bai.leader = leader.ai.leader
return
end
--Handle rings here
local isspecialstage = G_IsSpecialStage()
if not isspecialstage
--Syncing rings?
if CV_AIStatMode.value & 1 == 0
--Remember our "real" ring count if newly synced
if not bai.syncrings
bai.syncrings = true
bai.realrings = bot.rings
bai.realxtralife = bot.xtralife
end
--Keep rings if leader spectating (still reset on respawn)
if leader.spectator
and leader.rings != bai.lastrings
leader.rings = bai.lastrings
end
--Sync those rings!
if bot.rings != bai.lastrings
P_GivePlayerRings(leader, bot.rings - bai.lastrings)
end
bot.rings = leader.rings
--Oops! Fix awarding extra extra lives
bot.xtralife = leader.xtralife
--Restore our "real" ring count if no longer synced
elseif bai.syncrings
bai.syncrings = false
bot.rings = bai.realrings
bot.xtralife = bai.realxtralife
end
bai.lastrings = bot.rings
--Syncing lives?
if CV_AIStatMode.value & 2 == 0
--Remember our "real" life count if newly synced
if not bai.synclives
bai.synclives = true
bai.reallives = bot.lives
end
--Sync those lives!
if bot.lives > bai.lastlives
and bot.lives > leader.lives
P_GivePlayerLives(leader, bot.lives - bai.lastlives)
if leveltime
P_PlayLivesJingle(leader)
end
end
if bot.lives > 0
bot.lives = max(leader.lives, 1)
else
bot.lives = leader.lives
end
--Restore our "real" life count if no longer synced
elseif bai.synclives
bai.synclives = false
bot.lives = bai.reallives
if bot.lives < 1 and not bot.spectator
bot.playerstate = PST_REBORN
end
end
bai.lastlives = bot.lives
end
--****
--VARS (Player or AI)
local bmo = bot.realmo
local pmo = leader.realmo
local cmd = bot.cmd
if not (bmo and bmo.valid and pmo and pmo.valid)
return
end
--Handle shield loss here if ai_hurtmode off
if bai.loseshield
if not bot.powers[pw_shield]
bai.loseshield = nil
elseif (leveltime + bai.timeseed) % TICRATE == 0
bai.loseshield = nil --Make sure we only try once
P_RemoveShield(bot)
S_StartSound(bmo, sfx_corkp)
end
end
--Check line of sight to player
if CheckSight(bmo, pmo)
bai.playernosight = 0
UpdateLastSeenPos(bai, pmo)
else
bai.playernosight = $ + 1
end
--Check leader's teleport status
if leader.ai
bai.playernosight = max($, leader.ai.playernosight - TICRATE / 2)
bai.panicjumps = max($, leader.ai.panicjumps - 1)
end
--And teleport if necessary
bai.doteleport = bai.playernosight > 3 * TICRATE
or bai.panicjumps > 3
if bai.doteleport and Teleport(bot, true)
--Post-teleport cleanup
bai.doteleport = false
bai.playernosight = 0
bai.panicjumps = 0
bai.anxiety = 0
bai.panic = 0
end
--Check for player input!
--If we have any, override ai for a few seconds
--Check leveltime as cmd always has input at level start
if leveltime and (
cmd.forwardmove
or cmd.sidemove
or cmd.buttons
)
if not bai.cmd_time
Repossess(bot)
--Unset ronin as client must have reconnected
--(unfortunately PlayerJoin does not fire for rejoins)
bai.ronin = false
--Terminate AI to avoid interfering with normal SP bot stuff
--Otherwise AI may take control again too early and confuse things
--(We won't get another AI until a valid BotTiccmd is generated)
if bot.bot
DestroyAI(bot)
return
end
end
bai.cmd_time = 8 * TICRATE
end
if bai.cmd_time > 0
bai.cmd_time = $ - 1
--Hold cmd_time if AI is off
if CV_ExAI.value == 0
bai.cmd_time = 3 * TICRATE
end
--Teleport override?
if bai.doteleport and CV_AITeleMode.value > 0
cmd.buttons = $ | CV_AITeleMode.value
end
return
end
--Bail here if AI is off (allows logic above to flow normally)
if CV_ExAI.value == 0
--Just trigger cmd_time logic next tic, without the setup
--(also means this block only runs once)
bai.cmd_time = 3 * TICRATE
--Make sure SP bot AI is destroyed
if bot.bot
DestroyAI(bot)
end
return
end
--****
--VARS (AI-specific)
local pcmd = leader.cmd
--Elements
local flip = 1
if bmo.eflags & MFE_VERTICALFLIP
flip = -1
end
local _2d = twodlevel or (bmo.flags2 & MF2_TWOD)
local scale = bmo.scale
local touchdist = bmo.radius + pmo.radius
if bmo.tracer
touchdist = $ + bmo.tracer.radius
end
if pmo.tracer
touchdist = $ + pmo.tracer.radius
end
--Measurements
local ignoretargets = CV_AIIgnore.value
local pmom = FixedHypot(pmo.momx, pmo.momy)
local bmom = FixedHypot(bmo.momx, bmo.momy)
local pmoz = AdjustedZ(bmo, pmo) * flip
local bmoz = AdjustedZ(bmo, bmo) * flip
local pmomang = R_PointToAngle2(0, 0, pmo.momx, pmo.momy)
local bmomang = R_PointToAngle2(0, 0, bmo.momx, bmo.momy)
local pspd = leader.speed
local bspd = bot.speed
local dist = R_PointToDist2(bmo.x, bmo.y, pmo.x, pmo.y)
local zdist = pmoz - bmoz
local predictfloor = PredictFloorOrCeilingZ(bmo, 1) * flip
local ang = bmo.angle --Used for climbing etc.
local followmax = touchdist + 1024 * scale --Max follow distance before AI begins to enter "panic" state
local followthres = touchdist + 92 * scale --Distance that AI will try to reach
local followmin = touchdist + 32 * scale
local bmofloor = FloorOrCeilingZ(bmo, bmo) * flip
local pmofloor = FloorOrCeilingZ(bmo, pmo) * flip
local jumpheight = FixedMul(bot.jumpfactor, 96 * scale)
local ability = bot.charability
local ability2 = bot.charability2
local falling = bmo.momz * flip < 0
local isjump = bot.pflags & PF_JUMPED --Currently jumping
local isabil = bot.pflags & (PF_THOKKED | PF_GLIDING | PF_BOUNCING) --Currently using ability
local isspin = bot.pflags & PF_SPINNING --Currently spinning
local isdash = bot.pflags & PF_STARTDASH --Currently charging spindash
local bmogrounded = P_IsObjectOnGround(bmo) and not (bot.pflags & PF_BOUNCING) --Bot ground state
local pmogrounded = P_IsObjectOnGround(pmo) --Player ground state
local dojump = 0 --Signals whether to input for jump
local doabil = 0 --Signals whether to input for jump ability. Set -1 to cancel.
local dospin = 0 --Signals whether to input for spinning
local dodash = 0 --Signals whether to input for spindashing
local stalled = bai.move_last --AI is having trouble catching up
and (bmom < scale or (bspd > bmom and bmom < 2 * scale))
local targetdist = CV_AISeekDist.value * scale --Distance to seek enemy targets (reused as actual target dist later)
local targetz = 0 --Filled in later if target
local minspeed = 8 * scale --Minimum speed to spin or adjust combat jump range
local pmag = FixedHypot(pcmd.forwardmove * FRACUNIT, pcmd.sidemove * FRACUNIT)
local bmosloped = bmo.standingslope and AbsAngle(bmo.standingslope.zangle) > ANGLE_11hh
--Are we spectating?
if bot.spectator
--Allow bots to respawn in special stages when AI-controlled
--Otherwise they just die immediately in later stages
if isspecialstage and leader.nightstime > 0
and not (leader.outofcoop or leader.spectator)
and not (bmo.flags & MF_NOGRAVITY)
and pmo.health > 0
--Brute force special stage respawn rules
bot.exiting = 0
bot.spectator = false
bot.outofcoop = false
bot.playerstate = PST_LIVE
bot.nightstime = leader.nightstime * 3/4
Teleport(bot, false)
return
end
--Do spectator stuff
cmd.forwardmove,
cmd.sidemove = DesiredMove(bmo, pmo, dist, followthres * 2, FixedSqrt(dist) * 2, 0, bmogrounded, isspin, _2d)
if abs(zdist) > followthres * 2
or (bai.jump_last and abs(zdist) > followthres)
if zdist * flip < 0
cmd.buttons = $ | BT_USE
bai.jump_last = 1
else
cmd.buttons = $ | BT_JUMP
bai.jump_last = 1
end
else
bai.jump_last = 0
end
bmo.angle = R_PointToAngle2(bmo.x, bmo.y, pmo.x, pmo.y)
bot.aiming = R_PointToAngle2(0, bmo.z + bmo.height / 2,
dist + 32 * FRACUNIT, pmo.z + pmo.height / 2)
--Maybe press fire to join match? e.g. Chaos Mode
if (leveltime + bai.timeseed) % TICRATE == 0
cmd.buttons = $ | BT_ATTACK
end
--Debug
if CV_AIDebug.value > -1
and CV_AIDebug.value == #bot
hudtext[1] = "dist " + dist / scale
hudtext[2] = "zdist " + zdist / scale
hudtext[3] = "FM " + cmd.forwardmove + " SM " + cmd.sidemove
hudtext[4] = "Jmp " + (cmd.buttons & BT_JUMP) / BT_JUMP + " Spn " + (cmd.buttons & BT_USE) / BT_USE
hudtext[5] = "leader " + #bai.leader + " - " + bai.leader.name
if bai.leader != bai.realleader and bai.realleader and bai.realleader.valid
hudtext[5] = $ + " (realleader " + #bai.realleader + " - " + bai.realleader.name + ")"
end
hudtext[6] = nil
end
return
end
--followmin shrinks when airborne to help land
if not bmogrounded
and not bot.powers[pw_carry] --But not on vehicles
followmin = touchdist / 2
end
--If we're a valid ai, optionally keep us around on diconnect
--Note that this requires rejointimeout to be nonzero
--They will stay until kicked or no leader available
--(or until player rejoins, disables ai, and leaves again)
if bot.quittime and CV_AIKeepDisconnected.value
bot.quittime = 0 --We're still here!
bot.ai.ronin = true --But we have no master
end
--Set a few flags AI expects - no analog or autobrake, but do use dchar
bot.pflags = $
& ~PF_ANALOGMODE
| PF_DIRECTIONCHAR
& ~PF_AUTOBRAKE
--Predict platforming
-- 1 = predicted gap
-- 2 = predicted low floor relative to leader
-- 3 = both
-- 4 = jumping out of special stage badness
if not isjump
bai.predictgap = 0
end
if bmom > scale and abs(predictfloor - bmofloor) > 24 * scale
bai.predictgap = $ | 1
end
if zdist > -32 * scale and predictfloor - pmofloor < -jumpheight
bai.predictgap = $ | 2
else
bai.predictgap = $ & ~2
end
if isspecialstage
and (bmo.eflags & (MFE_TOUCHWATER | MFE_UNDERWATER))
bai.predictgap = $ | 4
end
if stalled
bai.stalltics = $ + 1
else
bai.stalltics = 0
end
--Target ranging - average of bot and leader position
--This technically allows up to 1.5x max target range
local bpx = (bmo.x - pmo.x) / 2 + pmo.x --Can't avg via addition as it may overflow
local bpy = (bmo.y - pmo.y) / 2 + pmo.y
--Minecart!
if bot.powers[pw_carry] == CR_MINECART
or leader.powers[pw_carry] == CR_MINECART
--Remain calm, possibly finding another minecart
if bot.powers[pw_carry] == CR_MINECART
bai.playernosight = 0
bai.stalltics = 0
end
bai.anxiety = 0
bai.panic = 0
bpx = bmo.x --Search nearby
bpy = bmo.y
end
--Determine whether to fight
if bai.thinkfly
targetdist = $ / 8
end
if bai.panic or bai.spinmode or bai.flymode
or bai.targetnosight > 2 * TICRATE --Implies valid target (or waypoint)
or bai.targetjumps > 3
bai.target = nil
bai.targetcount = 0
bai.targetjumps = 0
elseif not ValidTarget(bot, leader, bpx, bpy, bai.target, targetdist, jumpheight, flip, ignoretargets, isspecialstage)
bai.targetcount = 0
bai.targetjumps = 0
--If we had a previous target, just reacquire a new one immediately
--Otherwise, spread search calls out a bit across bots, based on playernum
if bai.target
or (
(leveltime + #bot) % (TICRATE / 2) == 0
and pspd < leader.runspeed
)
--For chains, prefer targets closest to us instead of avg point
--But only if we're within max target range
if bai.target
and dist < targetdist * 3/2 --Avg pos allows up to 1.5x range
bpx = bmo.x
bpy = bmo.y
end
--Gunslingers reset overheat on new target
if ability2 == CA2_GUNSLINGER
bai.attackoverheat = 0
end
--Begin the search!
bai.target = nil
if ignoretargets < 3 or bai.bored
local besttype = 255
local bestdist = targetdist
searchBlockmap(
"objects",
function(bmo, mo)
local ttype, tdist = ValidTarget(bot, leader, bpx, bpy, mo, targetdist, jumpheight, flip, ignoretargets, isspecialstage)
if ttype and CheckSight(bmo, mo)
if ttype < besttype
or (ttype == besttype and tdist < bestdist)
besttype = ttype
bestdist = tdist
bai.target = mo
end
if mo.flags & (MF_BOSS | MF_ENEMY)
bai.targetcount = $ + 1
end
end
end, bmo,
bpx - targetdist, bpx + targetdist,
bpy - targetdist, bpy + targetdist
)
--Always bop leader if they need it
elseif ValidTarget(bot, leader, bpx, bpy, pmo, targetdist, jumpheight, flip, ignoretargets, isspecialstage)
and CheckSight(bmo, pmo)
bai.target = pmo
end
end
end
--Waypoint! Attempt to negotiate corners
if bai.playernosight
if not (bai.waypoint and bai.waypoint.valid)
bai.waypoint = P_SpawnMobj(bai.lastseenpos.x, bai.lastseenpos.y, bai.lastseenpos.z, MT_FOXAI_POINT)
--bai.waypoint.state = S_LOCKON3
bai.waypoint.ai_type = 1
end
elseif bai.waypoint
bai.waypoint = DestroyObj($)
end
--Determine movement
if bai.target --Above checks infer bai.target.valid
--Check target sight
if CheckSight(bmo, bai.target)
bai.targetnosight = 0
else
bai.targetnosight = $ + 1
end
--Used in fight logic later
targetdist = R_PointToDist2(bmo.x, bmo.y, bai.target.x, bai.target.y)
targetz = AdjustedZ(bmo, bai.target) * flip
--Override our movement and heading to intercept
--Avoid self-tagged CoopOrDie targets (kinda fudgy and ignores waypoints, but gets us away)
if bai.target.cd_lastattacker
and bai.target.cd_lastattacker.player == bot
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, pmo, dist, followmin, 0, pmag, bmogrounded, isspin, _2d)
else
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, bai.target, targetdist, 0, 0, 0, bmogrounded, isspin, _2d)
end
bmo.angle = R_PointToAngle2(bmo.x - bmo.momx, bmo.y - bmo.momy, bai.target.x, bai.target.y)
bot.aiming = R_PointToAngle2(0, bmo.z - bmo.momz + bmo.height / 2,
targetdist + 32 * FRACUNIT, bai.target.z + bai.target.height / 2)
--Waypoint!
elseif bai.waypoint
--Check waypoint sight
if CheckSight(bmo, bai.waypoint)
bai.targetnosight = 0
else
bai.targetnosight = $ + 1
end
--dist eventually recalculates as a total path length (left partial here for aiming vector)
--zdist just gets overwritten so we ascend/descend appropriately
dist = R_PointToDist2(bmo.x, bmo.y, bai.waypoint.x, bai.waypoint.y)
zdist = AdjustedZ(bmo, bai.waypoint) * flip - bmoz
--Divert through the waypoint
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, bai.waypoint, dist, 0, 0, 0, bmogrounded, isspin, _2d)
bmo.angle = R_PointToAngle2(bmo.x - bmo.momx, bmo.y - bmo.momy, bai.waypoint.x, bai.waypoint.y)
bot.aiming = R_PointToAngle2(0, bmo.z - bmo.momz + bmo.height / 2,
dist + 32 * FRACUNIT, bai.waypoint.z + bai.waypoint.height / 2)
--Check distance to waypoint, updating if we've reached it (may help path to leader)
if FixedHypot(dist, zdist) < touchdist
UpdateLastSeenPos(bai, pmo)
P_TeleportMove(bai.waypoint, bai.lastseenpos.x, bai.lastseenpos.y, bai.lastseenpos.z)
--bai.waypoint.state = S_LOCKON4
bai.waypoint.ai_type = 0
else
--Finish the dist calc
dist = $ + R_PointToDist2(bai.waypoint.x, bai.waypoint.y, pmo.x, pmo.y)
end
else
--Clear target / waypoint sight
bai.targetnosight = 0
--Lead target if going super fast (and we're close or target behind us)
local leaddist = 0
if bspd > leader.normalspeed + pmo.scale and pspd > pmo.scale
and (dist < followthres or AbsAngle(bmomang - bmo.angle) > ANGLE_90)
leaddist = followmin + dist + (pmom + bmom) * 2
--Reduce minimum distance if moving away (so we don't fall behind moving too late)
elseif dist < followmin and pmom > bmom
and AbsAngle(pmomang - bmo.angle) < ANGLE_135
and not bot.powers[pw_carry] --But not on vehicles
followmin = 0 --Distance remains natural due to pmom > bmom check
end
--Normal follow movement and heading
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, pmo, dist, followmin, leaddist, pmag, bmogrounded, isspin, _2d)
bmo.angle = R_PointToAngle2(bmo.x - bmo.momx, bmo.y - bmo.momy, pmo.x, pmo.y)
bot.aiming = R_PointToAngle2(0, bmo.z - bmo.momz + bmo.height / 2,
dist + 32 * FRACUNIT, pmo.z + pmo.height / 2)
end
--Check water
bai.drowning = 0
if bmo.eflags & MFE_UNDERWATER
followmax = $ / 2
if bot.powers[pw_underwater] > 0
and bot.powers[pw_underwater] < 16 * TICRATE
bai.drowning = 1
if bot.powers[pw_underwater] < 8 * TICRATE
or WaterTopOrBottom(bmo, bmo) * flip - bmoz < jumpheight + bmo.height / 2
bai.drowning = 2
end
end
end
--Check anxiety
if bai.bored
bai.anxiety = 0
bai.panic = 0
elseif dist > followmax --Too far away
or (zdist > jumpheight --Too low w/o enemy
and (not bai.target or bai.target.player))
or bai.stalltics > TICRATE / 2 --Something in my way!
bai.anxiety = min($ + 2, 2 * TICRATE)
if bai.anxiety >= 2 * TICRATE
bai.panic = 1
end
elseif not isjump or zdist <= 0
bai.anxiety = max($ - 1, 0)
bai.panic = 0
end
--Over a pit / in danger w/o enemy
if falling and zdist > 0
and bmofloor < bmoz - jumpheight * 2
and (not bai.target or bai.target.player)
and FixedHypot(dist, zdist) > followthres * 2
and not bot.powers[pw_carry]
bai.panic = 1
bai.anxiety = 2 * TICRATE
end
--Carry pre-orientation (to avoid snapping leader's camera around)
if (bot.pflags & PF_CANCARRY) and dist < touchdist * 2
cmd.angleturn = pcmd.angleturn
bmo.angle = pmo.angle
end
--Being carried?
if bot.powers[pw_carry]
bot.pflags = $ | PF_DIRECTIONCHAR --This just looks nicer
--Override orientation on minecart
if bot.powers[pw_carry] == CR_MINECART and bmo.tracer
bmo.angle = bmo.tracer.angle
end
--Aaahh!
if bot.powers[pw_carry] == CR_PTERABYTE
cmd.forwardmove = P_RandomRange(-50, 50)
cmd.sidemove = P_RandomRange(-50, 50)
if bai.jump_last
doabil = -1
else
dojump = 1
doabil = 1
end
end
--Fix silly ERZ zoom tube bug
if bot.powers[pw_carry] == CR_ZOOMTUBE
bai.zoom_last = true --Temporary flag
end
--Override vertical aim if we're being carried by leader
--(so we're not just staring at the sky looking up - in fact, angle down a bit)
if bmo.tracer == pmo and not bai.target
bot.aiming = R_PointToAngle2(0, 16 * FRACUNIT, 32 * FRACUNIT, bmo.momz)
end
--Jump for targets!
if bai.target and bai.target.valid and not bai.target.player
dojump = 1
--Maybe ask AI carrier to descend
--Or simply let go of a pulley
elseif zdist < -jumpheight
doabil = -1
--Maybe carry leader again if they're tired?
elseif ability == CA_FLY
and bmo.tracer == pmo and bmom < minspeed * 2
and leader.powers[pw_tailsfly] < TICRATE / 2
and falling
and not (bmo.eflags & MFE_GOOWATER)
dojump = 1
bai.flymode = 1
end
--Fix silly ERZ zoom tube bug
elseif bai.zoom_last
cmd.forwardmove = 0
cmd.sidemove = 0
bai.zoom_last = nil
end
--Check boredom, carried down the leader chain
if leader.ai and leader.ai.bored
pmag = 0
bai.idlecount = max($, leader.ai.idlecount)
end
if pcmd.buttons == 0 and pmag == 0
and bmogrounded and (bai.bored or bspd < scale)
and not (bai.drowning or bai.panic)
bai.idlecount = $ + 2
--Aggressive bots get bored slightly faster
if ignoretargets < 3
bai.idlecount = $ + 1
end
else
bai.idlecount = 0
end
if bai.idlecount > 16 * TICRATE
bai.bored = 1
else
bai.bored = 0
end
--********
--FLY MODE (or super forms)
if dist < touchdist
--Carrying leader?
if pmo.tracer == bmo and leader.powers[pw_carry]
bai.flymode = 2
--Activate co-op flight
elseif bai.thinkfly == 1
and (leader.pflags & PF_JUMPED)
and (
pspd
or zdist > bmo.height / 2
or pmo.momz * flip < 0
)
dojump = 1
--Do superfly on gold arrow only (Tails AI toggles between them)
if bai.overlay and bai.overlay.valid
and bai.overlay.colorized
bai.flymode = 3
else
bai.flymode = 1
end
end
--Check positioning
--Thinker for co-op fly
if not (bai.bored or bai.drowning)
and dist < touchdist / 2
and abs(zdist) < (pmo.height + bmo.height) / 2
and bmogrounded and (pmogrounded or bai.thinkfly)
and not (leader.pflags & (PF_STASIS | PF_SPINNING))
and not (pspd or bspd)
and (ability == CA_FLY or SuperReady(bot))
bai.thinkfly = 1
else
bai.thinkfly = 0
end
--Ready for takeoff
if bai.flymode == 1
bai.thinkfly = 0
dojump = 1
--Make sure we're not too high up
if zdist < -pmo.height
doabil = -1
elseif falling
or pmo.momz * flip < 0
doabil = 1
end
bmo.angle = pmo.angle
--Abort if player moves away or spins
if --[[dist > touchdist or]] leader.dashspeed > 0
bai.flymode = 0
end
--Carrying; Read player inputs
elseif bai.flymode == 2
bai.thinkfly = 0
bot.pflags = $ | (leader.pflags & PF_AUTOBRAKE) --Use leader's autobrake settings
cmd.forwardmove = pcmd.forwardmove
cmd.sidemove = pcmd.sidemove
if pcmd.buttons & BT_USE
doabil = -1
else
doabil = 1
end
bmo.angle = pmo.angle
bot.aiming = R_PointToAngle2(0, 16 * FRACUNIT, 32 * FRACUNIT, bmo.momz)
--End flymode
if not leader.powers[pw_carry]
bai.flymode = 0
end
--Super!
elseif bai.flymode == 3
bai.thinkfly = 0
if zdist > -32 * scale
dojump = 1
end
if bot.powers[pw_shield] & SH_NOSTACK
S_StartSound(bmo, sfx_shldls)
P_RemoveShield(bot)
bot.powers[pw_flashing] = max($, TICRATE)
end
if falling
dodash = 1
bai.flymode = 0
end
end
else
bai.flymode = 0
bai.thinkfly = 0
end
--********
--SPINNING
if ability2 == CA2_SPINDASH
and not (bai.panic or bai.flymode or bai.target)
and (leader.pflags & PF_SPINNING)
and (isdash or not (leader.pflags & PF_JUMPED))
--Spindash
if leader.dashspeed > 0
if dist > touchdist and not isdash --Do positioning
--Same as our normal follow DesiredMove but w/ no mindist / leaddist / minmag
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, pmo, dist, 0, 0, 0, bmogrounded, isspin, _2d)
bai.spinmode = 0
elseif leader.dashspeed > leader.maxdash / 4
bot.pflags = $ | PF_AUTOBRAKE
cmd.forwardmove = 0
cmd.sidemove = 0
bmo.angle = pmo.angle
dodash = 1
bai.spinmode = 1
else --Delay until ready to spin
bai.spinmode = 1
end
--Spin
else
--Keep angle from dash on initial spin frame
--(So we don't rocket off in some random direction)
if isdash
bmo.angle = pmo.angle
--Jump-cancel this frame?
if leader.pflags & PF_JUMPED
dojump = 1
end
end
if bspd > minspeed
and AbsAngle(bmomang - bmo.angle) < ANGLE_22h
dospin = 1
end
bai.spinmode = 1
end
else
bai.spinmode = 0
end
--Leader pushing against something? Attack it!
--Here so we can override spinmode
--Also carry this down the leader chain if one exists
--Or a spectating leader holding spin against the ground
if (leader.ai and leader.ai.pushtics > TICRATE / 8)
or (leader.spectator and (pcmd.buttons & BT_USE))
pmag = 50 * FRACUNIT
end
if pmag > 45 * FRACUNIT and pspd < pmo.scale / 2
and not bai.flymode
if bai.pushtics > TICRATE / 2
if dist > touchdist --Do positioning
--Same as spinmode above
cmd.forwardmove, cmd.sidemove =
DesiredMove(bmo, pmo, dist, 0, 0, 0, bmogrounded, isspin, _2d)
bai.targetnosight = 3 * TICRATE --Recall bot from any target
else
--Helpmode!
bai.target = pmo
targetdist = dist
targetz = zdist
--Stop and aim at what we're aiming at
bot.pflags = $ | PF_AUTOBRAKE
cmd.forwardmove = 0
cmd.sidemove = 0
bmo.angle = pmo.angle
bot.pflags = $ & ~PF_DIRECTIONCHAR --Ensure accurate melee
--Spin! Or melee etc.
if pmogrounded
and ability2 != CA2_GUNSLINGER
dodash = 1
--Tap key for non-spin characters
if ability2 != CA2_SPINDASH
and bai.spin_last
dodash = 0
end
--Do ability
else
dojump = 1
doabil = 1
cmd.forwardmove = 50
cmd.sidemove = 0
end
bai.spinmode = 1 --Lock behavior
end
else
bai.pushtics = $ + 1
end
elseif bai.pushtics > 0
if isspin
if isdash
bmo.angle = pmo.angle
elseif bmom
bmo.angle = bmomang
dospin = 1
end
bai.spinmode = 1 --Lock behavior
end
if isabil
if bmom
bmo.angle = bmomang
end
doabil = 1
cmd.forwardmove = 50
cmd.sidemove = 0
bai.spinmode = 1 --Lock behavior
end
bai.pushtics = $ - 1
end
--Are we pushing against something?
if bmogrounded
and bai.stalltics > TICRATE / 2
and bai.stalltics < TICRATE * 3/4
and ability2 != CA2_GUNSLINGER
dodash = 1
end
--******
--FOLLOW
if not (bai.flymode or bai.spinmode or bai.target or bot.climbing)
--Bored
if bai.bored
local idle = (bai.idlecount + bai.timeseed) * 17 / TICRATE
local b1 = 256|128|64
local b2 = 128|64
local b3 = 64
local imirror = 1
if bai.timeseed & 1 --Odd timeseeds idle in reverse direction
imirror = -1
end
cmd.forwardmove = 0
cmd.sidemove = 0
if idle & b1 == b1
cmd.forwardmove = 35
bmo.angle = $ + ANGLE_270 * imirror
elseif idle & b2 == b2
cmd.forwardmove = 25
bmo.angle = $ + ANGLE_67h * imirror
elseif idle & b3 == b3
cmd.forwardmove = 15
bmo.angle = $ + ANGLE_337h * imirror
else
bmo.angle = idle * (ANG1 * imirror / 2)
end
--Too far
elseif bai.panic or dist > followthres
if CV_AICatchup.value and dist > followthres * 2
and not bot.powers[pw_sneakers]
bot.powers[pw_sneakers] = 2
end
--Water panic?
elseif bai.drowning
and dist < followmin
local imirror = 1
if bai.timeseed & 1 --Odd timeseeds panic in reverse direction
imirror = -1
end
bmo.angle = $ + ANGLE_45 * imirror
cmd.forwardmove = 50
--Hit the brakes?
elseif dist < touchdist
bot.pflags = $ | PF_AUTOBRAKE
end
end
--*********
--JUMP
if not (bai.flymode or bai.spinmode or bai.target or isdash)
--Start jump
if (zdist > 32 * scale and (leader.pflags & PF_JUMPED)) --Following
or (zdist > 64 * scale and bai.panic) --Vertical catch-up
or (stalled and not bmosloped
and pmofloor - bmofloor > 24 * scale)
or bai.stalltics > TICRATE
or (isspin and not isjump and bmom
and (bspd <= max(minspeed, bot.normalspeed / 2)
or AbsAngle(bmomang - bmo.angle) > ANGLE_157h)) --Spinning
or ((bai.predictgap & 3 == 3) --Jumping a gap w/ low floor rel. to leader
and not bot.powers[pw_carry]) --Not in carry state
or (bai.predictgap & 4) --Jumping out of special stage water
or bai.drowning == 2
dojump = 1
--Force ability getting out of special stage water
if falling and (bai.predictgap & 4)
doabil = 1
end
--Count panicjumps
if bmogrounded and not (isjump or isabil)
if bai.panic
bai.panicjumps = $ + 1
else
bai.panicjumps = 0
end
end
--Hold jump
elseif isjump and (zdist > 0 or bai.panic or bai.predictgap or stalled)
and not bot.powers[pw_carry] --Don't freak out on maces
dojump = 1
end
--********
--ABILITIES
if not bai.target
--Thok / Super Float
if ability == CA_THOK
if bot.actionspd > bspd * 3/2
and (
(bai.panic and abs(zdist) < jumpheight * 2)
or dist > followmax / 2
)
dojump = 1
if falling or dist > followmax
--Mix in fire shield half the time
if bot.powers[pw_shield] == SH_FLAMEAURA
and BotTime(bai, 1, 2)
dodash = 1
else
doabil = 1
end
end
end
--Super? Use the special float ability in midair too
local isspinabil = isjump and bai.spin_last
if bot.powers[pw_super]
and (isspinabil or bai.panic)
if zdist > jumpheight
or (zdist > 0 and (falling or isspinabil))
or (bai.predictgap & 2)
dojump = 1
if falling or isspinabil
dodash = 1
end
end
end
--Fly
elseif ability == CA_FLY
and (isabil or bai.panic or bai.drowning == 2)
if zdist > jumpheight
or (zdist > 0 and (falling or isabil))
or bai.drowning == 2
or (bai.predictgap & 2) --Flying over low floor rel. to leader
dojump = 1
if falling or isabil
doabil = 1
end
elseif zdist < -jumpheight * 2
or (pmogrounded and dist < followthres and zdist < 0)
or (bmo.eflags & MFE_GOOWATER)
doabil = -1
end
--Glide and climb / Float / Pogo Bounce
elseif (ability == CA_GLIDEANDCLIMB or ability == CA_FLOAT or ability == CA_BOUNCE)
and (isabil or bai.panic)
if zdist > jumpheight
or (zdist > 0 and (falling or isabil))
or (bai.predictgap & 2)
or (
ability != CA_FLOAT
and dist > followmax
and (
ability == CA_BOUNCE
or bai.playernosight > TICRATE / 2
)
)
dojump = 1
if falling or isabil
doabil = 1
end
end
if ability == CA_GLIDEANDCLIMB
and isabil and not bot.climbing
and (dist < followthres or zdist > followmax / 2)
bmo.angle = pmo.angle --Match up angles for better wall linking
end
end
--Why not fire shield?
if not (doabil or isabil)
and bot.powers[pw_shield] == SH_FLAMEAURA
and (
(bai.panic and abs(zdist) < jumpheight * 2)
or dist > followmax / 2
)
dojump = 1
if falling or dist > followmax
dodash = 1 --Use shield ability
end
end
end
end
--Climb controls
if bot.climbing
local dmf = zdist
local dms = dist
local dmgd = pmogrounded
if bai.target
dmf = targetz - bmoz
dms = targetdist
dmgd = P_IsObjectOnGround(bai.target)
end
--Don't wiggle around if target's off the wall
if AbsAngle(bmo.angle - ang) < ANGLE_67h
or AbsAngle(bmo.angle - ang) > ANGLE_112h
dms = 0
--Shorthand for relative angles >= 180 - meaning, move left
elseif ang - bmo.angle < 0
dms = -$
end
if dmgd and AbsAngle(bmo.angle - ang) < ANGLE_67h
cmd.forwardmove = 50
cmd.sidemove = 0
elseif dmgd or FixedHypot(abs(dmf), abs(dms)) > touchdist
cmd.forwardmove = min(max(dmf / scale, -50), 50)
cmd.sidemove = min(max(dms / scale, -50), 50)
else
cmd.forwardmove = 0
cmd.sidemove = 0
end
if AbsAngle(ang - bmo.angle) > ANGLE_112h
and (
bai.target
or dist > followthres * 2
or zdist < -jumpheight
)
doabil = -1
end
--Hold our previous angle when climbing
bmo.angle = ang
end
--Emergency obstacle evasion!
if bai.waypoint
and bai.targetnosight > TICRATE
if BotTime(bai, 2, 4)
cmd.sidemove = 50
else
cmd.sidemove = -50
end
end
--Gun cooldown for Fang
if bot.panim == PA_ABILITY2
and (ability2 == CA2_GUNSLINGER or ability2 == CA2_MELEE)
bai.attackoverheat = $ + 1
if bai.attackoverheat > 2 * TICRATE
bai.attackwait = 1
--Wait a longer cooldown
if ability2 == CA2_MELEE
bai.attackoverheat = 4 * TICRATE
end
end
elseif bai.attackoverheat > 0
bai.attackoverheat = $ - 1
else
bai.attackwait = 0
end
--*******
--FIGHT
if bai.target and bai.target.valid
and not bai.pushtics --Don't do combat stuff for pushtics helpmode
local hintdist = 32 * scale --Magic value - absolute minimum attack range hint, zdists larger than this are also no longer considered for spin/melee
local maxdist = 256 * scale --Distance to catch up to.
local mindist = bai.target.radius + bmo.radius + hintdist --Distance to attack from. Gunslingers avoid getting this close
local targetfloor = FloorOrCeilingZ(bmo, bai.target) * flip
local attkey = BT_JUMP
local attack = 0
local attshield = (bai.target.flags & (MF_BOSS | MF_ENEMY))
and (bot.powers[pw_shield] == SH_ATTRACT
or (bot.powers[pw_shield] == SH_ARMAGEDDON and bai.targetcount > 4))
--Helpmode!
if bai.target.player
attkey = BT_USE
--Rings! And other collectibles
elseif (bai.target.type >= MT_RING and bai.target.type <= MT_FLINGBLUESPHERE)
or bai.target.type == MT_COIN or bai.target.type == MT_FLINGCOIN
or bai.target.type == MT_FIREFLOWER
or bai.target.type == MT_STARPOST
or bai.target.info.spawnstate == S_EMBLEM1 --Chaos Mode hack
--Run into them if within targetfloor vs character standing height
if bmogrounded
and targetz - targetfloor < P_GetPlayerHeight(bot)
attkey = -1
end
--Jump for air bubbles! Or vehicles etc.
elseif bai.target.type == MT_EXTRALARGEBUBBLE
or bai.target.type == MT_MINECARTSPAWNER
--Run into them if within height
if bmogrounded
and abs(targetz - bmoz) < bmo.height / 2
attkey = -1
end
--Avoid self-tagged CoopOrDie targets
elseif bai.target.cd_lastattacker
and bai.target.cd_lastattacker.player == bot
--Do nothing, default to jump
--Override if we have an offensive shield or we're rolling out
elseif attshield
or bai.target.type == MT_ROLLOUTROCK
--Do nothing, default to jump
--If we're invulnerable just run into stuff!
elseif bmogrounded
and (bot.powers[pw_invulnerability]
or bot.powers[pw_super]
or (bot.dashmode > 3 * TICRATE and (bot.charflags & SF_MACHINE)))
and (bai.target.flags & (MF_BOSS | MF_ENEMY))
and abs(targetz - bmoz) < bmo.height / 2
attkey = -1
--Fire flower hack
elseif (bot.powers[pw_shield] & SH_FIREFLOWER)
and (bai.target.flags & (MF_BOSS | MF_ENEMY | MF_MONITOR))
and targetdist > mindist
--Run into / shoot them if within height
if bmogrounded
and abs(targetz - bmoz) < bmo.height / 2
attkey = -1
end
if (leveltime + bai.timeseed) % (TICRATE / 4) == 0
cmd.buttons = $ | BT_ATTACK
end
--Gunslingers shoot from a distance
elseif ability2 == CA2_GUNSLINGER
if BotTime(bai, 31, 32) --Randomly (rarely) jump too
and bmogrounded and not bai.attackwait
and not bai.targetnosight
mindist = max($, abs(targetz - bmoz) * 3/2)
maxdist = max($ + mindist, 512 * scale)
attkey = BT_USE
end
--Melee only attacks on ground if it makes sense
elseif ability2 == CA2_MELEE
if BotTime(bai, 7, 8) --Randomly jump too
and bmogrounded and abs(targetz - bmoz) < hintdist
attkey = BT_USE --Otherwise default to jump below
mindist = $ + bmom * 3 --Account for <3 range
end
--But other no-jump characters always ground-attack
elseif bot.charflags & SF_NOJUMPDAMAGE
attkey = BT_USE
mindist = $ + bmom
--Finally jump characters randomly spin
elseif ability2 == CA2_SPINDASH
and (isspin or bmosloped or BotTime(bai, 1, 8)
--Always spin spin-attack enemies tagged in CoopOrDie
or (bai.target.cd_lastattacker --Inferred not us
and bai.target.info.cd_aispinattack))
and bmogrounded and abs(targetz - bmoz) < hintdist
attkey = BT_USE
mindist = $ + bmom * 16
--Slope hack (always want to dash)
if bmosloped
maxdist = $ + targetdist
end
--Min dash speed hack
if targetdist < maxdist
and bspd <= minspeed
and (isdash or not isspin)
mindist = $ + maxdist
--Halt!
bot.pflags = $ | PF_AUTOBRAKE
cmd.forwardmove = 0
cmd.sidemove = 0
end
end
--Don't do gunslinger stuff if jump-attacking etc.
if ability2 == CA2_GUNSLINGER and attkey != BT_USE
and not bai.attackwait --Gunslingers get special attackwait behavior
ability2 = nil
end
--Make sure we're facing the right way if stand-attacking
if attkey == BT_USE and bmogrounded
and (ability2 == CA2_GUNSLINGER or ability2 == CA2_MELEE)
and AbsAngle(bot.drawangle - bmo.angle) > ANGLE_22h
--Should correct us
mindist = 0
maxdist = 0
end
--Stay engaged if already jumped or spinning
if ability2 != CA2_GUNSLINGER
and (isjump or isabil or isspin) --isspin infers isdash
mindist = $ + targetdist
else
--Determine if we should commit to a longer jump
bai.longjump = targetdist > maxdist
or abs(targetz - bmoz) > jumpheight
or bmom <= minspeed / 2
end
--Range modification if momentum in right direction
if bmom and AbsAngle(bmomang - bmo.angle) < ANGLE_22h
mindist = $ + bmom * 8
--Jump attack should be further timed relative to movespeed
--Make sure we have a minimum speed for this as well
if attkey == BT_JUMP
and (isjump or bmom > minspeed / 2)
mindist = $ + bmom * 12
end
--Cancel spin if off course
elseif isspin and not isdash
dojump = 1
end
--Gunslingers gets special AI
if ability2 == CA2_GUNSLINGER
--Make Fang find another angle after shots
if bai.attackwait
dojump = 1
doabil = 1
cmd.forwardmove = 15
if BotTime(bai, 4, 8)
cmd.sidemove = 50
else
cmd.sidemove = -50
end
--Too close, back up!
elseif targetdist < mindist
if _2d
if bai.target.x < bmo.x
cmd.sidemove = 50
else
cmd.sidemove = -50
end
else
cmd.forwardmove = -50
end
--Leader might be blocking shot
elseif dist < followthres
and targetdist >= R_PointToDist2(pmo.x, pmo.y, bai.target.x, bai.target.y)
cmd.forwardmove = 15
if BotTime(bai, 4, 8)
cmd.sidemove = 30
else
cmd.sidemove = -30
end
--Fire!
else
attack = 1
--Halt!
bot.pflags = $ | PF_AUTOBRAKE
cmd.forwardmove = 0
cmd.sidemove = 0
end
--Other types just engage within mindist
elseif targetdist < mindist
attack = 1
--Hit the brakes?
if targetdist < bai.target.radius + bmo.radius
bot.pflags = $ | PF_AUTOBRAKE
end
end
--Attack
if attack
if attkey == BT_JUMP
and not isdash --Release charged dash first
if bmogrounded or bai.longjump
or targetfloor > bmofloor
or bai.target.height * 3/4 * flip + targetz - bmoz > 0
dojump = 1
--Count targetjumps
if bmogrounded and not (isjump or isabil)
bai.targetjumps = $ + 1
end
end
--Maybe fly-attack target
if ability == CA_FLY
and not bmogrounded
and (
bmo.state == S_PLAY_FLY --isabil would include shield abilities
or (bmo.state == S_PLAY_SWIM
and not (bai.target.flags & (MF_BOSS | MF_ENEMY)))
or (
(dist > touchdist or zdist < -pmo.height) --Avoid picking up leader
and targetz - bmoz > jumpheight + bmo.height
and not (
(bai.target.flags & (MF_BOSS | MF_ENEMY))
and (bmo.eflags & MFE_UNDERWATER)
)
)
)
if targetz - bmoz > bmo.height
doabil = 1
else
doabil = -1
end
--Use offensive shields
elseif attshield and (falling
or abs((hintdist * 2 + bai.target.height) * flip + targetz - bmoz) < hintdist)
and targetdist < RING_DIST --Lock range
dodash = 1 --Should fire the shield
--Bubble shield check!
elseif (bot.powers[pw_shield] == SH_ELEMENTAL
or bot.powers[pw_shield] == SH_BUBBLEWRAP)
and targetdist < bai.target.radius + bmo.radius
and bai.target.height * flip + targetz - bmoz < 0
and not (
--Don't ground-pound self-tagged CoopOrDie targets
bai.target.cd_lastattacker
and bai.target.cd_lastattacker.player == bot
and bot.powers[pw_shield] == SH_ELEMENTAL
)
dodash = 1 --Bop!
--Hammer double-jump hack
elseif ability == CA_TWINSPIN
and not isabil and not bmogrounded
and (bai.target.flags & (MF_BOSS | MF_ENEMY | MF_MONITOR))
and targetdist < bai.target.radius + bmo.radius + hintdist
and abs(targetz - bmoz) < (bai.target.height + bmo.height) / 2 + hintdist
doabil = 1
--Fang double-jump hack
elseif ability == CA_BOUNCE
and not bmogrounded and (falling or isabil)
and (bai.target.flags & (MF_BOSS | MF_ENEMY | MF_MONITOR))
and (
(isabil and targetdist < maxdist)
or targetfloor - bmofloor > jumpheight
or (
targetdist < bai.target.radius + bmo.radius + hintdist
and targetz - bmoz < 0
)
)
doabil = 1
--Thok / fire shield hack
elseif (ability == CA_THOK
or bot.powers[pw_shield] == SH_FLAMEAURA)
--and not (bot.charflags & SF_NOJUMPDAMAGE) --2.2.9 all characters now spin
and not bmogrounded and falling
and targetdist > bai.target.radius + bmo.radius + hintdist
and bai.target.height * 1/4 * flip + targetz - bmoz < 0
and bai.target.height * flip + targetz - bmoz > 0
--Mix in fire shield half the time if thokking
if ability != CA_THOK
or (
bot.powers[pw_shield] == SH_FLAMEAURA
and BotTime(bai, 1, 2)
)
dodash = 1
else
doabil = 1
end
--Glide / slide hack!
elseif ability == CA_GLIDEANDCLIMB
and (
isabil
or (
not bmogrounded and falling
and targetdist > bai.target.radius + bmo.radius + hintdist
and targetz - bmoz <= 0
and bai.target.height * 5/4 * flip + targetz - bmoz > 0
)
)
doabil = 1
end
elseif attkey == BT_USE
if ability2 == CA2_SPINDASH
--Only spin we're accurately on target, or very close to target
if bspd > minspeed
and (
AbsAngle(bmomang - bmo.angle) < ANGLE_22h / 10
or targetdist < bai.target.radius + bmo.radius + hintdist
)
dospin = 1
--Otherwise rev a dash (bigger charge when sloped)
elseif (bmosloped
and bot.dashspeed < bot.maxdash * 2/3
--Release if about to slide off slope edge
and not (bai.predictgap & 1))
or bot.dashspeed < bot.maxdash / 3
dodash = 1
end
else
dospin = 1
end
end
end
--Platforming during combat
if not isdash
and (
(isjump and not attack)
or (stalled and not bmosloped
and targetfloor - bmofloor > 24 * scale)
or bai.stalltics > TICRATE
or (bai.predictgap & 5) --Jumping a gap / out of special stage water
)
dojump = 1
end
end
--Special action - cull bad momentum w/ force shield or ground-pound
if isjump and falling
and not (doabil or isabil)
and (
(bot.powers[pw_shield] & SH_FORCE)
or (
bot.powers[pw_shield] == SH_ELEMENTAL
and bmoz - bmofloor < jumpheight
)
)
and bmom > minspeed
and AbsAngle(bmomang - bmo.angle) > ANGLE_157h
dodash = 1
end
--Maybe use shield double-jump?
--Outside of dojump block for whirlwind shield (should be safe)
if not bmogrounded and falling
and not (doabil or isabil or bot.climbing)
and (
bot.powers[pw_shield] == SH_THUNDERCOIN
or bot.powers[pw_shield] == SH_WHIRLWIND
or (
bot.powers[pw_shield] == SH_BUBBLEWRAP
and bmoz - bmofloor < jumpheight
)
)
and not bot.powers[pw_carry]
and (
(
--In combat - no whirlwind shield
bai.target and not bai.target.player
--and not (bot.charflags & SF_NOJUMPDAMAGE) --2.2.9 all characters now spin
and not (
--We'll allow whirlwind for ring etc. collection though
bot.powers[pw_shield] == SH_WHIRLWIND
and (bai.target.flags & (MF_BOSS | MF_ENEMY))
)
and (
targetz - bmoz > 32 * scale
or targetdist > 384 * scale
)
)
or (
--Out of combat - any shield
(not bai.target or bai.target.player)
and (
zdist > 32 * scale
or dist > 384 * scale
)
)
)
dodash = 1 --Use shield double-jump
cmd.buttons = $ | BT_JUMP --Force jump control for whirlwind
end
--**********
--DO INPUTS
--Jump action
--Could also check "or doabil > 0" as a shortcut
--But prefer to keep them separate for now
if dojump
and (
(isjump and bai.jump_last) --Already jumping
or (bmogrounded and not bai.jump_last) --Not jumping yet
or bot.powers[pw_carry] --Being carried?
)
and not (isjump and doabil) --Not requesting abilities
and not (isabil or bot.climbing) --Not using abilities
cmd.buttons = $ | BT_JUMP
end
--Ability
if doabil > 0
and (
isabil --Already using ability
or (isjump and not bai.jump_last) --Jump, released input
)
and not bot.climbing --Not climbing
and not (ability == CA_FLY and bai.jump_last) --Flight input check
cmd.buttons = $ | BT_JUMP
--"Force cancel" ability
elseif doabil < 0
and (
(ability == CA_FLY and isabil --If flying, descend
and bmo.state >= S_PLAY_FLY --Oops
and bmo.state <= S_PLAY_FLY_TIRED)
or bot.climbing --If climbing, let go
or bot.powers[pw_carry] --Being carried?
)
dodash = 1
cmd.buttons = $ & ~BT_JUMP
end
--Spin while moving
if dospin
and bmogrounded --Avoid accidental shield abilities
and not bai.spin_last
cmd.buttons = $ | BT_USE
end
--Charge spindash
if dodash
and (
not bmogrounded --Flight descend / shield abilities
or isdash --Already spinning
or (bspd < 2 * scale --Spin only from standstill
and not bai.spin_last)
)
cmd.buttons = $ | BT_USE
end
--Teleport override?
if bai.doteleport and CV_AITeleMode.value > 0
cmd.buttons = $ | CV_AITeleMode.value
end
--Nights hack - just copy player input
--(Nights isn't officially supported in coop anyway)
if bot.powers[pw_carry] == CR_NIGHTSMODE
cmd.forwardmove = pcmd.forwardmove
cmd.sidemove = pcmd.sidemove
cmd.buttons = pcmd.buttons
end
--Dead! (Overrides other jump actions)
if bot.playerstate == PST_DEAD
bai.playernosight = 0 --Don't spawn waypoints or try to teleport
bai.stalltics = $ + 1
cmd.buttons = $ & ~BT_JUMP
if leader.playerstate == PST_LIVE
and (
bmoz - bmofloor < 0
or bai.stalltics > 6 * TICRATE
)
and not bai.jump_last
cmd.buttons = $ | BT_JUMP
end
end
--In Stasis? (e.g. OLDC Voting)
if bot.pflags & PF_FULLSTASIS
cmd.buttons = pcmd.buttons --Just copy leader buttons
end
--*******
--History
if cmd.buttons & BT_JUMP
bai.jump_last = 1
else
bai.jump_last = 0
end
if cmd.buttons & BT_USE
bai.spin_last = 1
else
bai.spin_last = 0
end
if FixedHypot(cmd.forwardmove, cmd.sidemove) > 30
bai.move_last = 1
else
bai.move_last = 0
end
--*******
--Aesthetic
--thinkfly overlay
if bai.thinkfly == 1
if not (bai.overlay and bai.overlay.valid)
bai.overlay = P_SpawnMobj(bmo.x, bmo.y, bmo.z, MT_OVERLAY)
bai.overlay.target = bmo
bai.overlay.state = S_FLIGHTINDICATOR
bai.overlaytime = TICRATE
end
if SuperReady(bot)
and (ability != CA_FLY or bai.overlaytime % (2 * TICRATE) < TICRATE)
bai.overlay.colorized = true
bai.overlay.color = SKINCOLOR_YELLOW
elseif bai.overlay.colorized
bai.overlay.colorized = false
bai.overlay.color = SKINCOLOR_NONE
end
bai.overlaytime = $ + 1
else
bai.overlay = DestroyObj($)
end
--Debug
if CV_AIDebug.value > -1
and CV_AIDebug.value == #bot
local p = "follow"
local fight = 0
local helpmode = 0
if bai.target and bai.target.valid
if bai.target.player
helpmode = 1
else
fight = 1
end
end
if bai.flymode == 1 then p = "flymode (ready)"
elseif bai.flymode == 2 then p = "flymode (carrying)"
elseif bai.doteleport then p = "\x84" + "teleport!"
elseif helpmode then p = "\x81" + "helpmode"
elseif bai.target and bai.targetnosight then p = "\x84" + "targetnosight " + bai.targetnosight
elseif fight then p = "\x83" + "fight"
elseif bai.drowning then p = "\x85" + "drowning"
elseif bai.panic then p = "\x85" + "panic (anxiety " + bai.anxiety + ")"
elseif bai.bored then p = "bored"
elseif bai.thinkfly then p = "thinkfly"
elseif bai.anxiety then p = "\x82" + "anxiety " + bai.anxiety
elseif bai.targetnosight then p = "\x87" + "waypointnosight " + bai.targetnosight
elseif bai.playernosight then p = "\x87" + "playernosight " + bai.playernosight
elseif bai.spinmode then p = "spinmode (dashspeed " + bot.dashspeed / FRACUNIT + ")"
elseif dist > followthres then p = "follow (far)"
elseif dist < followmin then p = "follow (close)"
end
local dcol = ""
if dist > followmax then dcol = "\x85" end
local zcol = ""
if zdist > jumpheight then zcol = "\x85" end
--AI States
hudtext[1] = "AI [" + bai.bored..helpmode..fight..bai.attackwait..bai.thinkfly..bai.flymode..bai.spinmode..bai.drowning..bai.anxiety..bai.panic + "]"
hudtext[2] = p
--Distance
hudtext[3] = dcol + "dist " + dist / scale + "/" + followmax / scale
hudtext[4] = zcol + "zdist " + zdist / scale + "/" + jumpheight / scale
--Physics and Action states
hudtext[5] = "perf " + min(isjump,1)..min(isabil,1)..min(isspin,1)..min(isdash,1) + "|" + dojump..doabil..dospin..dodash
hudtext[6] = "gap " + bai.predictgap + " stall " + bai.stalltics
--Inputs
hudtext[7] = "FM " + cmd.forwardmove + " SM " + cmd.sidemove
hudtext[8] = "Jmp " + (cmd.buttons & BT_JUMP) / BT_JUMP + " Spn " + (cmd.buttons & BT_USE) / BT_USE + " Th " + (bot.pflags & PF_THOKKED) / PF_THOKKED
--Target
if fight
hudtext[9] = "\x83" + "target " + #bai.target.info + " - " + string.gsub(tostring(bai.target), "userdata: ", "")
+ " " + bai.targetcount + " " + targetdist / scale
elseif helpmode
hudtext[9] = "\x81" + "target " + #bai.target.player + " - " + bai.target.player.name
else
hudtext[9] = "leader " + #bai.leader + " - " + bai.leader.name
if bai.leader != bai.realleader and bai.realleader and bai.realleader.valid
hudtext[9] = $ + " (realleader " + #bai.realleader + " - " + bai.realleader.name + ")"
end
end
--Waypoint?
if bai.waypoint
hudtext[10] = ""
hudtext[11] = "waypoint " + string.gsub(tostring(bai.waypoint), "userdata: ", "")
if bai.waypoint.ai_type
hudtext[11] = "\x87" + $
else
hudtext[11] = "\x86" + $
end
end
end
end
--[[
--------------------------------------------------------------------------------
LUA HOOKS
Define all hooks used to actually interact w/ the game
--------------------------------------------------------------------------------
]]
--Tic? Tock! Call PreThinkFrameFor bot
addHook("PreThinkFrame", function()
for player in players.iterate
if player.ai
PreThinkFrameFor(player)
--Cancel quittime if we've rejoined a previously headless bot
--(unfortunately PlayerJoin does not fire for rejoins)
elseif player.quittime and (
player.cmd.forwardmove
or player.cmd.sidemove
or player.cmd.buttons
)
player.quittime = 0
end
end
end)
--Handle MapChange for bots (e.g. call ResetAI)
addHook("MapChange", function(mapnum)
for player in players.iterate
if player.ai
ResetAI(player.ai)
end
end
end)
--Handle MapLoad for bots
addHook("MapLoad", function(mapnum)
for player in players.iterate
if player.ai
--Fix bug where "real" ring counts aren't reset on map change
player.ai.realrings = player.rings
end
end
end)
--Handle damage for bots (simple "ouch" instead of losing rings etc.)
local function NotifyLoseShield(bot, basebot)
--basebot nil on initial call, but automatically set after
if bot != basebot
if bot.ai_followers
for _, b in pairs(bot.ai_followers)
NotifyLoseShield(b, basebot or bot)
end
end
if bot.ai
bot.ai.loseshield = true --Temporary flag
end
end
end
addHook("MobjDamage", function(target, inflictor, source, damage, damagetype)
if target.player and target.player.valid
--Handle bot invulnerability
if damagetype < DMG_DEATHMASK
and target.player.ai
and target.player.rings > 0
--Always allow heart shield loss so bots don't just have it all the time
--Otherwise do loss rules according to ai_hurtmode
and target.player.powers[pw_shield] != SH_PINK
and (
CV_AIHurtMode.value == 0
or (
CV_AIHurtMode.value == 1
and not target.player.powers[pw_shield]
)
)
S_StartSound(target, sfx_shldls)
P_DoPlayerPain(target.player, source, inflictor)
return true
--Handle shield loss if ai_hurtmode off
elseif CV_AIHurtMode.value == 0
and not target.player.ai
and not target.player.powers[pw_shield]
NotifyLoseShield(target.player)
end
end
end, MT_PLAYER)
--Handle death for bots
addHook("MobjDeath", function(target, inflictor, source, damagetype)
--Handle shield loss if ai_hurtmode off
if CV_AIHurtMode.value == 0
and target.player and target.player.valid
and not target.player.ai
NotifyLoseShield(target.player)
end
end, MT_PLAYER)
--Handle pickup rules for bots
local function CanPickup(special, toucher)
--Only pick up flung rings/coins leader could've also picked up
--However, let anyone pick up rings when ai_hurtmode == 2
--That is difficult to otherwise account for and is pretty brutal anyway
if toucher.player
and toucher.player.valid
and toucher.player.ai
and toucher.player.ai.leader
and toucher.player.ai.leader.valid
and CV_AIHurtMode.value < 2
and not P_CanPickupItem(GetTopLeader(toucher.player.ai.leader, toucher.player))
return true
end
end
addHook("TouchSpecial", CanPickup, MT_FLINGRING)
addHook("TouchSpecial", CanPickup, MT_FLINGCOIN)
--Handle (re)spawning for bots
addHook("PlayerSpawn", function(player)
if player.ai
--Fix resetting leader's rings to our startrings
player.ai.lastrings = player.rings
--Queue teleport to player, unless we're still in sight
player.ai.playernosight = 3 * TICRATE
elseif not player.jointime
and CV_AIDefaultLeader.value >= 0
and CV_AIDefaultLeader.value != #player
--Defaults to no ai/leader, but bot will sort itself out
PreThinkFrameFor(player)
end
end)
--Handle sudden quitting for bots
addHook("PlayerQuit", function(player, reason)
if player.ai
DestroyAI(player)
end
end)
--SP Only: Handle (re)spawning for bots
addHook("BotRespawn", function(pmo, bmo)
--Allow game to reset SP bot as normal if player-controlled or dead
if CV_ExAI.value == 0
or not bmo.player.ai
return
--Just destroy AI if dead, since SP bots don't get a PlayerSpawn event on respawn
--This resolves ring-sync issues on respawn and probably other things too
elseif bmo.player.playerstate == PST_DEAD
DestroyAI(bmo.player)
end
return false
end)
--SP Only: Delegate SP AI to foxBot
addHook("BotTiccmd", function(bot, cmd)
if CV_ExAI.value == 0
return
end
--SP bots need carry state manually set
if bot.charability == CA_FLY
and bot.mo and bot.mo.valid
and bot.mo.state >= S_PLAY_FLY
and bot.mo.state <= S_PLAY_FLY_TIRED
bot.pflags = $ | PF_CANCARRY
end
--Hook no longer needed once ai set up (PreThinkFrame handles instead)
if bot.ai
--But first, mirror leader's powerups! Since we can't grab monitors
local leader = bot.ai.leader
if leader and leader.valid
if leader.powers[pw_shield]
and (leader.powers[pw_shield] & SH_NOSTACK != SH_PINK)
and not bot.powers[pw_shield]
and (leveltime + bot.ai.timeseed) % TICRATE == 0
--Temporary var for this logic only
--Note that it does not go in bot.ai, as that is destroyed on p2 input in SP
and not bot.ai_noshieldregen
if leader.powers[pw_shield] == SH_ARMAGEDDON
bot.ai_noshieldregen = leader.powers[pw_shield]
end
P_SwitchShield(bot, leader.powers[pw_shield])
if bot.mo and bot.mo.valid
S_StartSound(bot.mo, sfx_s3kcas)
end
elseif leader.powers[pw_shield] != bot.ai_noshieldregen
bot.ai_noshieldregen = nil
end
bot.powers[pw_invulnerability] = leader.powers[pw_invulnerability]
bot.powers[pw_sneakers] = leader.powers[pw_sneakers]
bot.powers[pw_gravityboots] = leader.powers[pw_gravityboots]
end
return true
end
--Defaults to no ai/leader, but bot will sort itself out
PreThinkFrameFor(bot)
return true
end)
--HUD hook!
hud.add(function(v, stplyr, cam)
--If not previous text in buffer... (e.g. debug)
if hudtext[1] == nil
--And we're not a bot...
if stplyr.ai == nil
or stplyr.ai.leader == nil
or not stplyr.ai.leader.valid
or CV_AIShowHud.value == 0
return
end
--Otherwise generate a simple bot hud
local bmo = stplyr.realmo
local pmo = stplyr.ai.leader.realmo
if bmo and bmo.valid
and pmo and pmo.valid
hudtext[1] = "Following " + stplyr.ai.leader.name
if stplyr.ai.leader != stplyr.ai.realleader
and stplyr.ai.realleader and stplyr.ai.realleader.valid
hudtext[1] = $ + " \x83(" + stplyr.ai.realleader.name + " KO'd)"
end
hudtext[2] = ""
if stplyr.ai.doteleport
hudtext[3] = "\x84Teleporting..."
elseif pmo.health <= 0
hudtext[3] = "Waiting for respawn..."
else
hudtext[3] = "Dist " + FixedHypot(
R_PointToDist2(
bmo.x, bmo.y,
pmo.x, pmo.y
),
abs(pmo.z - bmo.z)
) / bmo.scale
if stplyr.ai.playernosight
hudtext[3] = "\x87" + $
end
end
hudtext[4] = nil
if stplyr.ai.cmd_time > 0
and stplyr.ai.cmd_time < 3 * TICRATE
hudtext[4] = ""
hudtext[5] = "\x81" + "AI control in " .. stplyr.ai.cmd_time / TICRATE + 1 .. "..."
hudtext[6] = nil
end
end
end
--Positioning / size
local x = 16
local y = 56
local size = "small"
local scale = 1
--Spectating?
if stplyr.spectator
y = $ + 44
elseif stplyr.pflags & PF_FINISHED
y = $ + 22
end
--Account for splitscreen
--Avoiding V_PERPLAYER as text gets a bit too squashed
if splitscreen
y = $ / 2
if #stplyr > 0
y = $ + 108 --Magic!
end
end
--Small fonts become illegible at low res
if v.height() < 400
size = nil
scale = 2
end
--Draw! Flushing hudtext after
for k, s in ipairs(hudtext)
if k & 1
v.drawString(x, y, s, V_SNAPTOTOP | V_SNAPTOLEFT | v.localTransFlag(), size)
else
v.drawString(x + 64 * scale, y, s, V_SNAPTOTOP | V_SNAPTOLEFT | v.localTransFlag(), size)
y = $ + 4 * scale
end
hudtext[k] = nil
end
end, "game")
--[[
--------------------------------------------------------------------------------
HELP STUFF
Things that may or may not be helpful
--------------------------------------------------------------------------------
]]
local function BotHelp(player)
print(
"\x87 foxBot! v1.4: 2021-08-20",
"\x81 Based on ExAI v2.0: 2019-12-31",
"",
"\x87 SP / MP Server Admin:",
"\x80 ai_sys - Enable/Disable AI",
"\x80 ai_ignore - Ignore targets? \x86(1 = enemies, 2 = rings / monitors, 3 = all)",
"\x80 ai_seekdist - Distance to seek enemies, rings, etc.",
"",
"\x87 MP Server Admin:",
"\x80 ai_catchup - Allow AI catchup boost? \x86(MP only, sorry!)",
"\x80 ai_keepdisconnected - Allow AI to remain after client disconnect?",
"\x83 Note: rejointimeout must also be > 0 for this to work!",
"\x80 ai_defaultleader - Default leader for new clients \x86(-1 = off, 32 = random)",
"\x80 ai_hurtmode - Allow AI to get hurt? \x86(1 = shield loss, 2 = ring loss)",
"\x80 ai_statmode - Allow AI individual stats? \x86(1 = rings, 2 = lives, 3 = both)",
"\x80 ai_telemode - Override AI teleport behavior w/ button press?",
"\x86 (64 = fire, 1024 = toss flag, 4096 = alt fire, etc.)",
"\x80 setbota <leader> <bot> - Have <bot> follow <leader> by number \x86(-1 = stop)",
"",
"\x87 SP / MP Client:",
"\x80 ai_debug - Draw detailed debug info to HUD? \x86(-1 = off)",
"",
"\x87 MP Client:",
"\x80 ai_showhud - Draw basic bot info to HUD?",
"\x80 setbot <leader> - Follow <leader> by number \x86(-1 = stop)",
"\x80 listbots - List active bots and players"
)
if not player
print(
"",
"\x87 Use \"bothelp\" to show this again!"
)
end
end
COM_AddCommand("BOTHELP", BotHelp, COM_LOCAL)
--[[
--------------------------------------------------------------------------------
INIT ACTIONS
Actions to take once we've successfully initialized
--------------------------------------------------------------------------------
]]
BotHelp() --Display help
|
hook.Add("Initialize", "nadmin_register_silent_notify", function()
nadmin:RegisterPerm({
title = "See Silent Commands"
})
end)
-- Parse a string as a commandline input
function nadmin:ParseArgs(str, normal)
local out = {} -- This is the simple table
local advOut = {__unindexed = {}} -- This is the commandline parsed output
local quote = false -- Supports wrapping a string in quotes to preserve spaces; gets counted as a single argument
local s = "" -- The current string to be added to out
str = string.Explode("", str)
for i, c in ipairs(str) do
local t = string.Trim(s)
if c == " " and not quote and #t > 0 then
table.insert(out, t)
s = ""
elseif c == '"' and str[i - 1] ~= "\\" then
quote = not quote
else
if c == "\\" and str[i + 1] == '"' then continue end
s = s .. c
end
end
local t = string.Trim(s)
if #t > 0 then
table.insert(out, t)
end
if not normal then
local cmd = "__unindexed"
for i, o in ipairs(out) do
if string.StartWith(o, "-") then
local newCmd = string.Trim(string.sub(o, 2))
if #newCmd > 0 then
cmd = newCmd
continue
end
end
if string.sub(o, 1, 2) == "\\-" then
out[i] = string.sub(o, 2)
end
if not advOut[cmd] then advOut[cmd] = {} end
table.insert(advOut[cmd], out[i])
end
end
if normal then return out end
return advOut, out
end
|
--MUST READ:
-- to use this file do the following
-- 1)find and replace each capitalized instance of NodeTemplate
-- with a capitalized version of your node's name
-- 2) find and replace each lowercase instance of nodeTemplate
-- with a lowercase version of your node's name(this should be the same as the filename)
-- 3) start coding
-----------------------------------------------
-- NodeTemplate.lua
-----------------------------------------------
local NodeTemplate = {}
NodeTemplate.__index = NodeTemplate
NodeTemplate.isNodeTemplate = true
---
-- Creates a new NodeTemplate object
-- @param node the table used to create this
-- @param a collider of objects
-- @return the NodeTemplate object created
function NodeTemplate.new(node, collider)
--creates a new object
local nodeTemplate = {}
--sets it to use the functions and variables defined in NodeTemplate
-- if it doesn;t have one by that name
setmetatable(nodeTemplate, NodeTemplate)
--stores all the parameters from the tmx file
nodeTemplate.node = node
nodeTemplate.position = {x = node.x, y = node.y}
nodeTemplate.width = node.width
nodeTemplate.height = node.height
--initialize the node's bounding box
nodeTemplate.collider = collider
nodeTemplate.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
nodeTemplate.bb.node = nodeTemplate
nodeTemplate.collider:setPassive(nodeTemplate.bb)
--define some offsets for the bounding box that can be used each update cycle
nodeTemplate.bb_offset = {x = 0,y = 0}
--add more initialization code here if you want
return nodeTemplate
end
---
-- Draws the NodeTemplate to the screen
-- @return nil
function NodeTemplate:draw()
--to access the field called "foo" of this node do the following:
-- self.foo
end
function NodeTemplate:keypressed( button, player )
end
---
-- Called when the NodeTemplate begins colliding with another node
-- @param node the node you're colliding with
-- @param dt ?
-- @param mtv_x amount the node must be moved in the x direction to stop colliding
-- @param mtv_y amount the node must be moved in the y direction to stop colliding
-- @return nil
function NodeTemplate:collide(node, dt, mtv_x, mtv_y)
end
---
-- Called when the NodeTemplate finishes colliding with another node
-- @return nil
function NodeTemplate:collide_end(node, dt)
end
---
-- Updates the NodeTemplate
-- dt is the amount of time in seconds since the last update
function NodeTemplate:update(dt)
--do this immediately before leaving the function
-- repositions the bounding box based on your current coordinates
local x1,y1,x2,y2 = self.bb:bbox()
self.bb:moveTo( self.position.x + (x2-x1)/2 + self.bb_offset.x,
self.position.y + (y2-y1)/2 + self.bb_offset.y )
end
return NodeTemplate
|
local sqlite3 = require "rspamd_sqlite3"
local redis = require "rspamd_redis"
local util = require "rspamd_util"
local function connect_redis(server, password, db)
local ret
local conn, err = redis.connect_sync({
host = server,
})
if not conn then
return nil, 'Cannot connect: ' .. err
end
if password then
ret = conn:add_cmd('AUTH', {password})
if not ret then
return nil, 'Cannot queue command'
end
end
if db then
ret = conn:add_cmd('SELECT', {db})
if not ret then
return nil, 'Cannot queue command'
end
end
return conn, nil
end
local function send_digests(digests, redis_host, redis_password, redis_db)
local conn, err = connect_redis(redis_host, redis_password, redis_db)
if err then
print(err)
return false
end
local ret
for _, v in ipairs(digests) do
ret = conn:add_cmd('HMSET', {
'fuzzy' .. v[1],
'F', v[2],
'V', v[3],
})
if not ret then
print('Cannot batch command')
return false
end
ret = conn:add_cmd('EXPIRE', {
'fuzzy' .. v[1],
tostring(v[4]),
})
if not ret then
print('Cannot batch command')
return false
end
end
ret, err = conn:exec()
if not ret then
print('Cannot execute batched commands: ' .. err)
return false
end
return true
end
local function send_shingles(shingles, redis_host, redis_password, redis_db)
local conn, err = connect_redis(redis_host, redis_password, redis_db)
if err then
print("Redis error: " .. err)
return false
end
local ret
for _, v in ipairs(shingles) do
ret = conn:add_cmd('SET', {
'fuzzy_' .. v[2] .. '_' .. v[1],
v[4],
})
if not ret then
print('Cannot batch SET command: ' .. err)
return false
end
ret = conn:add_cmd('EXPIRE', {
'fuzzy_' .. v[2] .. '_' .. v[1],
tostring(v[3]),
})
if not ret then
print('Cannot batch command')
return false
end
end
ret, err = conn:exec()
if not ret then
print('Cannot execute batched commands: ' .. err)
return false
end
return true
end
local function update_counters(total, redis_host, redis_password, redis_db)
local conn, err = connect_redis(redis_host, redis_password, redis_db)
if err then
print(err)
return false
end
local ret
ret = conn:add_cmd('SET', {
'fuzzylocal',
total,
})
if not ret then
print('Cannot batch command')
return false
end
ret = conn:add_cmd('SET', {
'fuzzy_count',
total,
})
if not ret then
print('Cannot batch command')
return false
end
ret, err = conn:exec()
if not ret then
print('Cannot execute batched commands: ' .. err)
return false
end
return true
end
return function (_, res)
local db = sqlite3.open(res['source_db'])
local shingles = {}
local digests = {}
local num_batch_digests = 0
local num_batch_shingles = 0
local total_digests = 0
local total_shingles = 0
local lim_batch = 1000 -- Update each 1000 entries
local redis_password = res['redis_password']
local redis_db = nil
if res['redis_db'] then
redis_db = tostring(res['redis_db'])
end
if not db then
print('Cannot open source db: ' .. res['source_db'])
return
end
local now = util.get_time()
for row in db:rows('SELECT id, flag, digest, value, time FROM digests') do
local expire_in = math.floor(now - row.time + res['expiry'])
if expire_in >= 1 then
table.insert(digests, {row.digest, row.flag, row.value, expire_in})
num_batch_digests = num_batch_digests + 1
total_digests = total_digests + 1
for srow in db:rows('SELECT value, number FROM shingles WHERE digest_id = ' .. row.id) do
table.insert(shingles, {srow.value, srow.number, expire_in, row.digest})
total_shingles = total_shingles + 1
num_batch_shingles = num_batch_shingles + 1
end
end
if num_batch_digests >= lim_batch then
if not send_digests(digests, res['redis_host'], redis_password, redis_db) then
return
end
num_batch_digests = 0
digests = {}
end
if num_batch_shingles >= lim_batch then
if not send_shingles(shingles, res['redis_host'], redis_password, redis_db) then
return
end
num_batch_shingles = 0
shingles = {}
end
end
if digests[1] then
if not send_digests(digests, res['redis_host'], redis_password, redis_db) then
return
end
end
if shingles[1] then
if not send_shingles(shingles, res['redis_host'], redis_password, redis_db) then
return
end
end
local message = string.format(
'Migrated %d digests and %d shingles',
total_digests, total_shingles
)
if not update_counters(total_digests, res['redis_host'], redis_password, redis_db) then
message = message .. ' but failed to update counters'
end
print(message)
end
|
-- local uv = vim.loop
-- local stdin = uv.new_pipe(false)
-- local stdout = uv.new_pipe(false)
-- local stderr = uv.new_pipe(false)
-- local job = vim.loop.spawn(
-- 'cargo', {
-- args = {'run', 'server'},
-- stdin = stdin,
-- stdout = stdout,
-- stderr = stderr,
-- }, function(code, signal)
-- print("Exit:", code, signal)
-- end
-- )
-- P(job.stdout)
local Job = require('plenary.job')
local lib = R('lib_lsp')
Job:new { command = 'cargo', args = { 'build' } }:sync()
local j = lib.start_server()
j:initialize {}
j:request_sync {
method = "textDocument/definition",
params = {
textDocument = {
uri = "file://tmp"
},
position = {
line = 1,
character = 1,
},
}
}
j:finish()
|
--[=[
Simple rig component to point at attachments given
@client
@class GripPointer
]=]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local BaseObject = require(ReplicatedStorage.Knit.Util.Additions.Classes.BaseObject)
local Janitor = require(ReplicatedStorage.Knit.Util.Janitor)
local GripPointer = setmetatable({}, BaseObject)
GripPointer.ClassName = "GripPointer"
GripPointer.__index = GripPointer
function GripPointer.new(IkRig)
local self = setmetatable(BaseObject.new(), GripPointer)
self.IkRig = IkRig or error("No ikRig")
return self
end
function GripPointer:SetLeftGrip(LeftGrip)
self.LeftGripAttachment = LeftGrip
if not self.LeftGripAttachment then
return self.Janitor:Remove("LeftGripJanitor")
end
local LeftGripJanitor = self.Janitor:Add(Janitor.new(), "Destroy", "LeftGripJanitor")
LeftGripJanitor:AddPromise(self.IkRig:PromiseLeftArm()):Then(function(LeftArm)
LeftGripJanitor:Add(LeftArm:Grip(self.LeftGripAttachment, 1), true)
end)
end
function GripPointer:SetRightGrip(RightGrip)
self.RightGripAttachment = RightGrip
if not self.RightGripAttachment then
return self.Janitor:Remove("RightGripJanitor")
end
local RightGripJanitor = self.Janitor:Add(Janitor.new(), "Destroy", "RightGripJanitor")
RightGripJanitor:AddPromise(self.IkRig:PromiseRightArm()):Then(function(RightArm)
RightGripJanitor:Add(RightArm:Grip(self.RightGripAttachment, 1), true)
end)
end
function GripPointer:__tostring()
return "GripPointer"
end
table.freeze(GripPointer)
return GripPointer
|
--[[
tp8_book
Uses:
Todo:
Models: shoe: models/props_junk/Shoe001a.mdl
hula: models/props_lab/huladoll.mdl
soda: models/props_junk/PopCan01a.mdl
kettle: models/props_interiors/pot01a.mdl
alcohol: models/props_junk/garbage_glassbottle002a.mdl
baby: models/props_c17/doll01.mdl
tiny rock: models/props_junk/rock001a.mdl
]]
AddCSLuaFile()
ENT.Type = "anim"
ENT.Model = "models/props_junk/Shoe001a.mdl"
ENT.Up = {"vo/npc/female01/upthere01.wav", "vo/npc/female01/upthere02.wav"}
ENT.Down = {"vo/npc/male01/getdown02.wav"}
ENT.Back = {"vo/npc/male01/overhere01.wav"}
ENT.Fwd = {"vo/npc/vortigaunt/forward.wav", "vo/npc/vortigaunt/onward.wav", "vo/npc/vortigaunt/yesforward.wav"}
ENT.Left = {"vo/ravenholm/shotgun_keepitclose.wav"}
ENT.Right = {"vo/npc/vortigaunt/vanswer12.wav"}
ENT.Gene = {"vo/npc/vortigaunt/satisfaction.wav", "vo/npc/vortigaunt/ourplacehere.wav", "vo/npc/vortigaunt/dreamed.wav"}
ENT.Start = -1
ENT.End = -1
ENT.playa = nil
ENT.positions = {}
ENT.timeInterval = 0.05
ENT.isTracking = false
ENT.delta = 0
ENT.timer_name = ""
ENT.tolerancePercentage = 0.99 -- if 1, will divide by zero
ENT.toleranceDistance = 10 --not related to above!
ENT.devMode = true
--q is 27
hook.Add( "PlayerButtonDown", "ButtonUpWikiExample", function( ply, button )
-- print( ply:Nick() .. " pressed " .. (button) )
if button == 27 && ply.entitty != nil then
for i=1,#ply.entitty do
ply.entitty[i]:startTracking()
end
end
end)
function ENT:startTracking()
if self.isTracking then return end
self.isTracking = true
self.positions = {}
self.Start = CurTime()
--every x seconds grab player position, insert it into table
self.timer_name = "bend_" .. self:EntIndex()
timer.Create(self.timer_name,self.timeInterval,0, function() --every (some amount) seconds, update pos
--print("time: "..CurTime())
if IsValid(self) then
table.insert(self.positions, self:GetPos())
elseif !IsValid(self) then
timer.Remove(self.timer_name)
end
end)
end
-- if self:similar(self.movementRecord[1], self.spell1[1], self.tolerancePercentage) then
-- --cast spell
-- self:cast()
-- end
hook.Add( "PlayerButtonUp", "ButtonUpWikiExample", function( ply, button )
-- print( ply:Nick() .. " released " .. (button) )
if button == 27 && ply.entitty != nil then
for i=1,#ply.entitty do
ply.entitty[i]:stopTracking()
end
end
end)
function ENT:stopTracking()
print("forzen like Elsa")
if !self.isTracking then return end
self.isTracking = false
self.End = CurTime()
self.delta = self.End - self.Start
--check if it was a good spell or not
self:LookForASpellAndCastIt()
--remove timer
timer.Remove(self.timer_name)
end
--Have use set the ply on the ent and ent on ply
--player presses q, sends curtime to start ?on the ent? (where? ply? globalArray[ply, value]?)
--ENT:startTracking() ent uses this to start tracking own position (solves the syncing problem)
--player releases q, sends curtime to end ?on the ent? (where?)
--ent uses this to calc time to see if it worked
--checks if at the right time, the pos is close to an equation's same point at that time.
--if it works, then cast spell where player is looking or something. Depends on spell. Like fire hands vs. rock toss up and punch
--DAB SPELL???
--for two handed motions, just have to make sure both ents passed their part of the spell required movements... might want a global list to pair them...
--due to this pairing of ents, it is possible to have multiperson spells be made with >2 bendables.
function ENT:LookForASpellAndCastIt()
--validate amongst various spells
print("wow, we doing it now!!!")
--use self.delta to map
--imagine a line, divided into 0.1 time segments
local isGoodToCast = true
local spellX = 0
local spellY = 0
local spellZ = 0
local t = 0
local relativePos = Vector(0,0,0)
local skip = 0
local uniquePos = {}
--if the player stays still, they do not lose progress
--in the future, rather than == for perfect match, this could also be a similarDistance check...
for i=1,#self.positions-1 do
if !(self.positions[i] == self.positions[i+1]) then
table.insert(uniquePos, self.positions[i])
else
self.delta = self.delta - self.timeInterval
end
end
--[[this is how you add a new spell!]]
if self.devMode && #uniquePos > 2 then
local addNewSpellCode = "{"
for i=1,#uniquePos-1 do
addNewSpellCode = addNewSpellCode.."Vector("..uniquePos[i].x -uniquePos[1].x..","..uniquePos[i].y -uniquePos[1].y..","..uniquePos[i].z -uniquePos[1].z.."), "
end
addNewSpellCode = addNewSpellCode.."Vector("..uniquePos[#uniquePos].x -uniquePos[1].x..","..uniquePos[#uniquePos].y -uniquePos[1].y..","..uniquePos[#uniquePos].z -uniquePos[1].z..")}"
print(addNewSpellCode)
end
-- calculate total distance to use in comparing changes in vector distance
for i=1,#uniquePos do
end
t = 0
if #uniquePos > 2 then
for spell=1,#self.spellList do
print("Spell: "..spell.. " ******************************************************************************************")
local spellStep=2
for i=1,#uniquePos-1 do
--t = (self.timeInterval * i) / self.delta --normalizes t from 0 to 1
t = t +
print("i: ".. i.. ", spellStep: ".. spellStep)
print(#uniquePos..", "..#self.spellList[spell])
--might want to use the absolute value of all these x and y... hacky fix for causing the circle front, circle back problem (success depends where you start)
spellX = self.spellList[spell][spellStep].x *t + self.spellList[spell][spellStep-1].x
spellY = self.spellList[spell][spellStep].y *t + self.spellList[spell][spellStep-1].y
spellZ = self.spellList[spell][spellStep].z *t + self.spellList[spell][spellStep-1].z
relativePos = uniquePos[i]-uniquePos[1]
if !(self:similarDistance(relativePos,Vector(spellX,spellY,spellZ),self.toleranceDistance)) then
--if !(self:cosineSimilarity(relativePos,Vector(spellX,spellY,spellZ),self.tolerancePercentage)) then
isGoodToCast = false
print("here is bad")
break --skips the rest of this spell
end
if((i/#uniquePos) > (spellStep)/#self.spellList[spell] && spellStep < #self.spellList[spell]) then --[[ Set the spell point based on time. Note, both spell and spellList are synchronized time-wise]]
spellStep = spellStep + 1
end
end
if isGoodToCast then
self:cast(spell)
end
end
end
end
function ENT:Initialize()
self:SetModel(self.Model)
if SERVER then
self:SetUseType( SIMPLE_USE )
--self:SetModel(self.Model)
self:PhysicsInit( SOLID_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:EnableGravity(false)
--phys:EnableDrag(false)
phys:SetMass(25)
end
local trail = util.SpriteTrail(self, 0, Color(125,125,255), false, 15, 1, 5, 1/(15+1)*0.5, "trails/plasma.vmt")
end
self.devUp = {Vector(0,0,0), Vector(0,0,36)}
self.circleRight = {Vector(0,0,0), Vector(-8.493408203125,-17.801025390625,0), Vector(-23.04833984375,-31.111083984375,0), Vector(-38.75244140625,-37.445556640625,0), Vector(-58.468994140625,-37.95947265625,0), Vector(-76.9365234375,-31.03369140625,0), Vector(-89.710205078125,-19.916748046875,0), Vector(-99.118896484375,-2.58251953125,0), Vector(-101.33178710938,17.016357421875,0), Vector(-97.225830078125,33.444580078125,0), Vector(-86.05224609375,49.697509765625,0), Vector(-69.59423828125,60.567138671875,0), Vector(-53.0927734375,64.366943359375,0), Vector(-33.538330078125,61.789794921875,0), Vector(-16.382080078125,52.060302734375,0), Vector(-5.504638671875,39.082275390625,0), Vector(1.07666015625,20.4892578125,0)}
self.spellList = {self.devUp, self.circleRight}
self.spellDerivativeList = {}
self.spellDist = {}
-- TODO: When you use a ratio of these DistToSqr AKA self.spellDerivativeList[i], be sure to square the value at i!
-- https://www.wolframalpha.com/input/?i=%283%5E2%29+%2F+%2812%5E2%29
-- Use this code to calculate the distance each spell is... can save CPU by hardcoding these with this information.
-- https://wiki.facepunch.com/gmod/Vector:DistToSqr is faster than Vector:Distance. Not too different for my purpose.
local result = 0
local derivOfPos = 0
local resultStr = ""
local derivStr = ""
if self.devMode && (#self.spellDerivativeList < 1 || #self.spellDist < 1) then
self.spellDerivativeList = {}
self.spellDist = {}
for spell=1,#self.spellList do
-- calculate total distance to use in comparing changes in vector distance
result = 0
derivStr = ""
for i=1,#self.spellList[spell]-1 do
derivOfPos = self.spellList[spell][i]:DistToSqr(self.spellList[spell][i+1])
table.insert(self.spellDerivativeList[spell][i], derivOfPos)
derivStr = derivStr..derivOfPos..", "
result = result + derivOfPos
end
table.insert(self.spellDist, result)
print("derivatives of the postions: ".. derivStr)
resultStr = resultStr..result..", "
end
print("all (total-distances)^2s: "..resultStr)
end
end
function ENT:Use(ply)
self.playa = ply
if !IsValid(ply.entitty) then ply.entitty = {} end
table.insert(ply.entitty, self)
print("used")
end
function ENT:cast(spell)
print("cast: "..spell)
if spell == 1 then
--devUp
self:EmitSound(Sound(self.Up[math.random(#self.Up)]))
elseif spell == 2 then
--circleRight
self:EmitSound(Sound(self.Gene[math.random(#self.Gene)]))
else
error("Error: spell not defined")
end
end
function ENT:OnRemove()
--once ent is removed, remove self from player's entitty table of linked bend(ables) entities.
if self.playa != nil && self.playa.entitty != nil then
for i=1,#self.playa.entitty do
if self.playa.entitty[i] == self then
table.remove(self.playa.entitty, i)
end
end
end
end
function ENT:cosineSimilarity(new, old, percent)
-- https://en.wikipedia.org/wiki/Cosine_similarity
local truth = true
local dotty = new:Dot(old)
local a = math.sqrt(new:Dot(new))
local b = math.sqrt(old:Dot(old))
local cosSim = dotty / (a*b)
cosSim = cosSim
print("~~~~~~~~~~~~~~~~~~~~~~~ "..CurTime().." ~~~~~~~~~~~~~~~~~~~~~~~")
print("new.x: "..new.x.." v "..old.x.." :old.x")
print("new.y: "..new.y.." v "..old.y.." :old.y")
print("new.z: "..new.z.." v "..old.z.." :old.z")
print("Cosine Similarity: "..cosSim)
print("is true if: "..1+percent.." > "..cosSim.." > "..1-percent)
if cosSim ~= cosSim || cosSim > (1+percent) || cosSim < 1-percent then
truth = false
end
return truth
end
function ENT:dotProduct(new, old, percent)
local truth = true
local dotty = new:Dot(old)
print("~~~~~~~~~~~~~~~~~~~~~~~ "..CurTime().." ~~~~~~~~~~~~~~~~~~~~~~~")
print("new.x: "..new.x.." v "..old.x.." :old.x")
print("new.y: "..new.y.." v "..old.y.." :old.y")
print("new.z: "..new.z.." v "..old.z.." :old.z")
print("dot: "..dotty)
print("is true if: "..1+percent.." > "..dotty.." > "..1-percent)
if dotty > (1+percent) || dotty < 1-percent then
truth = false
end
return truth
end
function ENT:similarPercent(new, old, percent)
--each component may not be more than 'percent' % different + or - from 'orig'
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("new.x: "..new.x.." - "..old.x.." :old.x")
print("new.y: "..new.y.." - "..old.y.." :old.y")
print("new.z: "..new.z.." - "..old.z.." :old.z")
print("new.x - old.x > 1+percent * old.x: "..new.x - old.x.." ? ".. 1+percent* old.x)
print("new.x - old.x < 1-percent * old.x: "..new.x - old.x.." ? ".. 1-percent* old.x)
print("new.y - old.y > 1+percent * old.y: "..new.y - old.y.." ? ".. 1+percent* old.y)
print("new.y - old.y < 1-percent * old.y: "..new.y - old.y.." ? ".. 1-percent* old.y)
print("new.z - old.z > 1+percent * old.z: "..new.z - old.z.." ? ".. 1+percent* old.z)
print("new.z - old.z < 1-percent * old.z: "..new.z - old.z.." ? ".. 1-percent* old.z)
local truth = true
if (new.x - old.x > 1+percent * old.x) || (new.x - old.x < 1-percent * old.x) then
truth = false
end
if (new.y - old.y > 1+percent * old.y) || (new.y - old.y < 1-percent * old.y) then
truth = false
end
if (new.z - old.z > 1+percent * old.z) || (new.z - old.z < 1-percent * old.z) then
truth = false
end
if truth then print("truth") end
return truth
end
function ENT:similarDistance(new, old, distance)
--each component may not be more than 'percent' % different + or - from 'orig'
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("new.x: "..new.x.." - "..old.x.." :old.x")
print("new.y: "..new.y.." - "..old.y.." :old.y")
print("new.z: "..new.z.." - "..old.z.." :old.z")
-- print("new.x - old.x > distance: "..new.x - old.x.." ? ".. distance)
-- print("new.x - old.x < -distance: "..new.x - old.x.." ? "..-distance)
-- print("new.y - old.y > distance: "..new.y - old.y.." ? ".. distance)
-- print("new.y - old.y < -distance: "..new.y - old.y.." ? "..-distance)
-- print("new.z - old.z > distance: "..new.z - old.z.." ? ".. distance)
-- print("new.z - old.z < -distance: "..new.z - old.z.." ? "..-distance)
local truth = true
if (new.x - old.x > distance) || (new.x - old.x < -distance) then
truth = false
end
if (new.y - old.y > distance) || (new.y - old.y < -distance) then
truth = false
end
if (new.z - old.z > distance) || (new.z - old.z < -distance) then
truth = false
end
--if truth then print("truth") end
return truth
end
|
local PANEL = {}
function PANEL:Initialize()
self:super()
self:DockPadding(0,0,0,0)
self.m_pCanvas = self:Add("Panel")
self.m_pCanvas:SetBGColor(color_blank)
self.m_pCanvas:SetBorderColor(color_blank)
-- Create the scroll bar
self.m_pVBar = self:Add("ScrollBar")
self.m_pVBar:DockMargin(-1,0,0,0)
self.m_pVBar:Dock(DOCK_RIGHT)
end
function PANEL:AddItem(class)
return self.m_pCanvas:Add(class)
end
function PANEL:OnChildAdded(child)
end
function PANEL:SizeToContents()
self:SetSize(self.m_pCanvas:GetSize())
end
function PANEL:GetVBar()
return self.m_pVBar
end
function PANEL:GetCanvas()
return self.m_pCanvas
end
function PANEL:InnerWidth()
return self:GetCanvas():GetWidth()
end
function PANEL:Rebuild()
self:GetCanvas():SizeToChildren(false, true)
if self.m_bNoSizing and self:GetCanvas():GetHeight() < self:GetHeight() then
self:GetCanvas():SetPos(0, (self:GetHeight()-self:GetCanvas():GetHeight()) * 0.5)
end
end
function PANEL:OnMouseWheeled(x, y)
return self.m_pVBar:OnMouseWheeled(x, y)
end
function PANEL:OnVScroll(iOffset)
self.m_pCanvas:SetPos(0, iOffset)
end
function PANEL:ScrollToChild(panel)
self:PerformLayout()
local x, y = self.m_pCanvas:GetChildPosition(panel)
local w, h = panel:GetSize()
y = y + h * 0.5;
y = y - self:GetHeight() * 0.5;
self.m_pVBar:AnimateTo(y, 0.5, 0, 0.5);
end
function PANEL:PerformLayout()
local wide = self:GetWidth()
local ypos = 0
local xpos = 0
self:Rebuild()
self.m_pVBar:SetUp(self:GetHeight(), self.m_pCanvas:GetHeight())
ypos = self.m_pVBar:GetOffset()
if self.m_pVBar.m_bEnabled then
wide = wide - self.m_pVBar:GetWidth()
wide = wide - self.m_pVBar.m_tDockMargins.left - self.m_pVBar.m_tDockMargins.right
end
self.m_pCanvas:SetPos(0, ypos)
self.m_pCanvas:SetWidth(wide)
self:Rebuild()
end
function PANEL:Clear()
return self.m_pCanvas:Clear()
end
gui.register("ScrollPanel", PANEL, "Panel")
|
if FirstLoad then
CycleFunc = false
end
----- CycleMember
DefineClass.CycleMember = {
parents = { "PropertyObject" },
}
function CycleMember:CycleNext(gamepad)
local index, objs, text = GetCycleInfo(self)
local obj = index and objs and (index < #objs and objs[index + 1] or objs[1])
if obj then
InfopanelSlideIn = false
InfopanelFocused = gamepad or false
obj:Select(CycleFunc)
end
end
function CycleMember:CyclePrev(gamepad)
local index, objs, text = GetCycleInfo(self)
local obj = index and objs and (index > 1 and objs[index - 1] or objs[#objs])
if obj then
InfopanelSlideIn = false
InfopanelFocused = gamepad or false
obj:Select(CycleFunc)
end
end
function CycleMember:GetDefaultCycleFunc()
end
----- globals
function GetCycleInfo(obj)
obj = obj or SelectedObj
local index, objs, text
if CycleFunc then
index, objs, text = CycleFunc(obj)
end
if not index then
CycleFunc = false
end
return index, objs, text
end
local clear_cycle = true
function OnMsg.SelectedObjChange(obj)
if clear_cycle then
CycleFunc = false
if obj and obj:IsKindOf("CycleMember") then
CycleFunc = obj:GetDefaultCycleFunc() or false
end
end
clear_cycle = true
end
function SelectObjWithCycle(obj, cycle_func)
clear_cycle = false
CycleFunc = cycle_func or obj and obj:GetDefaultCycleFunc() or false
SelectObj(obj)
end
function ResidenceCycle(obj)
local residence = obj.residence
local objs = residence and residence.colonists
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = residence:GetDisplayName(), index = index, max = #objs}
end
end
function DomeCycle(obj)
local dome = obj.dome
local objs = dome and dome.labels.Colonist
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = dome:GetDisplayName(), index = index, max = #objs}
end
end
function HomelessCycle(obj)
local city = obj.city or UICity
local objs = city.labels.Homeless or empty_table
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = T(3869, "Homeless"), index = index, max = #objs}
end
end
function UnemployedCycle(obj)
local city = obj.city or UICity
local objs = city.labels.Unemployed or empty_table
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = T(6859, "Unemployed"), index = index, max = #objs}
end
end
function TraitCycle(trait, dome)
local trait_def = TraitPresets[trait]
if not trait_def then return end
return function(obj)
local objs = {}
local array = dome and dome.labels[trait] or UICity.labels.Colonist or empty_table
for _, colonist in ipairs(array) do
if colonist.traits[trait] then
objs[#objs + 1] = colonist
end
end
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = trait_def.display_name, index = index, max = #objs}
end
end
end
function WorkplaceCycle(obj)
local workplace = obj and obj.workplace
if not workplace then return end
local objs = {}
local colonists = workplace:GetUnitsInShifts()
for _, workshift in ipairs(colonists) do
for _, worker in ipairs(workshift) do
objs[#objs + 1] = worker
end
end
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = workplace.display_name, index = index, max = #objs}
end
end
function CommandCenterDroneCycle(obj)
local center = obj.command_center
local objs = center and center.drones
local index = type(objs) == "table" and table.find(objs, obj)
if index then
return index, objs, T{7679, "<name><right><index> / <max>", name = center:GetDisplayName(), index = index, max = #objs}
end
end
function InfopanelCycleUpdate(infopanel)
-- updates idCycleText, idCyclePrev and idCycleNext buttons
local index, objs, text = GetCycleInfo(infopanel.context)
infopanel.idCycleText:SetText(text or "")
-- find and update prev/next buttons
local idPrev = infopanel.idMainButtons:ResolveId("idPrev")
if idPrev then
idPrev:SetVisible(index)
end
local idNext = infopanel.idMainButtons:ResolveId("idNext")
if idNext then
idNext:SetVisible(index)
end
end
|
local M = {}
function M.readUvarint(r)
x = 0
s = 0
for i=0,10,1 do
local bs = assert(r:receive(1))
local b = string.byte(bs, 1)
if b == nil then
return nil, "failed to read"
end
if(b < 0x80) then
if (i > 9 or (i == 9 and b > 1)) then
return x, "overflow"
end
return x | (b << s), nil
end
x = x | ((b & 0x7f) << s)
s = s + 7
end
end
function M.UvarintBuf(x)
local buf = ""
local i = 0
while x > 0x80 do
buf = buf .. string.char((x & 0xff) | 0x80)
x = x >> 7
i = i + 1
end
buf = buf .. string.char(x & 0xff)
return buf
end
return M
|
function Aran_Water_Elementals(Unit, event, miscUnit, misc)
if((Unit:GetHealthPct() < 40) and (Didthat == 0)) then
Unit:SpawnCreature(21160, -11167.2, -1914.13, 232.009, 0, 18, 96000000);
Unit:SpawnCreature(21160, -11163.2, -1910.13, 232.009, 0, 18, 96000000);
Unit:SpawnCreature(21160, -11165.2, -1916.13, 232.009, 0, 18, 96000000);
Unit:SpawnCreature(21160, -11162.2, -1911.13, 232.009, 0, 18, 96000000);
Didthat = 1
else
end
end
function Aran_Polymorph(Unit, event, miscUnit, misc)
if((Unit:GetManaPct() < 20) and (Didthat == 1)) then
Unit:FullCastSpellOnTarget(23603,Unit:GetClosestPlayer())
Unit:FullCastSpell(32453)
Didthat = 2
else
end
end
function Aran_Fireball(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(20678, Unit:GetClosestPlayer())
end
function Aran_Conterspell(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29961, Unit:GetClosestPlayer())
end
function Aran_Conflagration(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(23023, Unit:GetClosestPlayer())
end
function Aran_FrostBolt(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(41486, Unit:GetClosestPlayer())
end
function Aran_Chains_Ice(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29991, Unit:GetClosestPlayer())
end
function Aran_Arcane_Missiles(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29955, Unit:GetClosestPlayer())
end
function Aran_Flame_Wreath(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(30004, Unit:GetRandomPlayer())
end
function Aran_Circular_Blizzard(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29952, Unit:GetClosestPlayer())
end
function Aran_Magnetic_Pull(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29979, Unit:GetClosestPlayer())
end
function Aran_Arcane_Explosion(Unit, event, miscUnit, misc)
Unit:FullCastSpellOnTarget(29973, Unit:GetClosestPlayer())
end
function Aran(Unit, event, miscUnit, misc)
Unit:RegisterEvent("Aran_Water_Elementals", 1000, 1)
Unit:RegisterEvent("Aran_Polymorph", 1000, 1)
Unit:RegisterEvent("Aran_Fireball", 9000, 0)
Unit:RegisterEvent("Aran_Conterspell", 13000, 0)
Unit:RegisterEvent("Aran_Conflagration", 15000, 0)
Unit:RegisterEvent("Aran_FrostBolt", 17000, 0)
Unit:RegisterEvent("Aran_Chains_Ice", 20000, 0)
Unit:RegisterEvent("Aran_Arcane_Missiles", 25000, 0)
Unit:RegisterEvent("Aran_Flame_Wreath", 30000, 0)
Unit:RegisterEvent("Aran_Circular_Blizzard", 60000, 0)
Unit:RegisterEvent("Aran_Magnetic_Pull", 90000, 0)
Unit:RegisterEvent("Aran_Arcane_Explosion", 91000, 0)
end
RegisterUnitEvent(16524, 1, "Aran")
--[[Shade of Aran yells: At last the nightmare is over...
Shade of Aran yells: Back to the cold dark with you!
Shade of Aran yells: Burn, you hellish fiends!
Shade of Aran yells: I am not some simple jester! I am Nielas Aran!
Shade of Aran yells: I want this nightmare to be over!
Shade of Aran yells: I'll freeze you all!
Shade of Aran yells: I'll not be tortured again!
Shade of Aran yells: I'll show you: this beaten dog still has some teeth!
Shade of Aran yells: Please, no more! My son... he's gone mad!
Shade of Aran yells: Torment me no more!
Shade of Aran yells: Who are you? What do you want? Stay away from me!
Shade of Aran yells: Yes, yes my son is quite powerful... but I have powers of my own!
Shade of Aran says: I'm not finished yet! No, I have a few more tricks up my sleeve...]]
|
--
-- tests/actions/vstudio/vc200x/test_build_steps.lua
-- Test generation of custom build step elements.
-- Copyright (c) 2013 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vs200x_build_steps")
local vc200x = p.vstudio.vc200x
--
-- Setup/teardown
--
local wks, prj
function suite.setup()
p.escaper(p.vstudio.vs2005.esc)
wks, prj = test.createWorkspace()
end
local function prepare()
local cfg = test.getconfig(prj, "Debug")
vc200x.VCPreBuildEventTool(cfg)
end
---
-- Should output empty element wrapper on no build steps.
---
function suite.noCommandLine_onNoBuildSteps()
prepare()
test.capture [[
<Tool
Name="VCPreBuildEventTool"
/>
]]
end
---
-- Should insert CR-LF at end of each command line.
---
function suite.addsCRLF()
prebuildcommands { "command_1", "command_2" }
prepare()
test.capture [[
<Tool
Name="VCPreBuildEventTool"
CommandLine="command_1
command_2"
/>
]]
end
--
-- If a message is specified, it should be included.
--
function suite.onMessageProvided()
prebuildcommands { "command1" }
prebuildmessage "Pre-building..."
prepare()
test.capture [[
<Tool
Name="VCPreBuildEventTool"
Description="Pre-building..."
CommandLine="command1"
/>
]]
end
|
local fun = require "nvim-lsp-installer.core.functional.function"
local _ = {}
_.equals = fun.curryN(function(expected, value)
return value == expected
end, 2)
_.prop_eq = fun.curryN(function(property, value, tbl)
return tbl[property] == value
end, 3)
_.prop_satisfies = fun.curryN(function(predicate, property, tbl)
return predicate(tbl[property])
end, 3)
return _
|
local _, private = ...
if private.isClassic then return end
--[[ Lua Globals ]]
-- luacheck: globals
--[[ Core ]]
local Aurora = private.Aurora
local Hook, Skin = Aurora.Hook, Aurora.Skin
local Util = Aurora.Util
do --[[ AddOns\Blizzard_AzeriteUI.lua ]]
do --[[ Blizzard_AzeriteEmpoweredItemUI.xml ]]
Hook.AzeriteEmpoweredItemUIMixin = {}
function Hook.AzeriteEmpoweredItemUIMixin:AdjustSizeForTiers(numTiers)
if numTiers == 3 then
self:SetSize(474, 460)
elseif numTiers == 4 then
self:SetSize(615, 601)
elseif numTiers == 5 then
self:SetSize(754, 740)
end
self.transformTree:GetRoot():SetLocalPosition(_G.CreateVector2D(self.ClipFrame.BackgroundFrame:GetWidth() * .5, self.ClipFrame.BackgroundFrame:GetHeight() * .5))
end
end
end
do --[[ AddOns\Blizzard_AzeriteUI.xml ]]
do --[[ Blizzard_AzeriteEmpoweredItemUITemplates.xml ]]
function Skin.AzeriteEmpoweredItemUITemplate(Frame)
Util.Mixin(Frame, Hook.AzeriteEmpoweredItemUIMixin)
Skin.PortraitFrameTemplate(Frame.BorderFrame)
local shadow = Frame.BorderFrame:CreateTexture(nil, "ARTWORK")
shadow:SetAllPoints(Frame.BorderFrame.TitleText)
shadow:SetAtlas("Azerite-TopShadow")
Frame.ClipFrame:SetPoint("TOPLEFT")
Frame.ClipFrame:SetPoint("BOTTOMRIGHT")
end
end
end
function private.AddOns.Blizzard_AzeriteUI()
----====####$$$$%%%%$$$$####====----
-- AzeriteEmpowedItemDataSource --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%%%%%%%%%%$$$$####====----
-- Blizzard_AzeriteEmpoweredItemUITemplates --
----====####$$$$%%%%%%%%%%%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- AzeritePowerLayoutInfo --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- AzeritePowerModelInfo --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%$$$$####====----
-- AzeriteEmpoweredItemPowerMixin --
----====####$$$$%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- AzeriteEmpoweredItemTierMixin --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- AzeriteEmpoweredItemSlotMixin --
----====####$$$$%%%%%$$$$####====----
----====####$$$$%%%%%$$$$####====----
-- Blizzard_AzeriteEmpoweredItemUI --
----====####$$$$%%%%%$$$$####====----
Skin.AzeriteEmpoweredItemUITemplate(_G.AzeriteEmpoweredItemUI)
end
|
-- Copyright (c) 2020-2021 shadmansaleh
-- MIT license, see LICENSE for more details.
-- Credit: challsted(lightline)
local molokai = {}
local colors = {
black = '#232526',
gray = '#808080',
white = '#f8f8f2',
cyan = '#66d9ef',
green = '#a6e22e',
orange = '#ef5939',
pink = '#f92672',
red = '#ff0000',
yellow = '#e6db74',
}
molokai.normal = {
a = { fg = colors.black, bg = colors.cyan , gui = 'bold', },
b = { fg = colors.black, bg = colors.pink , },
c = { fg = colors.orange, bg = colors.black , }
}
molokai.insert = {
a = { fg = colors.black, bg = colors.green , gui = 'bold', },
}
molokai.visual = {
a = { fg = colors.black, bg = colors.yellow , gui = 'bold', },
}
molokai.replace = {
a = { fg = colors.black, bg = colors.red , gui = 'bold', },
}
molokai.inactive = {
a = { fg = colors.pink, bg = colors.black , gui = 'bold', },
b = { fg = colors.white, bg = colors.pink , },
c = { fg = colors.gray, bg = colors.black , },
}
return molokai
|
furion_wrath_of_nature_lua = class({})
LinkLuaModifier( "modifier_furion_wrath_of_nature_thinker_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
function furion_wrath_of_nature_lua:OnAbilityPhaseStart()
local nFXIndex = ParticleManager:CreateParticle( "particles/units/heroes/hero_furion/furion_wrath_of_nature_cast.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetCaster() )
ParticleManager:SetParticleControlEnt( nFXIndex, 1, self:GetCaster(), PATTACH_POINT_FOLLOW, "attach_attack1", self:GetCaster():GetOrigin(), false )
ParticleManager:ReleaseParticleIndex( nFXIndex )
return true
end
--------------------------------------------------------------------------------
function furion_wrath_of_nature_lua:OnSpellStart()
self.hTarget = self:GetCursorTarget()
self.vTargetPos = self:GetCursorPosition()
EmitSoundOn( "Hero_Furion.WrathOfNature_Cast", self:GetCaster() )
CreateModifierThinker( self:GetCaster(), self, "modifier_furion_wrath_of_nature_thinker_lua", kv, self.vTargetPos, self:GetCaster():GetTeamNumber(), false )
end
--------------------------------------------------------------------------------
function furion_wrath_of_nature_lua:GetAssociatedSecondaryAbilities()
return "furion_force_of_nature_lua"
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
|
--
-- Created by IntelliJ IDEA.
-- User: xiaofa
-- Date: 2016/3/29
-- Time: 15:48
-- To change this template use File | Settings | File Templates.
--
local _M = {
local_ip="10.116.163.54",
port="80",
db_host = "qdm217211123.my3w.com",
db_port = "3306",
db_user = "qdm217211123",
db_password = "gonzoopera",
db_name = "qdm217211123_db",
db_charset = "utf8"
};
_M.server_id = ngx.md5(_M.local_ip..':'.._M.port);
---
-- dump
-- @param obj
-- @param n
--
local function dump(obj,n)
local str = '';
n = n or 0;
for key,value in pairs(obj) do
local t = type(value)
str = str.."\n"..string.rep(' ', n*4)..key..' - '..t
if (t == 'table') then
str = str.."\n"..dump(value,n+1);
end
if (t == 'string' or t == 'number') then
str = str.."\n"..string.rep(' ', (n+1)*4)..value
end
end
return str;
end
---
-- 转换为16进制
-- @param IN
--
local function DEC_HEX(IN)
return IN;
-- local B,K,OUT,I,D=16,"0123456789ABCDEF","",0
-- while IN>0 do
-- I=I+1
-- IN,D=math.floor(IN/B),math.mod(IN,B)+1
-- OUT=string.sub(K,D,D)..OUT
-- end
-- return OUT
end
_M.dump = dump;
_M.DEC_HEX = DEC_HEX;
return _M;
|
local AL = _G.AtlasLoot.GetLocales("esES")
if not AL then return end
-- These localization strings are translated on WoWAce: https://www.wowace.com/projects/atlasloot-enhanced/localization
AL["--- or ---"] = "--- o ---"
AL["%s will finish loading after combat."] = "%s terminará de cargarse después del combate"
AL["/al - Open the AtlasLoot window."] = "/al - Abrir la ventana de AtlasLoot"
AL["/al mmb - Toggle MiniMapButton"] = "/al mmb - Activar botón del minimapa"
AL["/al options - Open AtlasLoot Options window."] = "/al options - Abre la ventana de opciones de AtlasLoot."
AL["/al slash - Prints a list of all slash commands."] = "/al slash - Imprime un listado de todos los comandos 'slash'"
AL["/al togglebg - Toggle the background image on loottables."] = "/al togglebg - Activar la imagen de fondo en las tablas de botín."
AL["|cff00ff00Right-Click:|r Change Spec"] = "|cff00ff00Click-Derecho:|r Cambiar Especialización"
AL["25 Player"] = "25 Jugadores"
AL["25 Player Heroic"] = "25 jugadores heroico"
AL["Achievement & Quest Rewards"] = "Recompensas de Logros y Misiones"
AL["Achievements"] = "Logros"
AL["Add achievement link into chat"] = "Añadir un enlace al logro en el chat"
AL["Add item into chat"] = "Añadir item en el chat"
AL["Add profession link into chat"] = "Añadir enlace a la profesión en el chat"
AL["Add sound into chat"] = "Añadir sonido en el chat"
AL["Aged Dalaran Wizard"] = "Zahorí de Dalaran envejecido"
AL["Amulets"] = "Amuletos"
AL["Apexis Crystal"] = "Cristal apexis"
AL["AQ Enchants"] = "Encantamientos de AQ"
AL["Arakkoa"] = "Arakkoa"
AL["Arena Reward"] = "Recompensas de Arenas"
AL["Argent Tournament"] = "Torneo Argenta"
AL["Armor"] = "Armadura"
AL["Armor Enhancements"] = "Mejoras de Armadura"
AL["AtlasLoot"] = "AtlasLoot"
AL["AtlasLoot Modules"] = "Módulos de AtlasLoot"
AL["AtlasLoot Search"] = "Búsqueda de AtlasLoot"
AL["AtlasLoot Set View"] = "Establecer vista de AtlasLoot"
AL["AtlasLoot_Loader_is_no_longer_in_use"] = [=[AtlasLoot_Loader ya no está en uso.
Elimínalo de tu carpeta de AddOns]=]
AL["AtlasLoot_Minimap_Clicks"] = [=[|cffFF0000Click: |cffFFFFFFAbrir AtlasLoot
|cffFF0000Shift+Click: |cffFFFFFFOpciones AtlasLoot]=]
AL["Attack/Spell Power"] = "Poder de Ataque/Hechizo"
AL["Attributes"] = "Atributos"
AL["Avatar of the Martyred"] = "Avatar de los Martirizados"
AL["Ayla Shadowstorm"] = "Ayla Ventiscaumbría"
AL["Azeroth"] = "Azeroth"
AL["Bags"] = "Bolsas"
AL["Banquets/Feasts"] = "Banquetes/Festines"
AL["Best Friend"] = "Mejor amigo"
AL["Black Market Auction House"] = "Casa de Subastas del Mercado Negro"
AL["Blue Gems"] = "Gemas azules"
AL["BoE World Epics"] = "Épicos del mundo BoE"
AL["Bonus Loot"] = "Botín Extra"
AL["Boots"] = "Botas"
AL["BoP Gems"] = "Gemas Ligadas al Recogerlas"
AL["Bow"] = "Arco"
AL["Bracers"] = "Brazales"
AL["Brew of the Month Club"] = "Club de la cerveza del mes"
AL["Brewfest"] = "Fiesta de la Cerveza"
AL["Candy"] = "Dulce"
AL["Card Game Tabards"] = "Tabardos del Juego de Cartas"
AL["Challenge Mode Armor Sets"] = "Conjuntos de Armadura en Modo Desafío"
AL["Challenge Mode Gear"] = "Equipo del Modo Desafío"
AL["Chat Link"] = "Enlace de chat"
AL["Chest"] = "Pechera"
AL["Children's Week"] = "Semana de los Niños"
AL["Class Sets"] = "Conjuntos de clase"
AL["Classic Sets"] = "Equipos Clásicos"
AL["Click to open Atlas instance map."] = "Haz clic para abrir el mapa de la mazmorra de Atlas"
AL["Click to open AtlasLoot window"] = "Clic para abrir la ventana de AtlasLoot"
AL["Click to open WoW instance map."] = "Clic para abrir el mapa del WoW de la instancia."
AL["Cloak"] = "Capa"
AL["Cloaks"] = "Capas"
AL["Cloth"] = "Tela"
AL["Cogwheels"] = "Engranajes"
AL["Collections"] = "Colecciones"
AL["Command %s not found. Use '/al slash' for a full list of commands"] = "Comando %s no encontrado. Use '/al slash' para obtener un listado completo de comandos"
AL["Common Rewards"] = "Recompensas Comunes"
AL["Copy Box"] = "Cuadro de copiado"
AL["Crafting"] = "Artesanía"
AL["Crossbow"] = "Ballesta"
AL["Custom Modules"] = "Módulos personalizados"
AL["Dagger"] = "Daga"
AL["Damek Bloombeard"] = "Damek Barbaflorida"
AL["Darkmoon Cards"] = "Cartas Luna Negra"
AL["Darkmoon Faire"] = "Feria de la Luna Negra"
AL["Day of the Dead"] = "Festividad de los Muertos"
AL["Defias Overseer"] = "Sobrestante Defias"
AL["Dire Maul Books"] = "Libros de La Masacre"
AL["Dire Maul North Tribute Chest"] = "Cofre de Tributos de La Masacre Norte"
AL["Don Carlos"] = "Don Carlos"
AL["Draenei"] = "Draenei"
AL["Draenor Clans"] = "Clanes de Draenor"
AL["Dress up"] = "Vestirse"
AL["Drinks"] = "Bebidas"
AL["Droprate:"] = "Probabilidad de caída:"
AL["Druid of the Fang"] = "Druida del Colmillo"
AL["Dungeon %d Sets"] = "Set %d de Mazmorra"
AL["Dungeon Sets"] = "Set de Mazmorra"
AL["Dungeons"] = "Mazmorras"
AL["Dwarf"] = "Enano"
AL["Elite"] = "Élite"
AL["Elixirs"] = "Elixires"
AL["Entrance"] = "Entrada"
AL["Exalted"] = "Exaltado"
AL["Factions"] = "Facciones"
AL["Feast of Winter Veil"] = "Festival de Invierno"
AL["Felvine Shard"] = "Fragmento de gangrevid"
AL["Firestone Vendor"] = "Vendedor de Piedras de fuego"
AL["Firework"] = "Fuegos Artificiales"
AL["First Fragment Guardian"] = "Guardián del primer trozo"
AL["First Prize"] = "Primer precio"
AL["Fishing Pole"] = "Caña de pescar"
AL["Fist Weapon"] = "Arma de puño"
AL["Flasks"] = "Frascos"
AL["Food"] = "Comida"
AL["Food without Buffs"] = "Comidas sin beneficios"
AL["Fossil"] = "Fósil"
AL["Friend"] = "Amigo"
AL["Garrison"] = "Ciudadela"
AL["Gifts & Presents"] = "Regalos"
AL["Gloves"] = "Guantes"
AL["Glyphs"] = "Glifos"
AL["Good Friend"] = "Buen Amigo"
AL["Green Gems"] = "Gemas verdes"
AL["Guild"] = "Hermandad"
AL["Gun"] = "Arma de fuego"
AL["Hallow's End"] = "Halloween"
AL["Harvest Festival"] = "Festival de la Cosecha"
AL["Heirloom"] = "Reliquia"
AL["Heroic"] = "Heróico"
AL["ilvl %d"] = "ilvl %d"
AL["Incompatible Atlas Detected"] = "Se ha detectado un Atlas incompatible "
AL["It has been detected that your version of Atlas does not match the version that Atlasloot is tuned for (%s/%s). Depending on changes, there may be the occasional error, so please visit http://www.atlasmod.com as soon as possible to update."] = "Se ha detectado que tu versión de Atlas no es compatible con la versión programada para Atlasloot (%s/%s). Dependiendo de los cambios, pueden surgir algunos errores, visita http://www.atlasmod.com lo antes posible."
AL["Item Enhancements"] = "Objetos de Mejora"
AL["Items"] = "Objetos"
AL["Knot Thimblejack"] = "Knot Thimblejack"
AL["Leather"] = "Cuero"
AL["Legacy Justice Points Gears"] = "Equipo de puntos de justicia de legado"
AL["Legacy Valor Points Gears"] = "Equipo de puntos de valor de legado"
AL["Legendary Items"] = "Objetos legendarios"
AL["Legion Season %d"] = "Temporada %d de Legion"
AL["Legion Season %d Elite"] = "Temporada %d élite de Legion"
AL["Link the item in chat"] = "Vincula el objeto en el chat"
AL["Loading Data ..."] = "Cargando datos..."
AL["Love is in the Air"] = "El amor está en el aire"
AL["Lunar Festival"] = "Festival Lunar"
AL["Mail"] = "Correo"
AL["Mantid"] = "Mantide"
AL["Master Elemental Shaper Krixix"] = "Maestro de los Elementos Formacio Krixix"
AL["Meta Gems"] = "Gemas meta"
AL["Midsummer Fire Festival"] = "Festival del Solsticio de Verano"
AL["Miscellaneous"] = "Misceláneo"
AL["Model"] = "Modelo"
AL["Module %s is deactivated."] = "El módulo %s está desactivado."
AL["Module %s is not installed."] = "El módulo %s no está instalado."
AL["Mogu"] = "Mogu"
AL["Mounts"] = "Monturas"
AL["Mythic"] = "Mítico"
AL["Neck"] = "Cuello"
AL["Necklaces"] = "Collares"
AL["Nerubian"] = "Nerubiano"
AL["Night Elf"] = "Elfo de la Noche"
AL["No longer available"] = "No disponible"
AL["No module found."] = "Módulo no encontrado"
AL["Noblegarden"] = "El jardín de los nobles"
AL["Non-Playable Race Masks"] = "Máscaras de razas no jugables"
AL["Non-Set Gear"] = "Equipamiento No-Conjunto"
AL["Normal"] = "Normal"
AL["Off-Hands"] = "Mano izquierda"
AL["Ogre"] = "Ogro"
AL["Ogre Tannin Basket"] = "Cesta de Ogro Tanino"
AL["OK"] = "Vale"
AL["Old Remedies"] = "Antiguos remedios"
AL["One-Hand, Axe"] = "Una mano, Hacha"
AL["One-Hand, Mace"] = "Una mano, Maza"
AL["One-Hand, Sword"] = "Una mano, Espada"
AL["Orange Gems"] = "Gemas naranjas"
AL["Orc"] = "Orco"
AL["Other Buffs"] = "Otros Beneficios"
AL["Overcharged Manacell"] = "Célula de maná sobrecargada"
AL["Pandaren"] = "Pandaren"
AL["Patterns/Plans"] = "Patrones/Recetas"
AL["Permanent/Recurring Events"] = "Eventos Permanentes/Recurrentes"
AL["Pets"] = "Mascotas"
AL["Pilgrim's Bounty"] = "Generosidad del Peregrino"
AL["Plate"] = "Placas"
AL["Playable Race Masks"] = "Máscaras de razas jugables"
AL["Polearm"] = "Arma de asta"
AL["Potions"] = "Pociones"
AL["Primal Trader"] = "Comerciante Primigenio"
AL["Primary Professions"] = "Profesiones Primarias"
AL["Prismatic Gems"] = "Gemas prismáticas"
AL["Purple Gems"] = "Gemas moradas"
AL["PvP"] = "JcJ"
AL["Raid Finder"] = "Buscador de bandas"
AL["Raids"] = "Bandas"
AL["Rajaxx's Captains"] = "Capitanes de Rajaxx"
AL["Rank %d"] = "Rango %d"
AL["Rare"] = "Raro"
AL["Rare Fish"] = "Pescados raros"
AL["Rare Fish Rewards"] = "Recompensas raras de pesca"
AL["Ratings"] = "Puntuaciones"
AL["Reagents"] = "Consumibles"
AL["Recipes"] = "Recetas"
AL["Red Gems"] = "Gemas rojas"
AL["Relic"] = "Reliquia"
AL["Removed"] = "Quitado"
AL["Replica available at Darkmoon Faire"] = "Réplica disponible en la Feria de la Luna Negra"
AL["Required module %s is currently disabled."] = "El módulo %s requerido está desactivado."
AL["Required module %s is not installed."] = "El módulo %s requerido no está instalado"
AL["Rewards"] = "Recompensas"
AL["Right-click to close Atlas window."] = "Clic derecho para cerrar la ventana de Atlas."
AL["Ring"] = "Anillo"
AL["Rings"] = "Anillos"
AL["Runes"] = "Runas"
AL["Scopes"] = "Miras"
AL["Scrolls"] = "Pergaminos"
AL["Season %d"] = "Temporada %d"
AL["Seasonal Events"] = "Eventos de Temporada"
AL["Second Fragment Guardian"] = "Guardián del segundo trozo"
AL["Secondary Professions"] = "Profesiones Secundarias"
AL["Select Module"] = "Seleccionar módulo"
AL["Select Subcategory"] = "Seleccionar Sub-categoria"
AL["Servant's Quarter Animal Bosses"] = "Jefes Animales en las Alcobas de los Sirvientes"
AL["Set"] = "Conjunto"
AL["Sets"] = "Conjuntos"
AL["Setup"] = "Configuración"
AL["Shared"] = "Compartido"
AL["Shared Boss Loot"] = "Botín compartido por los jefes"
AL["Shattered Hand Executioner"] = "Verdugo Mano Destrozada"
AL["Shen'dralar Provisioner"] = "Proveedor Shen'dralar"
AL["Shield"] = "Escudo"
AL["Shields"] = "Escudos"
AL["Shirts"] = "Camisas"
AL["Shop"] = "Tienda"
AL["Shoulder"] = "Hombros"
AL["Show Mount in Journal"] = "Monstrar montura en guía"
AL["Show Pet in Journal"] = "Mostrar Mascota en guía"
AL["Shows items for all %s specializations."] = "Muestra objetos para todas las %s especializaciones."
AL["Shows the item in the Dressing room"] = "Muestra el objeto en el probador"
AL["Shows the sound in the copy box"] = "Muestra el sonido en la caja de copiado"
AL["Slash commands:"] = "Comandos \"/\":"
AL["Smokywood Pastures Vendor"] = "Vendedor de Pastos de Bosquehumeante"
AL["Sounds"] = "Sonidos"
AL["Source"] = "Origen"
AL["Special"] = "Especial"
AL["Special Rewards"] = "Recompensas Especiales"
AL["Staff"] = "Bastón"
AL["Stats"] = "Estadisticas"
AL["Staves"] = "Bastones"
AL["Stranglethorn Fishing Extravaganza"] = "Concurso de Pesca"
AL["Summon"] = "Invocar"
AL["Tabards"] = "Tabardos"
AL["The Grim Guzzler"] = "El Tragapenas"
AL["The Secret Safe"] = "El secreto seguro"
AL["The Vault"] = "La caja fuerte"
AL["Third Fragment Guardian"] = "Guardián del tercer trozo"
AL["Thomas Yance"] = "Thomas Yance"
AL["Tier %d Sets"] = "Conjuntos de Tier %d"
AL["Tier Sets"] = "Conjuntos de Equipo"
AL["Tier Sets - per Class"] = "Conjuntos de equipo - por clase"
AL["Timed Reward Chest"] = "Cofre de recompensa con tiempo"
AL["Timewalking Dungeon Event"] = "Evento de mazmorra de Paseo en el tiempo"
AL["Tinker"] = "Artilugio"
AL["Toggle AtlasLoot"] = "Abre/Cierra AtlasLoot"
AL["Tol'vir"] = "Tol'vir"
AL["Toys"] = "Juguetes"
AL["Training Projects"] = "Proyectos de Entrenamiento"
AL["Transmoggable Replicas"] = "Réplicas de transfiguración"
AL["Transmutes"] = "Transmutaciones"
AL["Trash Mobs"] = "Bichos varios"
AL["Trinkets"] = "Abalorios"
AL["Troll"] = "Trol"
AL["Two-Hand, Axe"] = "Dos manos, Hacha"
AL["Two-Hand, Mace"] = "Dos manos, Maza"
AL["Two-Hand, Sword"] = "Dos manos, Espada"
AL["Unfinished Painting"] = "Pintura sin terminar"
AL["Unobtainable Tabards"] = "Tabardos no adquiribles"
AL["Vanity Gear"] = "Equipamiento de Vanidad"
AL["Varlan Highbough"] = "Varlan Ramaalta"
AL["Vendor"] = "Vendedor"
AL["Vendors"] = "Vendedores"
AL["Vrykul"] = "Vrykul"
AL["Wand"] = "Varita"
AL["Wands"] = "Varitas"
AL["Warlords Season %d"] = "Temporada de Warlords %d"
AL["Weapon Enhancements"] = "Mejoras de Armas"
AL["Weapons"] = "Armas"
AL["Welcome to Atlasloot Enhanced. Please take a moment to set your preferences."] = "Te damos la bienvenida a Atlasloot Enhanced. Dedícale un momento para establecer tus preferencias."
AL["World Bosses"] = "Jefes del Mundo"
AL["World Events"] = "Eventos mundo"
AL["Yellow Gems"] = "Gemas amarillas"
AL["Zen'Vorka"] = "Zen'Vorka"
|
--[[
More Blocks: conversion
Copyright (c) 2011-2017 Hugo Locurcio and contributors.
Licensed under the zlib license. See LICENSE.md for more information.
--]]
-- Function to convert all stairs/slabs/etc nodes from
-- inverted, wall, etc to regular + 6d facedir
local dirs1 = {21, 20, 23, 22, 21}
local dirs2 = {15, 8, 17, 6, 15}
local dirs3 = {14, 11, 16, 5, 14}
function stairsplus:register_6dfacedir_conversion(modname, material)
--print("Register stairsplus 6d facedir conversion")
--print('ABM for '..modname..' "'..material..'"')
local objects_list1 = {
modname.. ":slab_" ..material.. "_inverted",
modname.. ":slab_" ..material.. "_quarter_inverted",
modname.. ":slab_" ..material.. "_three_quarter_inverted",
modname.. ":stair_" ..material.. "_inverted",
modname.. ":stair_" ..material.. "_wall",
modname.. ":stair_" ..material.. "_wall_half",
modname.. ":stair_" ..material.. "_wall_half_inverted",
modname.. ":stair_" ..material.. "_half_inverted",
modname.. ":stair_" ..material.. "_right_half_inverted",
modname.. ":panel_" ..material.. "_vertical",
modname.. ":panel_" ..material.. "_top",
}
local objects_list2 = {
modname.. ":slab_" ..material.. "_wall",
modname.. ":slab_" ..material.. "_quarter_wall",
modname.. ":slab_" ..material.. "_three_quarter_wall",
modname.. ":stair_" ..material.. "_inner_inverted",
modname.. ":stair_" ..material.. "_outer_inverted",
modname.. ":micro_" ..material.. "_top"
}
for _, object in pairs(objects_list1) do
local flip_upside_down = false
local flip_to_wall = false
local dest_object = object
if string.find(dest_object, "_inverted") then
flip_upside_down = true
dest_object = string.gsub(dest_object, "_inverted", "")
end
if string.find(object, "_top") then
flip_upside_down = true
dest_object = string.gsub(dest_object, "_top", "")
end
if string.find(dest_object, "_wall") then
flip_to_wall = true
dest_object = string.gsub(dest_object, "_wall", "")
end
if string.find(dest_object, "_vertical") then
flip_to_wall = true
dest_object = string.gsub(dest_object, "_vertical", "")
end
if string.find(dest_object, "_half") and not string.find(dest_object, "_right_half") then
dest_object = string.gsub(dest_object, "_half", "_right_half")
elseif string.find(dest_object, "_right_half") then
dest_object = string.gsub(dest_object, "_right_half", "_half")
end
--print(" +---> convert " ..object)
--print(" | to " ..dest_object)
minetest.register_abm({
nodenames = {object},
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local fdir = node.param2 or 0
local nfdir
if flip_upside_down and not flip_to_wall then
nfdir = dirs1[fdir + 2]
elseif flip_to_wall and not flip_upside_down then
nfdir = dirs2[fdir + 1]
elseif flip_to_wall and flip_upside_down then
nfdir = dirs3[fdir + 2]
end
minetest.set_node(pos, {name = dest_object, param2 = nfdir})
end
})
end
for _, object in pairs(objects_list2) do
local flip_upside_down = false
local flip_to_wall = false
local dest_object = object
if string.find(dest_object, "_inverted") then
flip_upside_down = true
dest_object = string.gsub(dest_object, "_inverted", "")
end
if string.find(dest_object, "_top") then
flip_upside_down = true
dest_object = string.gsub(dest_object, "_top", "")
end
if string.find(dest_object, "_wall") then
flip_to_wall = true
dest_object = string.gsub(dest_object, "_wall", "")
end
--print(" +---> convert " ..object)
--print(" | to " ..dest_object)
minetest.register_abm({
nodenames = {object},
interval = 1,
chance = 1,
action = function(pos, node, active_object_count, active_object_count_wider)
local fdir = node.param2
local nfdir = 20
if flip_upside_down and not flip_to_wall then
nfdir = dirs1[fdir + 1]
elseif flip_to_wall and not flip_upside_down then
nfdir = dirs2[fdir + 2]
end
minetest.set_node(pos, {name = dest_object, param2 = nfdir})
end
})
end
end
|
Config = {}
Config.Locations = {
[1] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(26.5906, -1392.0261, 27.3634),
},
[2] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(167.1034, -1719.4704, 27.2916),
},
[3] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(-74.5693, 6427.8715, 29.4400),
},
[4] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(-1200.4, -1720.46, 3.40),
},
[5] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(1363.22, 3592.7, 34.41),
},
[6] = {
["label"] = "Hands Free Carwash",
["coords"] = vector3(-699.6325, -932.7043, 17.0139),
}
}
Config.DefaultPrice = 20
|
--ZFUNC-cdr-v1
local function cdr( arr ) --> tail
if not arr then return nil end
local n = #arr
if n <= 1 then return nil end
local tail = {}
for i = 2, n do
table.insert( tail, arr[ i ] )
end
return tail
end
return cdr
|
local lsp,api = vim.lsp,vim.api
local config = require('lspsaga').config_values
local window = require('lspsaga.window')
local libs = require('lspsaga.libs')
local action = require('lspsaga.action')
local implement = {}
function implement.lspsaga_implementation(timeout_ms)
local active,msg = libs.check_lsp_active()
if not active then print(msg) return end
local method = "textDocument/implementation"
local params = lsp.util.make_position_params()
local result = vim.lsp.buf_request_sync(0,method,params,timeout_ms or 1000)
if result == nil or vim.tbl_isempty(result) then
print("No location found: " .. method)
return nil
end
result = {vim.tbl_deep_extend("force", {}, unpack(result))}
if vim.tbl_islist(result) and not vim.tbl_isempty(result[1]) then
local uri = result[1].result[1].uri or result[1].result[1].targetUri
if #uri == 0 then return end
local bufnr = vim.uri_to_bufnr(uri)
if not vim.api.nvim_buf_is_loaded(bufnr) then
vim.fn.bufload(bufnr)
end
local range = result[1].result[1].targetRange or result[1].result[1].range
local start_line = 0
if range.start.line - 3 >= 1 then
start_line = range.start.line - 3
else
start_line = range.start.line
end
local content =
vim.api.nvim_buf_get_lines(bufnr, start_line, range["end"].line + 1 +
config.max_preview_lines, false)
content = vim.list_extend({config.definition_preview_icon.."Lsp Implements",""},content)
local filetype = vim.api.nvim_buf_get_option(bufnr, "filetype")
local opts = {
relative = "cursor",
style = "minimal",
}
local WIN_WIDTH = vim.fn.winwidth(0)
local max_width = math.floor(WIN_WIDTH * 0.5)
local width, _ = vim.lsp.util._make_floating_popup_size(content, opts)
if width > max_width then
opts.width = max_width
end
local content_opts = {
contents = content,
filetype = filetype,
}
local bf,wi = window.create_win_with_border(content_opts,opts)
libs.close_preview_autocmd({"CursorMoved", "CursorMovedI", "BufHidden", "BufLeave"},
wi)
vim.api.nvim_buf_add_highlight(bf,-1,"DefinitionPreviewTitle",0,0,-1)
api.nvim_buf_set_var(0,'lspsaga_implement_preview',{wi,1,config.max_preview_lines,10})
end
end
function implement.has_implement_win()
local has_win,data = pcall(api.nvim_buf_get_var,0,'lspsaga_implement_preview')
if not has_win then return false end
if api.nvim_win_is_valid(data[1]) then
return true
end
return false
end
function implement.scroll_in_implement(direction)
local has_hover_win,data = pcall(api.nvim_win_get_var,0,'lspsaga_implement_preview')
if not has_hover_win then return end
local hover_win,height,current_win_lnum,last_lnum = data[1],data[2],data[3],data[4]
if not api.nvim_win_is_valid(hover_win) then return end
current_win_lnum = action.scroll_in_win(hover_win,direction,current_win_lnum,last_lnum,height)
api.nvim_win_set_var(0,'lspsaga_implement_preview',{hover_win,height,current_win_lnum,last_lnum})
end
return implement
|
local function Probe(region)
return region:IsObjectType("Frame") and region:GetName():find("^StaticPopup%d+$") ~= nil
end
local function Describe(region, strings)
local speak = false
if not strings then
region = Vimp_Reader:GetRoot()
strings = {}
speak = true
end
table.insert(strings, "Popup")
if not speak then
return strings
end
Vimp_Say(strings)
end
local function OnShow(frame)
Vimp_Window:CreateDriver(frame, Probe, Describe)
Vimp_Reader:HandleWindow(frame)
end
for index = 1, STATICPOPUP_NUMDIALOGS do
_G["StaticPopup" .. index]:HookScript("OnShow", OnShow)
end
|
-- Turing machines
--
-- Collection of turing machines
-- affecting different parameters
--
-- TODO
--
-- Add midi and output control (similar to awake) and settings to map each machine that makes sense to a midi cc
-- Remove require for already imported libraries (i.e. util, see here https://monome.org/docs/norns/reference/#system-globals)
mu = require "musicutil"
ui = require 'ui'
util = require 'util'
fm = require 'formatters'
Machine = include('lib/machine')
machines = {}
current_machine = nil
engine.name = 'TuringEngine'
scale_notes = {}
alt = false
engine_types={'Pulse', 'Sin', 'Saw', 'Tri'}
ratcheting_options = {1, 2, 3, 4, 6, 8, 12, 16, 24}
releases_labels = {'4', '2', '1', '1/2', '1/4', '1/8', '1/16'}
releases_values = {4, 2, 1, 1/2, 1/4, 1/8, 1/16}
releases = {}
for i=1,#releases_labels do releases[releases_labels[i]] = releases_values end
ratcheting_metro = metro.init()
function init()
init_machines()
set_params()
build_scale()
screen.line_width(1)
screen.aa(1)
norns.enc.sens(1, 12)
ratcheting_metro.event = play_next_note
clock.run(update)
end
function init_machines()
local machine_ids = {"notes", "cutoff", "velocity", "ratcheting", "release", "probability", "pan"}
local machine_labels = {"Notes", "Cutoff", "Velocity", "Ratcheting", "Release", "Probability", "Pan"}
local previous = nil
local machine = nil
for i=1,#machine_ids do
machine = Machine.new(machine_ids[i], machine_labels[i])
if previous then
previous.next = machine
machine.previous = previous
end
previous = machine
machines[machine_ids[i]] = machine
machine:add_hidden_params()
machine:init_sequence()
end
current_machine = machines['notes']
end
function set_params()
params:add_separator("Common")
params:add{type="binary", id="running", name="Running", default=1, behavior='toggle',
action=function(x) if x == 1 then reset() end end}
params:add_group('Synth', 3)
local cs = controlspec.new(1,#engine_types,'lin',1,1,'')
params:add{type="control", id="type", name="Type", controlspec=cs,
formatter=function(param) return engine_types[param:get()] end,
action=function(x) engine.type(x) end}
cs = controlspec.new(1,#releases_labels,'lin',1,4,'')
params:add{type="control", id="attack", name="Attack", controlspec=cs,
formatter=function(param) return releases_labels[param:get()] end,
action=function(x) engine.attack(releases_values[x]) end}
cs = controlspec.new(0,1,'lin',0.05,0.5,'')
params:add{type="control", id="pw", name="Pulse width", controlspec=cs, action=function(x) engine.pw(x) end}
params:add_separator("Machines")
local cs_SEQL = controlspec.new(1,16,'lin',1,8,'')
local cs_KNOB = controlspec.new(0,100,'lin',1,50,'%')
local cs_CLKDIV = controlspec.new(1,16,'lin',1,1)
-- Notes
local machine = machines['notes']
params:add_group(machine.label, 10)
local cs_NOTE = controlspec.MIDINOTE:copy()
cs_NOTE.default = 48
cs_NOTE.step = 1
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_NOTE, function(param) return mu.note_num_to_name(param:get(), true) end)
params:add{type="control", id="root_note", name="Root note", controlspec=controlspec.new(0,11,'lin',1,0),
formatter=function(param) return mu.note_num_to_name(param:get(), false) end, action=function(x) build_scale() end}
params:add{type="number", id="scale", name="Scale", min=1, max=#mu.SCALES, default=1,
formatter=function(param) return mu.SCALES[param:get()].name end, action=function() build_scale() end}
local cs_OCT = controlspec.new(0,8,'lin',1,2,'')
params:add{type="control", id="min_oct", name="Min octave", controlspec=cs_OCT, formatter=fm.round(1),
action=function() build_scale() end}
cs_OCT = cs_OCT:copy()
cs_OCT.default = 3
params:add{type="control", id="max_oct", name="Max octave", controlspec=cs_OCT, formatter=fm.round(1),
action=function() build_scale() end}
machine:set_extra_params({'min_oct', 'max_oct'}, {'Min oct.', 'Max oct.'})
-- Cutoff
machine = machines['cutoff']
params:add_group(machine.label, 8)
local cs_FREQ = controlspec.new(50,5000,'exp',10,1000,'Hz')
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_FREQ)
cs_FREQ = cs_FREQ:copy()
cs_FREQ.default = 400
params:add_control("cutoff_min", "Min", cs_FREQ, fm.round(1))
cs_FREQ = cs_FREQ:copy()
cs_FREQ.default = 1600
params:add_control("cutoff_max", "Max", cs_FREQ, fm.round(1))
machine:set_extra_params({'cutoff_min', 'cutoff_max'}, {'Min', 'Max'})
-- Velocity
machine = machines['velocity']
params:add_group(machine.label, 8)
local cs_V = controlspec.MIDIVELOCITY:copy()
cs_V.default = 64
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_V)
cs_V = controlspec.MIDIVELOCITY:copy()
cs_V.default = 30
params:add_control("velocity_min", "Min", cs_V, fm.round(1))
cs_V = controlspec.MIDIVELOCITY:copy()
cs_V.default = 100
params:add_control("velocity_max", "Max", cs_V, fm.round(1))
machine:set_extra_params({'velocity_min', 'velocity_max'}, {'Min', 'Max'})
-- Ratcheting
machine = machines['ratcheting']
params:add_group(machine.label, 8)
local cs_RAT = controlspec.new(1,#ratcheting_options,'lin',1,1)
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_RAT)
cs_RAT = cs_RAT:copy()
params:add{type="control", id="ratcheting_min", name="Min", controlspec=cs_RAT, formatter=function(param) return ratcheting_options[param:get()] end}
cs_RAT = cs_RAT:copy()
cs_RAT.default = 4
params:add{type="control", id="ratcheting_max", name="Max", controlspec=cs_RAT, formatter=function(param) return ratcheting_options[param:get()] end}
machine:set_extra_params({'ratcheting_min', 'ratcheting_max'}, {'Min', 'Max'})
-- Release
machine = machines['release']
params:add_group(machine.label, 8)
local cs_DUR = controlspec.new(1,#releases_labels,'lin',1,3)
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_DUR)
cs_DUR = cs_DUR:copy()
params:add{type="control", id="release_min", name="Min", controlspec=cs_DUR, formatter=function(param) return releases_labels[param:get()] end}
cs_DUR = cs_DUR:copy()
cs_DUR.default = 5
params:add{type="control", id="release_max", name="Max", controlspec=cs_DUR, formatter=function(param) return releases_labels[param:get()] end}
machine:set_extra_params({'release_min', 'release_max'}, {'Min', 'Max'})
-- Probability
machine = machines['probability']
params:add_group(machine.label, 8)
local cs_PROB = controlspec.AMP:copy()
cs_PROB.default = 1
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_PROB)
cs_PROB = controlspec.AMP:copy()
cs_PROB.default = 0.75
params:add_control("probability_min", "Min", cs_PROB)
cs_PROB = controlspec.AMP:copy()
cs_PROB.default = 1
params:add_control("probability_max", "Max", cs_PROB)
machine:set_extra_params({'probability_min', 'probability_max'}, {'Min', 'Max'})
-- Pan
machine = machines['pan']
params:add_group(machine.label, 8)
local cs_PAN = controlspec.new(-1,1,'lin',0.1,0)
machine:add_params(cs_SEQL, cs_KNOB, cs_CLKDIV, cs_PAN)
cs_PAN = cs_PAN:copy()
cs_PAN.default = -0.3
params:add_control("pan_min", "Min", cs_PAN)
cs_PAN = cs_PAN:copy()
cs_PAN.default = 0.3
params:add_control("pan_max", "Max", cs_PAN)
machine:set_extra_params({'pan_min', 'pan_max'}, {'Min', 'Max'})
params:default()
-- Refresh dials of all machines to match default preset
for _, machine in pairs(machines) do
machine:refresh_dials_values(true, true)
end
end
function build_scale()
local min = math.min(params:get('min_oct'), params:get('max_oct')) + 1
local max = math.max(params:get('min_oct'), params:get('max_oct')) + 1
scale_notes = mu.generate_scale(params:get("root_note") + min * 12, params:get("scale"), max - min + 1)
-- Remove last note
scale_notes[#scale_notes] = nil
end
function round_value(value, min, max)
return value * math.abs(max - min) + math.min(min, max)
end
function round_index(index, min, max)
return math.floor(round_value(index, min, max) + 0.5)
end
function map_note(note, min_oct, max_oct)
return math.floor(round_value(note, (min_oct+1) * 12, (max_oct+2) * 12))
end
function update()
while true do
clock.sync(1)
if params:get('running') == 1 then
local ratcheting = ratcheting_options[machines['ratcheting']:get_next_value(round_index)]
play_next_note()
if ratcheting > 1 then
ratcheting_metro:start(clock:get_beat_sec() / ratcheting, ratcheting-1)
end
end
end
end
function play_next_note()
local probability = machines['probability']:get_next_value(round_value)
local should_play = math.random() <= probability
local release = releases_values[machines['release']:get_next_value(round_index)]
if should_play then engine.release(clock:get_beat_sec() * release) end
local velocity = machines['velocity']:get_next_value(round_value) / 127
if should_play then engine.amp(velocity) end
local cutoff = machines['cutoff']:get_next_value(round_value)
if should_play then engine.cutoff(cutoff) end
local pan = machines['pan']:get_next_value(round_value)
if should_play then engine.pan(pan) end
local note = mu.snap_note_to_array(machines['notes']:get_next_value(map_note), scale_notes)
if should_play then engine.hz(mu.note_num_to_freq(note)) end
redraw()
end
function reset()
for _, machine in pairs(machines) do
machine.position = 1
end
end
function clock.transport.start()
start()
end
function clock.transport.stop()
stop()
end
function clock.transport.reset()
reset()
end
function enc(index, delta)
if index==1 then
if delta < 0 and current_machine.previous then
current_machine = current_machine.previous
elseif delta > 0 and current_machine.next then
current_machine = current_machine.next
end
end
if current_machine:get_active() then
if not alt then
if index==2 then
current_machine:set_steps_delta(delta)
elseif index==3 then
current_machine:set_knob_delta(delta)
end
else
current_machine:extra_controls_delta(index, delta)
end
else
current_machine:extra_controls_delta(index, delta)
end
redraw()
end
function key(index, state)
if current_machine:get_active() then
if index == 1 then
alt = state == 1
current_machine:set_dials_active(not alt)
elseif index == 2 and state == 1 then
if alt then current_machine:move_to_next_position()
else current_machine:toggle_running() end
elseif index == 3 and state == 1 then
if alt then current_machine:randomize_current_step()
else current_machine:init_sequence() end
end
redraw()
end
end
function redraw()
screen.clear()
screen.fill()
current_machine:redraw()
screen.update()
end
|
require "Commandeer_CommandHandler"
Commandeer_CommandHandler.commands["/looc"] = function(param)
if not param or param == "" then
return "Usage: /looc [message]";
end
processSayMessage(string.format("*%s*%s: ((%s))", "teal", Commandeer_RPName.getRPName(), param))
end
Commandeer_CommandHandler.commands["/l"] = Commandeer_CommandHandler.commands["/looc"]
|
object_intangible_pet_massiff = object_intangible_pet_shared_massiff:new {
}
ObjectTemplates:addTemplate(object_intangible_pet_massiff, "object/intangible/pet/massiff.iff")
|
function plugindef()
finaleplugin.RequireSelection = true
finaleplugin.Author = "Carl Vine"
finaleplugin.AuthorURL = "http://carlvine.com/?cv=lua"
finaleplugin.Copyright = "CC0 https://creativecommons.org/publicdomain/zero/1.0/"
finaleplugin.Version = "v1.04"
finaleplugin.Date = "2022/06/15"
finaleplugin.CategoryTags = "Note"
finaleplugin.Notes = [[
Clear all music from the chosen layer in the surrently selected region.
(Note that all of a measure's layer will be cleared even if it is partially selected).
]]
return "Clear layer selective", "Clear layer selective", "Clear the chosen layer"
end
-- RetainLuaState will return global variable: clear_layer_number
--[[
$module Layer
]] --
local layer = {}
--[[
% copy
Duplicates the notes from the source layer to the destination. The source layer remains untouched.
@ region (FCMusicRegion) the region to be copied
@ source_layer (number) the number (1-4) of the layer to duplicate
@ destination_layer (number) the number (1-4) of the layer to be copied to
]]
function layer.copy(region, source_layer, destination_layer)
local start = region.StartMeasure
local stop = region.EndMeasure
local sysstaves = finale.FCSystemStaves()
sysstaves:LoadAllForRegion(region)
source_layer = source_layer - 1
destination_layer = destination_layer - 1
for sysstaff in each(sysstaves) do
staffNum = sysstaff.Staff
local noteentry_source_layer = finale.FCNoteEntryLayer(source_layer, staffNum, start, stop)
noteentry_source_layer:Load()
local noteentry_destination_layer = noteentry_source_layer:CreateCloneEntries(
destination_layer, staffNum, start)
noteentry_destination_layer:Save()
noteentry_destination_layer:CloneTuplets(noteentry_source_layer)
noteentry_destination_layer:Save()
end
end -- function layer_copy
--[[
% clear
Clears all entries from a given layer.
@ region (FCMusicRegion) the region to be cleared
@ layer_to_clear (number) the number (1-4) of the layer to clear
]]
function layer.clear(region, layer_to_clear)
layer_to_clear = layer_to_clear - 1 -- Turn 1 based layer to 0 based layer
local start = region.StartMeasure
local stop = region.EndMeasure
local sysstaves = finale.FCSystemStaves()
sysstaves:LoadAllForRegion(region)
for sysstaff in each(sysstaves) do
staffNum = sysstaff.Staff
local noteentrylayer = finale.FCNoteEntryLayer(layer_to_clear, staffNum, start, stop)
noteentrylayer:Load()
noteentrylayer:ClearAllEntries()
end
end
--[[
% swap
Swaps the entries from two different layers (e.g. 1-->2 and 2-->1).
@ region (FCMusicRegion) the region to be swapped
@ swap_a (number) the number (1-4) of the first layer to be swapped
@ swap_b (number) the number (1-4) of the second layer to be swapped
]]
function layer.swap(region, swap_a, swap_b)
local start = region.StartMeasure
local stop = region.EndMeasure
local sysstaves = finale.FCSystemStaves()
sysstaves:LoadAllForRegion(region)
-- Set layers for 0 based
swap_a = swap_a - 1
swap_b = swap_b - 1
for sysstaff in each(sysstaves) do
staffNum = sysstaff.Staff
local noteentrylayer_1 = finale.FCNoteEntryLayer(swap_a, staffNum, start, stop)
noteentrylayer_1:Load()
noteentrylayer_1.LayerIndex = swap_b
--
local noteentrylayer_2 = finale.FCNoteEntryLayer(swap_b, staffNum, start, stop)
noteentrylayer_2:Load()
noteentrylayer_2.LayerIndex = swap_a
noteentrylayer_1:Save()
noteentrylayer_2:Save()
end
end
function get_user_choice()
local vertical = 10
local horizontal = 110
local mac_offset = finenv.UI():IsOnMac() and 3 or 0 -- extra y-offset for Mac text box
local dialog = finale.FCCustomWindow()
local str = finale.FCString()
str.LuaString = plugindef()
dialog:SetTitle(str)
str.LuaString = "Clear Layer (1-4):"
local static = dialog:CreateStatic(0, vertical)
static:SetText(str)
static:SetWidth(horizontal)
local layer_choice = dialog:CreateEdit(horizontal, vertical - mac_offset)
layer_choice:SetInteger(clear_layer_number or 1) -- default layer 1
layer_choice:SetWidth(50)
dialog:CreateOkButton()
dialog:CreateCancelButton()
return (dialog:ExecuteModal(nil) == finale.EXECMODAL_OK), layer_choice:GetInteger()
end
function clear_layers()
local is_ok = false
is_ok, clear_layer_number = get_user_choice()
if not is_ok then -- user cancelled
return
end
if clear_layer_number < 1 or clear_layer_number > 4 then
finenv.UI():AlertNeutral("script: " .. plugindef(),
"The layer number must be\nan integer between 1 and 4\n(not " .. clear_layer_number .. ")")
return
end
if finenv.RetainLuaState ~= nil then
finenv.RetainLuaState = true
end
layer.clear(finenv.Region(), clear_layer_number)
end
clear_layers()
|
local diff = {
["axisDiffs"] = {
["a2001cdnil"] = {
["name"] = "Pitch",
["removed"] = {
[1] = {
["key"] = "JOY_Y",
},
},
},
["a2002cdnil"] = {
["name"] = "Roll",
["removed"] = {
[1] = {
["key"] = "JOY_X",
},
},
},
["a2003cdnil"] = {
["name"] = "Rudder",
["removed"] = {
[1] = {
["key"] = "JOY_RZ",
},
},
},
["a2004cdnil"] = {
["added"] = {
[1] = {
["filter"] = {
["curvature"] = {
[1] = -0.1,
},
["deadzone"] = 0,
["invert"] = false,
["saturationX"] = 1,
["saturationY"] = 1,
["slider"] = true,
},
["key"] = "JOY_RY",
},
},
["name"] = "Thrust",
["removed"] = {
[1] = {
["key"] = "JOY_Z",
},
},
},
["a3003cd30"] = {
["added"] = {
[1] = {
["key"] = "JOY_RZ",
},
},
["name"] = "HMCS SYMBOLOGY INT Knob",
},
["a3026cd2"] = {
["added"] = {
[1] = {
["key"] = "JOY_SLIDER2",
},
},
["name"] = "PITCH TRIM Wheel",
},
["a3046cd16"] = {
["added"] = {
[1] = {
["filter"] = {
["curvature"] = {
[1] = 0,
},
["deadzone"] = 0,
["invert"] = true,
["saturationX"] = 1,
["saturationY"] = 1,
["slider"] = false,
},
["key"] = "JOY_Y",
},
},
["name"] = "RDR CURSOR Switch - Y axis",
},
["a3047cd16"] = {
["added"] = {
[1] = {
["key"] = "JOY_X",
},
},
["name"] = "RDR CURSOR Switch - X axis",
},
},
["keyDiffs"] = {
["d179pnilunilcdnilvdnilvpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN13",
},
},
["name"] = "Communication menu",
},
["d3001pnilunilcd2vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN66",
},
},
["name"] = "DIGITAL BACKUP Switch - OFF",
},
["d3001pnilunilcd2vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN65",
},
},
["name"] = "DIGITAL BACKUP Switch - BACKUP",
},
["d3002pnilu3002cd12vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN102",
},
},
["name"] = "MAL & IND LTS Test Button",
},
["d3002pnilunilcd19vd-1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN95",
},
},
["name"] = "MASTER ARM Switch - SIMULATE",
},
["d3002pnilunilcd19vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN94",
},
},
["name"] = "MASTER ARM Switch - OFF",
},
["d3002pnilunilcd19vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN93",
},
},
["name"] = "MASTER ARM Switch - MASTER ARM",
},
["d3002pnilunilcd35vd0.1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN70",
},
},
["name"] = "IFF MASTER Knob - STBY",
},
["d3002pnilunilcd35vd0.3vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN71",
},
},
["name"] = "IFF MASTER Knob - NORM",
},
["d3002pnilunilcd35vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN69",
},
},
["name"] = "IFF MASTER Knob - OFF",
},
["d3003pnilu3003cd19vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN96",
},
},
["name"] = "EMER STORES JETTISON Button",
},
["d3003pnilu3003cd2vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN92",
},
},
["name"] = "BIT Switch - OFF/BIT",
},
["d3004pnilu3004cd3vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN91",
},
},
["name"] = "FLCS PWR TEST Switch - TEST",
},
["d3005pnilu3005cd28vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN105",
},
},
["name"] = "CRS Set / Brightness Control Knob - Depress",
},
["d3005pnilu3005cd3vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN89",
},
},
["name"] = "EPU/GEN Test Switch",
},
["d3006pnilunilcd11vd0.3vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN4",
},
},
["name"] = "MASTER Switch - FORM",
},
["d3006pnilunilcd11vd0.4vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN3",
},
},
["name"] = "MASTER Switch - NORM",
},
["d3006pnilunilcd11vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN5",
},
},
["name"] = "MASTER Switch - OFF",
},
["d3006pnilunilcd2vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN68",
},
},
["name"] = "TRIM/AP DISC Switch - DISC",
},
["d3006pnilunilcd2vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN67",
},
},
["name"] = "TRIM/AP DISC Switch - NORM",
},
["d3006pnilunilcd3vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN87",
},
},
["name"] = "PROBE HEAT Switch - OFF",
},
["d3006pnilunilcd3vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN86",
},
},
["name"] = "PROBE HEAT Switch - PROBE HEAT",
},
["d3007pnilu3007cd3vd-1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN88",
},
},
["name"] = "PROBE HEAT Switch - TEST",
},
["d3008pnilunilcd4vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN74",
},
},
["name"] = "AIR REFUEL Switch - CLOSE",
},
["d3008pnilunilcd4vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN73",
},
},
["name"] = "AIR REFUEL Switch - OPEN",
},
["d3010pnilu3010cd2vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN80",
},
},
["name"] = "MANUAL PITCH Override Switch - OVRD/NORM",
},
["d3012pnilu3012cd6vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN99",
},
},
["name"] = "FIRE & OHEAT DETECT Test Button",
},
["d3014pnilu3014cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN12",
},
},
["name"] = "Countermeasures Management Switch - Fwd",
},
["d3015pnilu3015cd16vd-1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN10",
},
},
["name"] = "Countermeasures Management Switch - Aft",
},
["d3016pnilu3016cd16vd-1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN9",
},
},
["name"] = "Countermeasures Management Switch - Left",
},
["d3017pnilu3017cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN11",
},
},
["name"] = "Countermeasures Management Switch - Right",
},
["d3018pnilu3018cd17vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN82",
},
},
["name"] = "ICP Master Mode Button - A-A",
},
["d3019pnilu3019cd17vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN81",
},
},
["name"] = "ICP Master Mode Button - A-G",
},
["d3024pnilu3024cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN16",
},
},
["name"] = "Transmit Switch - VHF (call radio menu)",
},
["d3025pnilu3025cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN14",
},
},
["name"] = "Transmit Switch - UHF (call radio menu)",
},
["d3026pnilu3026cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN17",
},
},
["name"] = "Transmit Switch - IFF OUT",
},
["d3027pnilu3027cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN15",
},
},
["name"] = "Transmit Switch - IFF IN",
},
["d3031pnilu3031cd16vd-1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN20",
},
},
["name"] = "SPD BRK Switch - Aft/EXTEND (Momentary)",
},
["d3031pnilu3031cd2vd-1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN79",
},
},
["name"] = "Autopilot PITCH Switch - ATT HOLD",
},
["d3031pnilunilcd16vd0vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN19",
},
},
["name"] = "SPD BRK Switch - OFF",
},
["d3031pnilunilcd16vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN18",
},
},
["name"] = "SPD BRK Switch - Fwd/RETRACT",
},
["d3032pnilu3032cd2vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN77",
},
},
["name"] = "Autopilot PITCH Switch - ALT HOLD",
},
["d3032pnilunilcd2vd-1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN78",
},
},
["name"] = "Autopilot PITCH Switch - A/P OFF",
},
["d3039pnilu3039cd16vd1vpnilvu0"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN8",
},
},
["name"] = "ENABLE Switch - Depress",
},
["d3044pnilunilcd16vd-1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN7",
},
},
["name"] = "DOGFIGHT/Missile Override Switch - MISSILE OVERRIDE/CENTER",
},
["d3044pnilunilcd16vd1vpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN6",
},
},
["name"] = "DOGFIGHT/Missile Override Switch - DOGFIGHT/CENTER",
},
["d311pnilunilcdnilvdnilvpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN30",
},
},
["name"] = "Throttle - IDLE",
},
["d313pnilunilcdnilvdnilvpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN2",
},
},
["name"] = "Throttle - OFF",
},
["d430pnilunilcdnilvdnilvpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN75",
},
},
["name"] = "LG Handle - UP",
},
["d431pnilunilcdnilvdnilvpnilvunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN76",
},
},
["name"] = "LG Handle - DN",
},
["dnilp210u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Up Right slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_UR",
},
},
},
["dnilp211u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Down Right slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_DR",
},
},
},
["dnilp212u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Down Left slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_DL",
},
},
},
["dnilp213u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Up Left slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_UL",
},
},
},
["dnilp3004unilcd28vdnilvp-0.01vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN103",
},
},
["name"] = "CRS Set / Brightness Control Knob - CCW/Decrease",
},
["dnilp3004unilcd28vdnilvp0.01vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN104",
},
},
["name"] = "CRS Set / Brightness Control Knob - CW/Increase",
},
["dnilp3019unilcd39vdnilvp-0.3vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN97",
},
},
["name"] = "COMM 1 (UHF) Power Knob - CCW/Decrease",
},
["dnilp3019unilcd39vdnilvp0.3vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN98",
},
},
["name"] = "COMM 1 (UHF) Power Knob - CW/Increase",
},
["dnilp3022unilcd39vdnilvp-0.3vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN100",
},
},
["name"] = "COMM 2 (VHF) Power Knob - CCW/Decrease",
},
["dnilp3022unilcd39vdnilvp0.3vunil"] = {
["added"] = {
[1] = {
["key"] = "JOY_BTN101",
},
},
["name"] = "COMM 2 (VHF) Power Knob - CW/Increase",
},
["dnilp32u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Left slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_L",
},
},
},
["dnilp33u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Right slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_R",
},
},
},
["dnilp34u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Up slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_U",
},
},
},
["dnilp35u214cdnilvdnilvpnilvunil"] = {
["name"] = "View Down slow",
["removed"] = {
[1] = {
["key"] = "JOY_BTN_POV1_D",
},
},
},
},
}
return diff
|
-- If LuaRocks is installed, make sure that packages installed through it are
-- found (e.g. lgi). If LuaRocks is not installed, do nothing.
pcall(require, "luarocks.loader")
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
-- Keys
local keys = require("keys")
-- Rules
local rules = require("rules")
-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors
})
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function(err)
-- Make sure we don't go into an endless error loop
if in_error then return end
in_error = true
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = tostring(err)
})
in_error = false
end)
end
-- }}}
-- {{{ Variable definitions
beautiful.init(gears.filesystem.get_configuration_dir() .. "mytheme.lua")
local modkey = "Mod4"
awful.layout.layouts = {
awful.layout.suit.tile,
}
-- }}}
-- {{{ Set keys
root.keys(keys.globalkeys)
-- }}}
-- {{{ Notification
-- }}}
-- {{{ Set rules
awful.rules.rules = rules
-- }}}
-- {{{ Signals
-- }}}
-- {{{ Widgets
local mytextclock = wibox.widget.textclock()
local mykeyboardlayout = awful.widget.keyboardlayout()
-- }}}
-- {{{ Create a wibox for each screen and add it
local taglist_buttons = gears.table.join(
awful.button({}, 1, function(t) t:view_only() end),
awful.button({ modkey }, 1, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
awful.button({}, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
awful.button({}, 4, function(t) awful.tag.viewnext(t.screen) end),
awful.button({}, 5, function(t) awful.tag.viewprev(t.screen) end)
)
-- }}}
-- {{{ Task list
local tasklist_buttons = gears.table.join(
awful.button({}, 1, function(c)
if c == client.focus then
c.minimized = true
else
c:emit_signal("request::activate", "tasklist", { raise = true })
end
end),
awful.button({}, 3, function()
awful.menu.client_list({ theme = { width = 250 } })
end),
awful.button({}, 4, function()
awful.client.focus.byidx(1)
end),
awful.button({}, 5, function()
awful.client.focus.byidx(-1)
end)
)
-- }}}
-- {{{ Configure screens
awful.screen.connect_for_each_screen(function(s)
-- Each screen has its own tag table.
awful.tag({ " 1 ", " 2 ", " 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 " }, s, awful.layout.layouts[1])
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contain an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(
gears.table.join(
awful.button({}, 1, function() awful.layout.inc(1) end),
awful.button({}, 3, function() awful.layout.inc(-1) end),
awful.button({}, 4, function() awful.layout.inc(1) end),
awful.button({}, 5, function() awful.layout.inc(-1) end)
)
)
-- Create a taglist widget
s.mytaglist = awful.widget.taglist {
screen = s,
filter = awful.widget.taglist.filter.all,
buttons = taglist_buttons
}
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist {
screen = s,
filter = awful.widget.tasklist.filter.currenttags,
buttons = tasklist_buttons,
style = {
shape_border_width = beautiful.border_width,
shape_border_color = '#777777',
shape = gears.shape.rounded_bar,
},
layout = {
spacing = 10,
spacing_widget = {
{
forced_width = 5,
shape = gears.shape.circle,
widget = wibox.widget.separator
},
valign = 'center',
halign = 'center',
widget = wibox.container.place,
},
layout = wibox.layout.flex.horizontal
},
widget_template = {
{
{
{
{
id = 'icon_role',
widget = wibox.widget.imagebox,
},
margins = 2,
widget = wibox.container.margin,
},
{
id = 'text_role',
widget = wibox.widget.textbox,
},
layout = wibox.layout.fixed.horizontal,
},
left = 10,
right = 10,
widget = wibox.container.margin
},
id = 'background_role',
widget = wibox.container.background,
}
}
-- Create the wibox
s.mywibox = awful.wibar({
position = "bottom",
screen = s,
height = 25
})
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal, {
-- Left widgets
layout = wibox.layout.fixed.horizontal,
s.mytaglist,
s.mypromptbox,
},
s.mytasklist, -- Middle widget
{ -- Right widgets
layout = wibox.layout.fixed.horizontal,
wibox.widget.systray(),
mytextclock,
s.mylayoutbox,
},
}
end)
-- }}}
-- {{{ Signal function to execute when a new client appears.
client.connect_signal("manage", function(c)
if awesome.startup
and not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
c.shape = function(cr, w, h)
gears.shape.rounded_rect(cr, w, h, 10)
end
end)
-- }}}
-- {{{ Remove titlebar on floating
client.connect_signal("property::floating", function(c)
if c.floating then
awful.titlebar.show(c)
awful.placement.centered()
else
awful.titlebar.hide(c)
end
end)
-- }}}
-- {{{ Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
-- buttons for the titlebar
local buttons = gears.table.join(
awful.button({}, 1, function()
c:emit_signal("request::activate", "titlebar", { raise = true })
awful.mouse.client.move(c)
end),
awful.button({}, 3, function()
c:emit_signal("request::activate", "titlebar", { raise = true })
awful.mouse.client.resize(c)
end)
)
awful.titlebar(c):setup {
{ -- Left
awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
awful.titlebar.widget.floatingbutton(c),
awful.titlebar.widget.maximizedbutton(c),
awful.titlebar.widget.stickybutton(c),
awful.titlebar.widget.ontopbutton(c),
awful.titlebar.widget.closebutton(c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
end)
-- }}}
-- {{{ Enable sloppy focus, so that focus follows mouse.
client.connect_signal("mouse::enter", function(c)
c:emit_signal("request::activate", "mouse_enter", { raise = false })
end)
-- }}}
-- {{{ Mouse bindings
root.buttons(gears.table.join(
-- awful.button({ }, 3, function () mymainmenu:toggle() end),
awful.button({}, 4, awful.tag.viewnext),
awful.button({}, 5, awful.tag.viewprev)
))
-- }}}
-- {{{ AutorRun
awful.spawn.with_shell("feh --bg-fill --randomize ~/Pictures/wallpapers/*")
-- awful.spawn.with_shell("xss-lock --transfer-sleep-lock -- slock")
-- awful.spawn.with_shell("xautolock -time 20 -locker slock")
awful.spawn.with_shell("xfce4-power-manager")
awful.spawn.with_shell("pgrep xfce4-clipman || xfce4-clipman")
awful.spawn.with_shell("mate-polkit")
awful.spawn.with_shell("pgrep volumeicon || volumeicon")
awful.spawn.with_shell("pamac-tray")
awful.spawn.with_shell("nm-applet")
awful.spawn.with_shell("picom")
-- }}}
beautiful.useless_gap = 2
naughty.config.defaults['icon_size'] = 100
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
|
---
-- @author wesen
-- @copyright 2018-2020 wesen <[email protected]>
-- @release 0.1
-- @license MIT
--
local BaseContentNode = require "AC-LuaServer.Core.Output.Template.TemplateNodeTree.Nodes.BaseContentNode"
---
-- Represents a row field.
--
-- @type RowFieldNode
--
local RowFieldNode = BaseContentNode:extend()
---
-- The name of this node type
--
-- @tfield string name
--
RowFieldNode.name = "row-field"
---
-- The list of tag names that close a node of this type when they occur during the tree parsing
--
-- @tfield string[] closedByTagNames
--
RowFieldNode.closedByTagNames = { "row", "custom-field", "end-custom-field", "row-field" }
---
-- Generates and returns a table from this node and its inner contents.
--
-- @treturn string The table representation of this node
--
function RowFieldNode:toTable()
return table.concat(self.innerTexts)
end
return RowFieldNode
|
-- code borrowed and modified from kikito/anim8 on github:
-- https://raw.githubusercontent.com/kikito/anim8/master/spec/love-mocks.lua
-- thank you @kikito!
-- Copyright (c) 2011 Enrique García Cota
-- 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.
-- mocks for LÖVE functions
local unpack = _G.unpack or table.unpack
local Quadmt = {
__eq = function(a,b)
if #a ~= #b then return false end
for i,v in ipairs(a) do
if b[i] ~= v then return false end
end
return true
end,
__tostring = function(self)
local buffer = {}
for i,v in ipairs(self) do
buffer[i] = tostring(v)
end
return "quad: {" .. table.concat(buffer, ",") .. "}"
end,
getViewport = function(self)
return unpack(self)
end,
typeOf = function(self, typ)
return typ == love.Quad
end,
}
Quadmt.__index = Quadmt
local Imagemt = {
getDimensions = function(self)
return 1, 1
end,
typeOf = function(self, typ)
return typ == love.Image
end,
}
Imagemt.__index = Imagemt
_G.love = {
Image = "image", -- type mocks
Quad = "quad",
graphics = {
newQuad = function(...)
return setmetatable({...}, Quadmt)
end,
draw = function()
end,
getLastDrawq = function()
end,
newImage = function(...)
return setmetatable({...}, Imagemt)
end,
}
}
|
ENT.Type = "anim"
ENT.Base = "bp_base"
ENT.PrintName = "Propionic Acid"
ENT.Spawnable = true
ENT.Category = "Blue's Pharmaceuticals"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.ChemicalID = 3
function ENT:SetupDataTables()
self:NetworkVar("Int", 0, "LiquidAmount")
end
|
local SettingsPerProxy: {[Proxy]: Settings} = {}
local ParentsPerProxy: {[Proxy]: Proxy} = {}
local ActiveListeners: ActiveListeners = {}
--[=[
@class Proxy
Class designed to work as a proxy table. Functions can be connected to listen for
key indexing or key changes/additions
```lua
local Proxy = Proxy.new()
Proxy:OnIndex(function(Key: string, Value: any) -- Will not fire when the key changes
print("Indexed ->", Key, Value)
end)
local Disconnect = Proxy:OnChange(function(Key: string, Value: any, OldValue: any)
print("Changed ->", Key, Value, OldValue)
end)
Proxy.Test = 10 -- Output: Changed -> Test 10 nil
print(Proxy.Test) -- 1st Output: Indexed -> Test 10
-- 2nd Output: 10
Disconnect() -- The connection gets disconnected by just calling it, magic!
Proxy.Test = 50 -- Nothing prints out
```
]=]
local Proxy = {}
Proxy.__index = Proxy
--- Table that acts as the proxy. All keys will automatically be added or indexed from this table except if `rawset` or `rawget` are used
--- @prop _Proxy table
--- @within Proxy
--- @readonly
--[=[
Returns a connection that must be called to disconnect a listener function
@since v3.0.0
@private
@function ListenToDisconnection
@within Proxy
]=]
local function ListenToDisconnection(self: Proxy, Callback: (...any?) -> (), Source: string): Connection
ActiveListeners[self][Source][Callback] = true
local Connection: Connection
Connection = function(CheckConnectionStatus: boolean?): boolean?
local SourceStillExists: boolean = ActiveListeners[self] and ActiveListeners[self][Source]
if SourceStillExists then
if CheckConnectionStatus then
return if SourceStillExists and ActiveListeners[self][Source][Callback] then true else nil
end
if not ActiveListeners[self][Source][Callback] then
return nil
end
ActiveListeners[self][Source][Callback] = nil
Connection = nil
return nil
else
return nil
end
end
return Connection
end
--[=[
Fires all the listeners from the specified source along with the passed arguments
@since v3.0.0
@private
@function FireListeners
@within Proxy
]=]
local function FireListeners(self: Proxy, Source: Listeners, ...: any)
for Callback: (...any) -> (...any) in pairs(Source) do
task.spawn(Callback, ...)
end
end
--[=[
Connects passed callback to a signal that fires when a key is indexed
@since v3.0.0
@method OnIndex
@within Proxy
]=]
function OnIndex(self: Proxy, Callback: (Key: string?, Value: any?, Proxy: Proxy?) -> ()): Connection
return ListenToDisconnection(self, Callback, "IndexListeners")
end
--[=[
Connects passed function to a signal that listens to key additions or changes
@since v3.0.0
@method OnChange
@within Proxy
]=]
function OnChange(self: Proxy, Callback: (Key: string?, Value: any?, OldValue: any?, Proxy: Proxy?) -> ()): Connection
return ListenToDisconnection(self, Callback, "ChangeListeners")
end
--[=[
Destroys the proxy and disconnects all listeners
@method Destroy
@within Proxy
]=]
function Destroy(self: Proxy): nil
if ActiveListeners[self] then
for _, Listeners: Listeners in pairs(ActiveListeners[self]) do
for Connection: Connection in pairs(Listeners) do
Connection()
end
Listeners = nil
end
ActiveListeners[self] = nil
end
SettingsPerProxy[self] = nil
setmetatable(self, nil)
self = nil
return nil
end
--[=[
Fires index listeners and returns the requested key's value
:::note Class members can also be indexed
Proxy properties or methods can be returned when indexing them. To only set
or get actual values from the proxy table, use [Proxy:Set] and [Proxy:Get]
@since v3.1.3
@private
@within Proxy
]=]
local function Index(self: Proxy, Key: string): any
local Value: any = self._Proxy[Key]
if Key ~= nil and Value ~= nil then -- Otherwise, index listeners will get fired while destroying the proxy
FireListeners(self, ActiveListeners[self].IndexListeners, Key, Value, self)
end
return Value
end
--[=[
Fires change listeners. Change listeners will only fire if the updated value
differs from its last value
:::tip Child proxies are automatically cleaned up
When a key's value is changed, if the old value is a proxy object, it will automatically
get cleaned up using [Proxy:Destroy]
@since v3.1.3
@private
@within Proxy
]=]
local function NewIndex(self: Proxy, Key: string, Value: any)
local CurrentValue: any = self._Proxy[Key]
if CurrentValue ~= Value then
if type(CurrentValue) == "table" and Proxy.IsProxy(CurrentValue) then
CurrentValue:Destroy()
end
if type(Value) == "table" and Proxy.IsProxy(Value) and SettingsPerProxy[self].TrackChildren then
SettingsPerProxy[Value].TrackChildren = true
ParentsPerProxy[Value] = self
end
self._Proxy[Key] = Value
if Key ~= nil and Value ~= nil then -- Otherwise, index listeners will get fired while destroying the proxy
FireListeners(self, ActiveListeners[self].ChangeListeners, Key, Value, CurrentValue, self)
end
end
end
--[=[
Specifically looks for the desired key inside the proxy table.
```lua
print(Proxy._Proxy) -- Outputs: {}
print(Proxy:Get("_Proxy")) -- Outputs: nil
-- Proxy._Proxy is the proxy table, since it is empty it returns an empty table
-- Proxy:Get("_Proxy") is actually looking for Proxy._Proxy["_Proxy"], which is nil
```
:::info
Use this in case the proxy object has a property that also is a key inside the proxy table
@since v3.0.0
@method Get
@within Proxy
]=]
function Get(self: Proxy, Key: string): any
return Index(self, Key)
end
--[=[
Specifically sets the value for the desired key inside the proxy table.
```lua
Proxy:Set("_Proxy", 10)
print(Proxy._Proxy) -- Outputs: { _Proxy = 10 }
print(Proxy:Get("_Proxy")) -- Outputs: 10
-- :Set() will only modify values inside Proxy._Proxy
```
:::info
Use this in case the proxy object should have a key inside the proxy table that also is a proxy property
@since v3.0.0
@method Set
@within Proxy
]=]
function Set(self: Proxy, Key: string, Value: any): any
return NewIndex(self, Key, Value)
end
local Methods = {
Get = Get,
Set = Set,
Destroy = Destroy,
OnIndex = OnIndex,
OnChange = OnChange,
}
--[=[
Checks if the given table is or not a proxy (checks its metatable)
```lua
local Proxy = require(Source.Proxy)
local NewProxy = Proxy.new()
print(Proxy.IsProxy(NewProxy)) -- Output: true
print(Proxy.IsProxy({})) -- Output: false
```
:::caution
A good practice is to check
@since v3.1.0
@within Proxy
]=]
function Proxy.IsProxy(Table: table): boolean
return getmetatable(Table) == Proxy
end
--[=[
Creates a new proxy object
@tag Constructor
@within Proxy
]=]
function Proxy.new(Origin: table?, Settings: Settings): Proxy
local self = { _Proxy = if Origin then Origin else {} }
ActiveListeners[self] = {
IndexListeners = {},
ChangeListeners = {},
}
SettingsPerProxy[self] = if Settings then Settings else {}
return setmetatable(self, Proxy)
end
function Proxy:__index(Key: string): any
if Methods[Key] then
return Methods[Key] -- Methods are found inside a table and must be returned like this when indexed
else
return Index(self, Key)
end
end
function Proxy:__newindex(Key: string, Value: any)
return NewIndex(self, Key, Value)
end
type table = {[any]: any}
--- A table that could contain any value indexed by any type of value
--- @type table {[any]: any}
--- @within Proxy
type Connection = (CheckConnectionStatus: boolean?) -> boolean
--- Connection between a signal and a listener function. To disconnect it, the connection must be called like a function with no arguments
--- @type Connection (CheckConnectionStatus: boolean) -> boolean
--- @within Proxy
type Listeners = {[(...any) -> (...any)]: boolean}
--- List of listener functions that will fire on signal events
--- @type Listeners {[(...any) -> (...any)]: boolean}
--- @within Proxy
type ProxyListeners = {
IndexListeners: Listeners,
ChangeListeners: Listeners,
}
--- Listeners of a proxy
--- @interface ProxyListeners
--- @within Proxy
--- .IndexListeners Listeners
--- .ChangeListeners Listeners
type ActiveListeners = {[table]: ProxyListeners}
--- List of active listeners indexed by their parent proxy
--- @type ActiveListeners {[table]: ProxyListeners}
--- @within Proxy
type Proxy = {
_Proxy: table,
IsProxy: (Table: table) -> boolean,
OnChange: (self: Proxy, Callback: (Key: string?, Value: any?, OldValue: any?, Proxy: Proxy?) -> ()) -> Connection,
OnIndex: (self: Proxy, Callback: (Key: string?, Value: any?, Proxy: Proxy?) -> ()) -> Connection,
Set: (self: Proxy, Key: string, Value: any) -> any,
Get: (self: Proxy, Key: string) -> any,
Destroy: (self: Proxy) -> nil
}
type Settings = {
TrackChildren: boolean?,
}
return Proxy
|
local BaseInstance = import("./BaseInstance")
local Selection = BaseInstance:extend("Selection")
return Selection
|
local List = script.Parent
local Llama = List.Parent
local t = require(Llama.t)
local validate = t.table
local function includes(list, value)
assert(validate(list))
for _, v in ipairs(list) do
if v == value then
return true
end
end
return false
end
return includes
|
print("\n motor.lua hv180829.1817\n")
--timers personnels
hvtimer1=tmr.create()
hvtimer2=tmr.create()
hvtimer3=tmr.create()
hvtimer4=tmr.create()
--parametres pour les moteurs
pin_a_speed = 1
pin_a_dir = 3
pin_b_speed = 2
pin_b_dir = 4
FWD = gpio.LOW
REV = gpio.HIGH
duty = 1023
--initialise moteur A
gpio.mode(pin_a_speed,gpio.OUTPUT)
gpio.write(pin_a_speed,gpio.LOW)
pwm.setup(pin_a_speed,50,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_a_speed)
pwm.setduty(pin_a_speed,0)
gpio.mode(pin_a_dir,gpio.OUTPUT)
gpio.write(pin_a_dir,FWD)
--initialise moteur B
gpio.mode(pin_b_speed,gpio.OUTPUT)
gpio.write(pin_b_speed,gpio.LOW)
pwm.setup(pin_b_speed,50,duty) --PWM 1KHz, Duty 1023
pwm.start(pin_b_speed)
pwm.setduty(pin_b_speed,0)
gpio.mode(pin_b_dir,gpio.OUTPUT)
gpio.write(pin_b_dir,FWD)
function forward()
gpio.write(pin_a_dir,FWD)
gpio.write(pin_b_dir,FWD)
pwm.setduty(pin_a_speed,(zpeed * duty) / 100)
pwm.setduty(pin_b_speed,(zpeed * duty) / 100)
end
function stop()
pwm.setduty(pin_a_speed,0)
pwm.setduty(pin_b_speed,0)
end
function set_speed()
pwm.setduty(pin_a_speed,(zpeed * duty) / 100)
pwm.setduty(pin_b_speed,(zpeed * duty) / 100)
end
function right()
tmr.unregister(hvtimer1)
print("right")
gpio.write(pin_a_dir,FWD)
gpio.write(pin_b_dir,REV)
pwm.setduty(pin_a_speed,(zpeed * duty) / 100)
pwm.setduty(pin_b_speed,(zpeed * duty) / 100)
tmr.alarm(hvtimer1, 500, tmr.ALARM_SINGLE, forward)
end
function left()
gpio.write(pin_a_dir,REV)
gpio.write(pin_b_dir,FWD)
pwm.setduty(pin_a_speed,(zpeed * duty) / 100)
pwm.setduty(pin_b_speed,(zpeed * duty) / 100)
tmr.alarm(hvtimer2, 500, tmr.ALARM_SINGLE, forward)
end
function backward()
gpio.write(pin_a_dir,REV)
gpio.write(pin_b_dir,REV)
pwm.setduty(pin_a_speed,(zpeed * duty) / 100)
pwm.setduty(pin_b_speed,(zpeed * duty) / 100)
tmr.alarm(hvtimer3, 1000, tmr.ALARM_SINGLE, right)
-- tmr.alarm(hvtimer4, 2000, tmr.ALARM_SINGLE, forward)
end
|
-- add target
target("tbox_test")
-- set kind
set_kind("binary")
-- add defines
add_defines("__tb_prefix__=\"tbox_test\"")
-- add packages
add_packages("tbox")
-- add files
add_files("*.cpp")
|
-- Copyright (C) 2018-2021 by KittenOS NEO contributors
--
-- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
-- THIS SOFTWARE.
-- metamachine-vgpu.lua : Virtual GPU library
-- Authors: 20kdc
return function (icecap, address, path, ro)
if path ~= "/" then
icecap.makeDirectory(path:sub(1, #path - 1))
end
local function resolvePath(p, post)
local pth = {}
local issue = false
string.gsub(p, "[^\\/]+", function (str)
if str == ".." then
if not pth[1] then
issue = true
else
table.remove(pth, #pth)
end
elseif str ~= "." then
table.insert(pth, str)
end
end)
if issue then
return
end
local str = path
if post then
str = str:sub(1, #str - 1)
end
for k, v in ipairs(pth) do
if k > 1 or post then
str = str .. "/"
end
str = str .. v
end
return str
end
local function wrapThing(fn, post, roStop)
-- If we're adding a "/", we get rid of the original "/".
--
local pofx = ""
if post then
pofx = "/"
end
return function (p)
if ro and roStop then
return false, "read-only filesystem"
end
p = resolvePath(p, post)
if p then
local nt = {pcall(fn, p .. pofx)}
if nt[1] then
return table.unpack(nt, 2)
end
end
return nil, "no such file or directory"
end
end
local function wrapStat(s)
return wrapThing(function (px)
local stat = icecap.stat(px)
if stat then
return stat[s]
end
end, false, false)
end
local handles = {}
local lHandle = 0
local modeMapping = {
r = false,
rb = false,
w = true,
wb = true,
a = "append",
ab = "append"
}
return {
type = "filesystem",
getLabel = function ()
return "VFS"
end,
setLabel = function (label)
end,
isReadOnly = function ()
return ro or icecap.isReadOnly()
end,
spaceUsed = function ()
return icecap.spaceUsed()
end,
spaceTotal = function ()
return icecap.spaceTotal()
end,
list = wrapThing(icecap.list, true, false),
exists = wrapThing(function (px)
if icecap.stat(px) then
return true
end
return false
end, false, false),
isDirectory = wrapStat(1),
size = wrapStat(2),
lastModified = wrapStat(3),
makeDirectory = wrapThing(icecap.makeDirectory, false, true),
rename = function (a, b)
if ro then return false, "read-only filesystem" end
a = resolvePath(a)
b = resolvePath(b)
if not (a and b) then
return nil, a
end
return icecap.rename(a, b)
end,
remove = wrapThing(icecap.remove, false, true),
--
open = function (p, mode)
checkArg(1, p, "string")
p = resolvePath(p)
if not p then return nil, "failed to open" end
if rawequal(mode, nil) then mode = "r" end
if modeMapping[mode] == nil then
error("unsupported mode " .. tostring(mode))
end
mode = modeMapping[mode]
if (mode ~= false) and ro then return nil, "read-only filesystem" end
lHandle = lHandle + 1
handles[lHandle] = icecap.open(p, mode)
if not handles[lHandle] then
return nil, "failed to open"
end
return lHandle
end,
read = function (fh, len)
checkArg(1, fh, "number")
checkArg(2, len, "number")
if not handles[fh] then return nil, "bad file descriptor" end
if not handles[fh].read then return nil, "bad file descriptor" end
return handles[fh].read(len)
end,
write = function (fh, data)
checkArg(1, fh, "number")
if not handles[fh] then return nil, "bad file descriptor" end
if not handles[fh].write then return nil, "bad file descriptor" end
return handles[fh].write(data)
end,
seek = function (fh, whence, point)
checkArg(1, fh, "number")
if not handles[fh] then return nil, "bad file descriptor" end
if not handles[fh].seek then return nil, "bad file descriptor" end
return handles[fh].seek(whence, point)
end,
close = function (fh)
checkArg(1, fh, "number")
if not handles[fh] then return nil, "bad file descriptor" end
handles[fh].close()
handles[fh] = nil
return true
end,
}
end
|
function createVRML(header)
local vrml = {}
vrml.__type = 'vrml'
vrml.__header = header
return vrml
end
function createPROTO(protoName)
local proto = {}
proto.__name = protoName
proto.__type = 'proto'
return proto
end
function createNode(nodeName, nodeType)
local node = {}
node.__name = nodeName
node.__nodeType = nodeType
node.__type = 'node'
node.__def = 0
return node
end
function createField(fieldName, value)
local field = {}
if type(value) == 'table' then
field = value
end
field.__name = fieldName
field.__type = 'field'
return field
end
function createMultiField(fieldName, value)
local field = {}
if type(value) == 'table' then
field = value
end
field.__name = fieldName
field.__type = 'multifield'
return field
end
function createProto(protoName)
local proto = {}
proto.__name = protoName
proto.__type = 'field'
return proto
end
function indentSpace(indent)
local str = ''
for i = 1, indent do
str = str..' '
end
return str
end
function writeproto(file, proto, indent)
file:write(indentSpace(indent)..'PROTO '..proto.__name..' [')
if proto.declaration then
end
file:write(indentSpace(indent)..']\n')
file:write(indentSpace(indent)..' {\n')
for k, v in ipairs(proto) do
_G['write'..v.__type](file, v, indent + 1)
end
file:write(indentSpace(indent)..'}\n')
end
function writenode(file, node, indent)
if node.__name then
if node.__def == 1 then
file:write(indentSpace(indent)..'DEF '..node.__name..' ')
else
file:write(indentSpace(indent)..node.__name..' ')
end
file:write(node.__nodeType..' {\n')
else
file:write(indentSpace(indent)..node.__nodeType..' {\n')
end
for k, v in ipairs(node) do
_G['write'..v.__type](file, v, indent + 1)
end
file:write(indentSpace(indent)..'}\n')
end
function writefield(file, field, indent)
file:write(indentSpace(indent)..field.__name)
for k, v in ipairs(field) do
file:write(' '..v)
end
file:write(indentSpace(indent)..'\n')
end
function writemultifield(file, field, indent)
file:write(indentSpace(indent)..field.__name..' [\n')
local numCount = 0
local maxLineNum = 4
for i = 1, #field do
if type(field[i]) == 'string' then
file:write(indentSpace(indent+1)..'"'..field[i]..'"\n')
elseif type(field[i]) == 'number' then
file:write(indentSpace(indent+1))
file:write(field[i]..' ')
numCount = numCount + 1
if field.__delimiterFreq and numCount % field.__delimiterFreq == 0 then
file:write(field.__delimiter)
end
if numCount % maxLineNum == 0 then
file:write(indentSpace(indent)..'\n')
end
elseif type(field[i]) == 'table' then
_G['write'..field[i].__type](file, field[i], indent + 1)
end
end
file:write(indentSpace(indent)..']\n')
end
function saveVRML(vrml, filename)
if vrml.__type ~= 'vrml' then
error('input must be created by createVRML')
end
local indent = 0
file = assert(io.open(filename, 'w'))
if vrml.__header then
file:write(vrml.__header)
file:write('\n\n')
end
for k, v in ipairs(vrml) do
_G['write'..v.__type](file, v, indent)
end
end
|
local has_telescope, telescope = pcall(require, "telescope")
if not has_telescope then
error("telescope-gitmoji.nvim requires telescope.nvim - https://github.com/nvim-telescope/telescope.nvim")
end
local gm_actions = require("telescope._extensions.gitmoji.actions")
local gm_picker = require("telescope._extensions.gitmoji.picker")
local gm_emojis = require("telescope._extensions.gitmoji.emojis")
local action = gm_actions.commit
local search = function(opts)
opts = opts or {}
defaults = {
action = action,
}
gm_picker(vim.tbl_extend("force", defaults, opts))
end
return telescope.register_extension({
setup = function(cfg)
action = cfg.action or gm_actions.commit
end,
exports = {
gitmoji = search,
},
})
|
mouse_x = 0
mouse_y = 0
game_width = 0
game_height = 0
game_time = 0
function updateGlobals(dt)
game_time = game_time + dt
mouse_x = love.mouse.getX()
mouse_y = love.mouse.getY()
game_width = love.graphics.getWidth()
game_height = love.graphics.getHeight()
end
|
local param = config.param
return {
handler = function(context)
context.request.method = context.request.query[param]:upper()
return nil, true
end,
options = {
predicate = function(context)
if context.request.query[param] then
return true
end
return false
end
}
}
|
project "Gaff"
if _ACTION then
location(GetFrameworkLocation())
end
kind "StaticLib"
language "C++"
files { "**.h", "**.cpp", "**.inl", "**.lua" }
includedirs
{
"include",
"../../Dependencies/EASTL/include",
"../../Dependencies/rapidjson",
"../../Dependencies/mpack"
}
flags { "FatalWarnings" }
filter { "system:windows" }
defines { "_CRT_SECURE_NO_WARNINGS" }
excludes { "**/*_Linux.*", "*_Linux.*" }
filter {}
SetupConfigMap()
|
local lsp_status = require('lsp-status')
lsp_status.register_progress()
-- local capabilities = vim.lsp.protocol.make_client_capabilities()
-- capabilities.textDocument.completion.completionItem.snippetSupport = true
require("lspconfig").clangd.setup {
capabilities = lsp_status.capabilities,
on_attach = lsp_status.on_attach,
init_options = {clangdFileStatus = true},
handlers = lsp_status.extensions.clangd.setup()
}
-- handlers = lsp_status.extensions.clangd.setup(),
-- init_options = {
-- clangdFileStatus = true
-- },
-- on_attach = lsp_status.on_attach,
-- capabilities = lsp_status.capabilities,
-- default_config = {
-- cmd = {
-- "clangd", "--background-index", "--pch-storage=memory",
-- "--clang-tidy", "--suggest-missing-includes"
-- },
-- filetypes = {"c", "cpp", "objc", "objcpp"},
-- }
|
return {
TRACER = {
prefix = "[trace] ",
queueCount = 16,
dumpParams = true,
dumpResults = true
},
CHECKER = {
mode = {
input = 1,
output = 2
},
maxDepth = 3
}
}
|
function DoSubSystemDemand_Bentusi()
end
CpuBuildSS_DefaultSubSystemDemandRules = DoSubSystemDemand_Bentusi
|
---
--- Bagels
--- Ported by Joe Nellis.
--- Text displayed is altered slightly from the original program to allow for
--- more (or less) than three digits to be guessed. Change the difficulty to
--- the number of digits you wish in the secret code.
---
--- difficult is number of digits to use
local difficulty = 3
print [[
BAGELS
CREATIVE COMPUTING MORRISTOWN, NEW JERSEY
]]
function getInput(prompt)
io.write(prompt)
io.flush()
local input = io.read("l")
if not input then --- test for EOF
print("GOODBYE")
os.exit(0)
end
return input
end
local needsRules = getInput("WOULD YOU LIKE THE RULES? (YES OR NO) ")
print()
if needsRules:match("[yY].*") then
print(string.format( [[
I AM THINKING OF A %u DIGIT NUMBER. TRY TO GUESS
MY NUMBER AND I WILL GIVE YOU CLUES AS FOLLOWS:
PICO - ONE DIGIT CORRECT BUT IN THE WRONG POSITION
FERMI - ONE DIGIT CORRECT AND IN THE RIGHT POSITION
BAGELS - NO DIGITS
]], difficulty))
end
function play(numDigits, score)
local digits = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" }
--- secret number must not have duplicate digits
--- randomly swap numDigits at the head of this list to create secret number
for i = 1, numDigits do
local j = math.random(1, 10)
digits[i], digits[j] = digits[j], digits[i]
end
print "O.K. I HAVE A NUMBER IN MIND."
for guessNum = 1, 20 do
:: GUESS_AGAIN :: ---<!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
local guess = getInput(string.format("GUESS #%u\t?",guessNum))
if #guess ~= numDigits then
print("TRY GUESSING A", numDigits, "DIGIT NUMBER.")
goto GUESS_AGAIN
elseif not guess:match("^(%d+)$") then
print("WHAT?")
goto GUESS_AGAIN
else
--- check if user has duplicate digits
for i = 1, numDigits - 1 do
for j = i + 1, numDigits do
if (guess:sub(i, i) == guess:sub(j, j)) then
print("OH, I FORGOT TO TELL YOU THAT THE NUMBER I HAVE")
print("IN MIND HAS NO TWO DIGITS THE SAME.")
goto GUESS_AGAIN
end
end
end
end
local report = ""
--- check for picos, right digit, wrong place
for i = 1, numDigits do
for j = i + 1, numDigits - 1 + i do
if (guess:sub(i, i) == digits[(j - 1) % numDigits + 1]) then
report = report .. "PICO "
end
end
end
--- check for fermis, right digit, right place
for i = 1, numDigits do
if (guess:sub(i, i) == digits[i]) then
report = report .. "FERMI "
end
end
if (report == string.rep("FERMI ", numDigits)) then
print "YOU GOT IT!!!"
print ""
score = score + 1
goto PLAY_AGAIN
end
if (report == "") then
print("BAGELS")
else
print(report)
end
end
print "OH WELL."
print("THAT'S TWENTY GUESSES. MY NUMBER WAS "
.. table.concat(digits, "", 1, numDigits))
:: PLAY_AGAIN :: ---<!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
local playAgain = getInput("PLAY AGAIN (YES OR NO)?")
print()
if (playAgain:match("[yY].*")) then
return play(numDigits, score)
else
if (score > 0) then
print("A", score, "POINT BAGELS BUFF!!")
end
print "HOPE YOU HAD FUN. BYE."
end
end
play(difficulty, 0) --- default is numDigits=3, score=0
|
AddCSLuaFile()
ENT.Type = "anim"
function ENT:SetupDataTables()
self:NetworkVar( "Bool",0, "Disabled" )
self:NetworkVar( "Bool",1, "CleanMissile" )
self:NetworkVar( "Bool",2, "DirtyMissile" )
self:NetworkVar( "Entity",0, "Attacker" )
self:NetworkVar( "Entity",1, "Inflictor" )
self:NetworkVar( "Entity",2, "LockOn" )
self:NetworkVar( "Float",0, "StartVelocity" )
end
if SERVER then
function ENT:SpawnFunction( ply, tr, ClassName )
if not tr.Hit then return end
local ent = ents.Create( ClassName )
ent:SetPos( tr.HitPos + tr.HitNormal * 90 )
ent:Spawn()
ent:Activate()
return ent
end
function ENT:BlindFire()
if self:GetDisabled() then return end
local pObj = self:GetPhysicsObject()
if IsValid( pObj ) then
pObj:SetVelocityInstantaneous( self:GetForward() * 90000000 )
end
end
function ENT:Initialize()
self:SetModel( "models/weapons/w_missile_launch.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:SetRenderMode( RENDERMODE_TRANSALPHA )
self:PhysWake()
local pObj = self:GetPhysicsObject()
if IsValid( pObj ) then
pObj:EnableGravity( false )
pObj:SetMass( 1 )
end
self.SpawnTime = CurTime()
end
function ENT:Think()
local curtime = CurTime()
self:NextThink( curtime )
local Target = self:GetLockOn()
if IsValid( Target ) then
self:BlindFire()
else
self:BlindFire()
end
if self.MarkForRemove then
self:Detonate()
end
if self.Explode then
local Inflictor = self:GetInflictor()
local Attacker = self:GetAttacker()
util.BlastDamage( IsValid( Inflictor ) and Inflictor or Entity(0), IsValid( Attacker ) and Attacker or Entity(0), self:GetPos(),300,600)
self:Detonate()
end
if (self.SpawnTime + 12) < curtime then
self:Detonate()
end
return true
end
local IsThisSimfphys = {
["gmod_sent_vehicle_fphysics_base"] = true,
["gmod_sent_vehicle_fphysics_wheel"] = true,
}
function ENT:PhysicsCollide( data )
if self:GetDisabled() then
self.MarkForRemove = true
else
local HitEnt = data.HitEntity
if IsValid( HitEnt ) and not self.Explode then
local Class = HitEnt:GetClass():lower()
if IsThisSimfphys[ Class ] then
local Pos = self:GetPos()
if Class == "gmod_sent_vehicle_fphysics_wheel" then
HitEnt = HitEnt:GetBaseEnt()
end
local effectdata = EffectData()
effectdata:SetOrigin( Pos )
effectdata:SetNormal( -self:GetForward() )
util.Effect( "manhacksparks", effectdata, true, true )
local dmginfo = DamageInfo()
dmginfo:SetDamage( 3000 )
dmginfo:SetAttacker( IsValid( self:GetAttacker() ) and self:GetAttacker() or self )
dmginfo:SetDamageType( DMG_DIRECT )
dmginfo:SetInflictor( self )
dmginfo:SetDamagePosition( Pos )
HitEnt:TakeDamageInfo( dmginfo )
end
if HitEnt.LFS or HitEnt.IdentifiesAsLFS then
local Pos = self:GetPos()
local effectdata = EffectData()
effectdata:SetOrigin( Pos )
effectdata:SetNormal( -self:GetForward() )
util.Effect( "manhacksparks", effectdata, true, true )
local dmginfo = DamageInfo()
dmginfo:SetDamage( 500 )
dmginfo:SetAttacker( IsValid( self:GetAttacker() ) and self:GetAttacker() or self )
dmginfo:SetDamageType( DMG_DIRECT )
dmginfo:SetInflictor( self )
dmginfo:SetDamagePosition( Pos )
HitEnt:TakeDamageInfo( dmginfo )
end
end
self.Explode = true
end
end
function ENT:BreakMissile()
if not self:GetDisabled() then
self:SetDisabled( true )
local pObj = self:GetPhysicsObject()
if IsValid( pObj ) then
pObj:EnableGravity( true )
self:PhysWake()
end
end
end
function ENT:Detonate()
local effectdata = EffectData()
effectdata:SetOrigin( self:GetPos() )
util.Effect( "astw2_halo3_explosion_fuelrod", effectdata )
self:Remove()
end
function ENT:OnTakeDamage( dmginfo )
if dmginfo:GetDamageType() ~= DMG_AIRBOAT then return end
if self:GetAttacker() == dmginfo:GetAttacker() then return end
self:BreakMissile()
end
else
function ENT:Initialize()
self.snd = CreateSound(self, "weapons/flaregun/burn.wav")
self.snd:Play()
local effectdata = EffectData()
effectdata:SetOrigin( self:GetPos() )
effectdata:SetEntity( self )
util.Effect( "fuelrod_trail", effectdata )
end
function ENT:Draw()
self:DrawModel()
end
function ENT:SoundStop()
if self.snd then
self.snd:Stop()
end
end
function ENT:Think()
if self:GetDisabled() then
self:SoundStop()
end
return true
end
function ENT:OnRemove()
self:SoundStop()
end
end
|
local Buffer = require("neogit.lib.buffer")
local GitCommandHistory = require("neogit.buffers.git_command_history")
local git = require("neogit.lib.git")
local cli = require('neogit.lib.git.cli')
local util = require("neogit.lib.util")
local notif = require("neogit.lib.notification")
local config = require("neogit.config")
local a = require'neogit.async'
local refreshing = false
local current_operation = nil
local status = {}
local locations = {}
local status_buffer = nil
local hunk_header_matcher = vim.regex('^@@.*@@')
local diff_add_matcher = vim.regex('^+')
local diff_delete_matcher = vim.regex('^-')
local function line_is_hunk(line)
-- This returns a false positive on untracked file entries
return not vim.fn.matchlist(line, "^\\(Modified\\|New file\\|Deleted\\|Conflict\\) .*")[1]
end
local function get_section_idx_for_line(linenr)
for i, l in pairs(locations) do
if l.first <= linenr and linenr <= l.last then
return i
end
end
return nil
end
local function get_location(section_name)
for _,l in pairs(locations) do
if l.name == section_name then
return l
end
end
end
local function get_section_item_idx_for_line(linenr)
local section_idx = get_section_idx_for_line(linenr)
local section = locations[section_idx]
if section == nil then
return nil, nil
end
for i, item in pairs(status[section.name]) do
if item.first <= linenr and linenr <= item.last then
return section_idx, i
end
end
return section_idx, nil
end
local function get_section_item_for_line(linenr)
local section_idx, item_idx = get_section_item_idx_for_line(linenr)
local section = locations[section_idx]
if section == nil then
return nil, nil
end
return section, status[section.name][item_idx]
end
local function get_current_section_item()
return get_section_item_for_line(vim.fn.line("."))
end
local function toggle_sign_at_line(line)
local sign_info = status_buffer:get_sign_at_line(line, "fold_markers")
local sign = sign_info.signs[1]
if sign ~= nil then
local parts = vim.split(sign.name, ":")
local new_name = (parts[1] == "NeogitOpen" and "NeogitClosed" or "NeogitOpen") .. ":" .. parts[2]
status_buffer:place_sign(line, new_name, 'fold_markers')
end
end
local function toggle()
vim.cmd("silent! normal za")
if not config.values.disable_signs then
local section, item = get_current_section_item()
if section == nil then
return
end
local line = item ~= nil and item.first or section.first
local on_hunk = item ~= nil and line_is_hunk(vim.fn.getline('.'))
if on_hunk then
local ignored_sections = { "untracked_files", "stashes", "unpulled", "unmerged" }
for _, val in pairs(ignored_sections) do
if val == section.name then
return
end
end
local hunk = get_current_hunk_of_item(item)
line = item.first + hunk.first
end
toggle_sign_at_line(line)
end
end
local function change_to_str(change)
if change.original_name ~= nil then
return string.format("%s %s -> %s", change.type, change.original_name, change.name)
else
return string.format("%s %s", change.type, change.name)
end
end
local function display_status()
status_buffer:unlock()
local old_view = vim.fn.winsaveview()
status_buffer:clear_sign_group('hl')
status_buffer:clear()
if status_buffer == nil then
return
end
locations = {}
local line_idx = 2
local output = {
"Head: " .. status.head.branch .. " " .. status.head.message
}
if status.upstream ~= nil then
line_idx = line_idx + 1
table.insert(output, "Push: " .. status.upstream.branch .. " " .. status.upstream.message)
end
table.insert(output, "")
local function write(str)
table.insert(output, str)
line_idx = line_idx + 1
end
local function write_section(options)
local items
if options.items == nil then
items = status[options.name]
else
items = options.items
end
local len = #items
if len ~= 0 then
if type(options.title) == "string" then
write(string.format("%s (%d)", options.title, len))
else
write(options.title())
end
local location = {
name = options.name,
first = line_idx,
last = 0,
files = {}
}
for _, item in pairs(items) do
local name
local hunks = {}
local current_hunk
if options.display then
name = options.display(item)
elseif type(item) == "string" then
name = item
else
name = item.name
end
write(name)
if type(item) == "table" then
item.first = line_idx
end
if item.diff_content ~= nil then
for _, diff_line in ipairs(item.diff_content.lines) do
write(diff_line)
if hunk_header_matcher:match_str(diff_line) then
if current_hunk ~= nil then
current_hunk.last = line_idx - 1
table.insert(hunks, current_hunk)
end
current_hunk = { first = line_idx }
status_buffer:place_sign(line_idx, 'NeogitHunkHeader', 'hl')
elseif diff_add_matcher:match_str(diff_line) then
status_buffer:place_sign(line_idx, 'NeogitDiffAdd', 'hl')
elseif diff_delete_matcher:match_str(diff_line) then
status_buffer:place_sign(line_idx, 'NeogitDiffDelete', 'hl')
end
end
item.diff_open = true
end
if type(item) == "table" then
item.last = line_idx
if current_hunk ~= nil then
current_hunk.last = line_idx
table.insert(hunks, current_hunk)
end
end
table.insert(location.files, {
first = item.first,
last = item.last,
hunks = hunks
})
end
location.last = line_idx
write("")
table.insert(locations, location)
end
end
write_section({
name = "untracked_files",
title = "Untracked files"
})
write_section({
name = "unstaged_changes",
title = "Unstaged changes",
display = change_to_str
})
write_section({
name = "unmerged_changes",
title = "Unmerged changes",
display = change_to_str
})
write_section({
name = "staged_changes",
title = "Staged changes",
display = change_to_str
})
write_section({
name = "stashes",
title = "Stashes",
display = function(stash)
return "stash@{" .. stash.idx .. "} " .. stash.name
end
})
if status.upstream ~= nil then
write_section({
name = "unpulled",
title = function()
return "Unpulled from " .. status.upstream.branch .. " (" .. #status.unpulled .. ")"
end,
})
write_section({
name = "unmerged",
title = function()
return "Unmerged into " .. status.upstream.branch .. " (" .. #status.unmerged .. ")"
end,
})
end
status_buffer:set_lines(0, -1, false, output)
status_buffer:set_foldlevel(2)
for _,l in pairs(locations) do
local items = status[l.name]
if items ~= nil and l.name ~= "stashes" and l.name ~= "unpulled" and l.name ~= "unmerged" then
for _, i in pairs(items) do
if i.diff_content ~= nil then
for _,h in ipairs(i.diff_content.hunks) do
status_buffer:create_fold(i.first + h.first, i.first + h.last)
status_buffer:open_fold(i.first + h.first)
if not config.values.disable_signs then
status_buffer:place_sign(i.first + h.first, "NeogitOpen:hunk", "fold_markers")
end
end
end
status_buffer:create_fold(i.first, i.last)
if not config.values.disable_signs and l.name ~= "untracked_files" then
status_buffer:place_sign(i.first, "NeogitClosed:item", "fold_markers")
end
end
end
status_buffer:create_fold(l.first, l.last)
status_buffer:open_fold(l.first)
if not config.values.disable_signs then
status_buffer:place_sign(l.first, "NeogitOpen:section", "fold_markers")
end
end
vim.fn.winrestview(old_view)
status_buffer:lock()
end
function primitive_move_cursor(line)
for _,l in pairs(locations) do
if l.first <= line and line <= l.last then
vim.api.nvim_win_set_cursor(0, { l.first, 0 })
break
end
end
end
--- TODO: rename
--- basically moves the cursor to the next section if the current one has no more items
--@param name of the current section
--@param name of the next section
--@returns whether the function managed to find the next cursor position
function contextually_move_cursor(current, next, item_idx)
local items = status[current]
local items_len = #items
if items_len == 0 then
local staged_changes = status[next]
if #staged_changes ~= 0 then
vim.api.nvim_win_set_cursor(0, { get_location(next).first + 1, 0 })
end
return true
else
local line = get_location(current).first
if item_idx > items_len then
line = line + items_len
else
line = line + item_idx
end
vim.api.nvim_win_set_cursor(0, { line, 0 })
return true
end
return false
end
local function refresh_status()
if status_buffer == nil then
return
end
for _,x in ipairs({
'untracked_files',
'unstaged_changes',
'unmerged_changes',
'staged_changes',
'unpulled',
'unmerged',
'stashes'
}) do
for _,i in ipairs(status[x]) do
i.diff_open = false
end
end
local line = vim.fn.line(".")
local section_idx = get_section_idx_for_line(line)
local section = locations[section_idx]
display_status()
if section == nil then
primitive_move_cursor(line)
return
end
local item_idx = line - section.first
if section.name == "unstaged_changes" then
if contextually_move_cursor("unstaged_changes", "staged_changes", item_idx) then
return
end
elseif section.name == "staged_changes" then
if contextually_move_cursor("staged_changes", "unstaged_changes", item_idx) then
return
end
elseif section.name == "untracked_files" then
if contextually_move_cursor("untracked_files", "staged_changes", item_idx) or
contextually_move_cursor("untracked_files", "unstaged_changes", item_idx) then
return
end
end
primitive_move_cursor(line)
end
local load_diffs = a.sync(function ()
local unstaged = {}
local staged = {}
for _,c in pairs(status.unstaged_changes) do
if c.type ~= "Deleted" and c.type ~= "New file" and not c.diff_open and not c.diff_content then
table.insert(unstaged, c)
end
end
local unstaged_len = #unstaged
for _,c in pairs(status.staged_changes) do
if c.type ~= "Deleted" and c.type ~= "New file" and not c.diff_open and not c.diff_content then
table.insert(staged, c)
end
end
local cmds = {}
for _, c in pairs(unstaged) do
if c.original_name ~= nil then
table.insert(cmds, cli.diff.files(c.original_name, c.name))
else
table.insert(cmds, cli.diff.files(c.name))
end
end
for _, c in pairs(staged) do
if c.original_name ~= nil then
table.insert(cmds, cli.diff.cached.files(c.original_name, c.name))
else
table.insert(cmds, cli.diff.cached.files(c.name))
end
end
local results = { a.wait(git.cli.in_parallel(unpack(cmds)).call()) }
for i=1,unstaged_len do
local name = unstaged[i].name
for _,c in pairs(status.unstaged_changes) do
if c.name == name then
c.diff_content = git.diff.parse(vim.split(results[i], '\n'))
break
end
end
end
for i=unstaged_len+1,#results do
local name = staged[i - unstaged_len].name
for _,c in pairs(status.staged_changes) do
if c.name == name then
c.diff_content = git.diff.parse(vim.split(results[i], '\n'))
break
end
end
end
end)
function __NeogitStatusRefresh(force)
local function wait(ms)
vim.wait(ms or 1000, function() return not refreshing end)
end
if refreshing or (status_buffer ~= nil and not force) then
return wait
end
a.dispatch(function ()
refreshing = true
status = a.wait(git.status.get())
if status ~= nil then
a.wait(load_diffs())
a.wait_for_textlock()
refresh_status()
end
a.wait_for_textlock()
vim.cmd [[do <nomodeline> User NeogitStatusRefreshed]]
refreshing = false
end)
return wait
end
function __NeogitStatusOnClose()
status_buffer = nil
end
function get_hunk_of_item_for_line(item, line)
local hunk
local lines = {}
for _,h in pairs(item.diff_content.hunks) do
if item.first + h.first <= line and line <= item.first + h.last then
hunk = h
for i=hunk.first,hunk.last do
table.insert(lines, item.diff_content.lines[i])
end
break
end
end
return hunk, lines
end
function get_current_hunk_of_item(item)
return get_hunk_of_item_for_line(item, vim.fn.line("."))
end
local function add_change(list, item, diff)
local change = nil
for _,c in pairs(list) do
if c.name == item.name then
change = c
break
end
end
if change then
change.diff_content = diff
else
local new_item = vim.deepcopy(item)
new_item.diff_content = diff
new_item.diff_open = false
table.insert(list, new_item)
end
end
local function remove_change(name, item)
status[name] = util.filter(status[name], function(i)
return i.name ~= item.name
end)
end
local function generate_patch_from_selection(item, hunk, from, to, reverse)
reverse = reverse or false
from = from or 1
to = to or hunk.last - hunk.first
if from > to then
from, to = to, from
end
from = from + hunk.first
to = to + hunk.first
local diff_content = {}
local len_start = hunk.index_len
local len_offset = 0
-- + 1 skips the hunk header, since we construct that manually afterwards
for k = hunk.first + 1, hunk.last do
local v = item.diff_content.lines[k]
local operand, line = v:match("^([+ -])(.*)")
if operand == "+" or operand == "-" then
if from <= k and k <= to then
len_offset = len_offset + (operand == "+" and 1 or -1)
table.insert(diff_content, v)
else
-- If we want to apply the patch normally, we need to include every `-` line we skip as a normal line,
-- since we want to keep that line.
if not reverse then
if operand == "-" then
table.insert(diff_content, " "..line)
end
-- If we want to apply the patch in reverse, we need to include every `+` line we skip as a normal line, since
-- it's unchanged as far as the diff is concerned and should not be reversed.
-- We also need to adapt the original line offset based on if we skip or not
elseif reverse then
if operand == "+" then
table.insert(diff_content, " "..line)
end
len_start = len_start + (operand == "-" and -1 or 1)
end
end
else
table.insert(diff_content, v)
end
end
local diff_header = string.format("@@ -%d,%d +%d,%d @@", hunk.index_from, len_start, hunk.index_from, len_start + len_offset)
table.insert(diff_content, 1, diff_header)
table.insert(diff_content, 1, string.format("+++ b/%s", item.name))
table.insert(diff_content, 1, string.format("--- a/%s", item.name))
table.insert(diff_content, "\n")
return table.concat(diff_content, "\n")
end
--- Validates the current selection and acts accordingly
--@return nil
--@return number, number
local function get_selection()
local first_line = vim.fn.getpos("v")[2]
local last_line = vim.fn.getpos(".")[2]
local first_section, first_item = get_section_item_for_line(first_line)
local last_section, last_item = get_section_item_for_line(last_line)
if not first_section or
not first_item or
not last_section or
not last_item
then
return nil
end
local first_hunk = get_hunk_of_item_for_line(first_item, first_line)
local last_hunk = get_hunk_of_item_for_line(last_item, last_line)
if not first_hunk or not last_hunk then
return nil
end
if first_section.name ~= last_section.name or
first_item.name ~= last_item.name or
first_hunk.first ~= last_hunk.first
then
return nil
end
first_line = first_line - first_item.first
last_line = last_line - last_item.first
-- both hunks are the same anyway so only have to check one
if first_hunk.first == first_line or
first_hunk.first == last_line
then
return nil
end
return first_section, first_item, first_hunk, first_line - first_hunk.first, last_line - first_hunk.first
end
local stage_selection = a.sync(function()
local _, item, hunk, from, to = get_selection()
local patch = generate_patch_from_selection(item, hunk, from, to)
a.wait(cli.apply.cached.with_patch(patch).call())
end)
local unstage_selection = a.sync(function()
local _, item, hunk, from, to = get_selection()
if from == nil then
return
end
local patch = generate_patch_from_selection(item, hunk, from, to, true)
a.wait(cli.apply.reverse.cached.with_patch(patch).call())
end)
local stage = a.sync(function()
current_operation = "stage"
local section, item = get_current_section_item()
if section == nil or (section.name ~= "unstaged_changes" and section.name ~= "untracked_files" and section.name ~= "unmerged_changes") or item == nil then
return
end
local mode = vim.api.nvim_get_mode()
if mode.mode == "V" then
a.wait(stage_selection())
else
local on_hunk = line_is_hunk(vim.fn.getline('.'))
if on_hunk and section.name ~= "untracked_files" then
local hunk = get_current_hunk_of_item(item)
local patch = generate_patch_from_selection(item, hunk)
a.wait(cli.apply.cached.with_patch(patch).call())
else
a.wait(git.status.stage(item.name))
end
end
__NeogitStatusRefresh(true)
current_operation = nil
end)
local unstage = a.sync(function()
current_operation = "unstage"
local section, item = get_current_section_item()
if section == nil or section.name ~= "staged_changes" or item == nil then
return
end
local mode = vim.api.nvim_get_mode()
if mode.mode == "V" then
a.wait(unstage_selection())
else
local on_hunk = line_is_hunk(vim.fn.getline('.'))
if on_hunk then
local hunk = get_current_hunk_of_item(item)
local patch = generate_patch_from_selection(item, hunk, nil, nil, true)
a.wait(cli.apply.reverse.cached.with_patch(patch).call())
else
a.wait(git.status.unstage(item.name))
end
end
__NeogitStatusRefresh(true)
current_operation = nil
end)
local discard = a.sync(function()
local section, item = get_current_section_item()
if section == nil or item == nil then
return
end
local result = vim.fn.confirm("Do you really want to do this?", "&Yes\n&No", 2)
if result == 2 then
return
end
-- TODO: fix nesting
local mode = vim.api.nvim_get_mode()
if mode.mode == "V" then
local section, item, hunk, from, to = get_selection()
local patch = generate_patch_from_selection(item, hunk, from, to, true)
if section.name == "staged_changes" then
a.wait(cli.apply.reverse.index.with_patch(patch).call())
else
a.wait(cli.apply.reverse.with_path(patch).call())
end
elseif section.name == "untracked_files" then
a.wait_for_textlock()
vim.fn.delete(item.name)
else
local on_hunk = line_is_hunk(vim.fn.getline('.'))
if on_hunk then
local hunk, lines = get_current_hunk_of_item(item)
lines[1] = string.format('@@ -%d,%d +%d,%d @@', hunk.index_from, hunk.index_len, hunk.index_from, hunk.disk_len)
local diff = table.concat(lines, "\n")
diff = table.concat({'--- a/'..item.name, '+++ b/'..item.name, diff, ""}, "\n")
if section.name == "staged_changes" then
a.wait(cli.apply.reverse.index.with_patch(diff).call())
else
a.wait(cli.apply.reverse.with_patch(diff).call())
end
elseif section.name == "unstaged_changes" then
a.wait(cli.checkout.files(item.name).call())
elseif section.name == "staged_changes" then
a.wait(cli.reset.files(item.name).call())
a.wait(cli.checkout.files(item.name).call())
end
end
__NeogitStatusRefresh(true)
end)
local cmd_func_map = {
["Close"] = function()
notif.delete_all()
vim.defer_fn(function ()
status_buffer:close()
end, 0)
end,
["Depth1"] = function()
vim.cmd("set foldlevel=0")
vim.cmd("norm zz")
end,
["Depth2"] = function()
vim.cmd("set foldlevel=1")
vim.cmd("norm zz")
end,
["Depth3"] = function()
vim.cmd("set foldlevel=1")
vim.cmd("set foldlevel=2")
vim.cmd("norm zz")
end,
["Depth4"] = function()
vim.cmd("set foldlevel=1")
vim.cmd("set foldlevel=3")
vim.cmd("norm zz")
end,
["Toggle"] = toggle,
["Discard"] = { "nv", function () a.run(discard) end, true },
["Stage"] = { "nv", function () a.run(stage) end, true },
["StageUnstaged"] = function ()
a.dispatch(function()
for _,c in pairs(status.unstaged_changes) do
table.insert(status.staged_changes, c)
end
status.unstaged_changes = {}
a.wait(git.status.stage_modified())
a.wait_for_textlock()
refresh_status()
end)
end,
["StageAll"] = function ()
a.dispatch(function()
for _,c in pairs(status.unstaged_changes) do
table.insert(status.staged_changes, c)
end
for _,c in pairs(status.untracked_files) do
table.insert(status.staged_changes, c)
end
status.unstaged_changes = {}
status.untracked_files = {}
a.wait(git.status.stage_all())
a.wait_for_textlock()
refresh_status()
end)
end,
["Unstage"] = { "nv", function () a.run(unstage) end, true },
["UnstageStaged"] = function ()
a.dispatch(function()
for _,c in pairs(status.staged_changes) do
if c.type == "new file" then
table.insert(status.untracked_files, c)
else
table.insert(status.unstaged_changes, c)
end
end
status.staged_changes = {}
a.wait(git.status.unstage_all())
a.wait_for_textlock()
refresh_status()
end)
end,
["CommandHistory"] = function()
GitCommandHistory:new():show()
end,
["GoToFile"] = function()
local section, item = get_current_section_item()
if item ~= nil then
if section.name ~= "unstaged_changes" and section.name ~= "staged_changes" and section.name ~= "untracked_files" then
return
end
local path = item.name
notif.delete_all()
status_buffer:close()
vim.cmd("e " .. path)
end
end,
["RefreshBuffer"] = function() __NeogitStatusRefresh(true) end,
["HelpPopup"] = function ()
local pos = vim.fn.getpos('.')
pos[1] = vim.api.nvim_get_current_buf()
require("neogit.popups.help").create(pos)
end,
["PullPopup"] = require("neogit.popups.pull").create,
["PushPopup"] = require("neogit.popups.push").create,
["CommitPopup"] = require("neogit.popups.commit").create,
["LogPopup"] = require("neogit.popups.log").create,
["StashPopup"] = function ()
local pos = vim.fn.getpos('.')
pos[1] = vim.api.nvim_get_current_buf()
require("neogit.popups.stash").create(pos)
end,
["BranchPopup"] = require("neogit.popups.branch").create,
}
local function create(kind)
kind = kind or "tab"
if status_buffer then
status_buffer:focus()
return
end
Buffer.create {
name = "NeogitStatus",
filetype = "NeogitStatus",
kind = kind,
initialize = function(buffer)
status_buffer = buffer
local mappings = buffer.mmanager.mappings
for key, val in pairs(config.values.mappings.status) do
if val ~= "" then
mappings[key] = cmd_func_map[val]
end
end
__NeogitStatusRefresh(true)
end
}
end
local highlight_group = vim.api.nvim_create_namespace("section-highlight")
local function update_highlight()
vim.api.nvim_buf_clear_namespace(0, highlight_group, 0, -1)
status_buffer:clear_sign_group('ctx')
local line = vim.fn.line('.')
local first, last
-- This nested madness finds the smallest section the cursor is currently
-- enclosed by, based on the locations table created while rendering.
for _,loc in ipairs(locations) do
if line == loc.first then
first, last = loc.first, loc.last
break
elseif line >= loc.first and line <= loc.last then
for _,file in ipairs(loc.files) do
if line == file.first then
first, last = file.first, file.last
break
elseif line >= file.first and line <= file.last then
for _, hunk in ipairs(file.hunks) do
if line <= hunk.last then
first, last = hunk.first, hunk.last
break
end
end
break
end
end
break
end
end
if first == nil or last == nil then
return
end
for i=first,last do
local line = vim.fn.getline(i)
if hunk_header_matcher:match_str(line) then
status_buffer:place_sign(i, 'NeogitHunkHeaderHighlight', 'ctx')
elseif diff_add_matcher:match_str(line) then
status_buffer:place_sign(i, 'NeogitDiffAddHighlight', 'ctx')
elseif diff_delete_matcher:match_str(line) then
status_buffer:place_sign(i, 'NeogitDiffDeleteHighlight', 'ctx')
else
status_buffer:place_sign(i, 'NeogitDiffContextHighlight', 'ctx')
end
end
end
return {
create = create,
toggle = toggle,
update_highlight = update_highlight,
get_status = function() return status end,
generate_patch_from_selection = generate_patch_from_selection,
wait_on_current_operation = function (ms)
vim.wait(ms or 1000, function() return not current_operation end)
end,
wait_on_refresh = function (ms)
vim.wait(ms or 1000, function() return not refreshing end)
end
}
|
object_tangible_quest_quest_start_shared_borvo_acklay_armor = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_borvo_acklay_armor.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_borvo_acklay_armor, "object/tangible/quest/quest_start/shared_borvo_acklay_armor.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_chapter7_publish_gift_collection_token = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_chapter7_publish_gift_collection_token.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_chapter7_publish_gift_collection_token, "object/tangible/quest/quest_start/shared_chapter7_publish_gift_collection_token.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_chapter8_publish_gift_collection_token = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_chapter8_publish_gift_collection_token.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_chapter8_publish_gift_collection_token, "object/tangible/quest/quest_start/shared_chapter8_publish_gift_collection_token.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_corellia_coronet_meatlump_act1_viewscreen = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_corellia_coronet_meatlump_act1_viewscreen.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_corellia_coronet_meatlump_act1_viewscreen, "object/tangible/quest/quest_start/shared_corellia_coronet_meatlump_act1_viewscreen.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_brightclaw_jaw = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_brightclaw_jaw.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_brightclaw_jaw, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_brightclaw_jaw.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_greyclimber_eye = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_greyclimber_eye.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_greyclimber_eye, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_greyclimber_eye.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_paleclaw_jaw = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_paleclaw_jaw.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_paleclaw_jaw, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_paleclaw_jaw.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_silkthrower_fang = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_silkthrower_fang.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_silkthrower_fang, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_silkthrower_fang.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_spiketop_horn = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_spiketop_horn.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_spiketop_horn, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_spiketop_horn.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_ep3_hunt_loot_stoneleg_heart = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_ep3_hunt_loot_stoneleg_heart.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_ep3_hunt_loot_stoneleg_heart, "object/tangible/quest/quest_start/shared_ep3_hunt_loot_stoneleg_heart.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_naboo_kadaara_jonni_skaak_journal = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_naboo_kadaara_jonni_skaak_journal.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_naboo_kadaara_jonni_skaak_journal, "object/tangible/quest/quest_start/shared_naboo_kadaara_jonni_skaak_journal.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_bounty_hunter_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_bounty_hunter_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_bounty_hunter_10, "object/tangible/quest/quest_start/shared_profession_bounty_hunter_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_bounty_hunter_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_bounty_hunter_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_bounty_hunter_20, "object/tangible/quest/quest_start/shared_profession_bounty_hunter_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_bounty_hunter_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_bounty_hunter_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_bounty_hunter_30, "object/tangible/quest/quest_start/shared_profession_bounty_hunter_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_commando_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_commando_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_commando_10, "object/tangible/quest/quest_start/shared_profession_commando_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_commando_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_commando_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_commando_20, "object/tangible/quest/quest_start/shared_profession_commando_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_commando_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_commando_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_commando_30, "object/tangible/quest/quest_start/shared_profession_commando_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_entertainer_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_entertainer_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_entertainer_10, "object/tangible/quest/quest_start/shared_profession_entertainer_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_entertainer_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_entertainer_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_entertainer_20, "object/tangible/quest/quest_start/shared_profession_entertainer_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_entertainer_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_entertainer_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_entertainer_30, "object/tangible/quest/quest_start/shared_profession_entertainer_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_force_sensitive_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_force_sensitive_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_force_sensitive_10, "object/tangible/quest/quest_start/shared_profession_force_sensitive_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_force_sensitive_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_force_sensitive_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_force_sensitive_20, "object/tangible/quest/quest_start/shared_profession_force_sensitive_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_force_sensitive_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_force_sensitive_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_force_sensitive_30, "object/tangible/quest/quest_start/shared_profession_force_sensitive_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_medic_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_medic_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_medic_10, "object/tangible/quest/quest_start/shared_profession_medic_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_medic_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_medic_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_medic_20, "object/tangible/quest/quest_start/shared_profession_medic_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_medic_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_medic_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_medic_30, "object/tangible/quest/quest_start/shared_profession_medic_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_officer_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_officer_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_officer_10, "object/tangible/quest/quest_start/shared_profession_officer_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_officer_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_officer_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_officer_20, "object/tangible/quest/quest_start/shared_profession_officer_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_officer_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_officer_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_officer_30, "object/tangible/quest/quest_start/shared_profession_officer_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_smuggler_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_smuggler_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_smuggler_10, "object/tangible/quest/quest_start/shared_profession_smuggler_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_smuggler_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_smuggler_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_smuggler_20, "object/tangible/quest/quest_start/shared_profession_smuggler_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_smuggler_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_smuggler_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_smuggler_30, "object/tangible/quest/quest_start/shared_profession_smuggler_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_spy_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_spy_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_spy_10, "object/tangible/quest/quest_start/shared_profession_spy_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_spy_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_spy_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_spy_20, "object/tangible/quest/quest_start/shared_profession_spy_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_spy_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_spy_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_spy_30, "object/tangible/quest/quest_start/shared_profession_spy_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_trader_10 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_trader_10.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_trader_10, "object/tangible/quest/quest_start/shared_profession_trader_10.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_trader_20 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_trader_20.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_trader_20, "object/tangible/quest/quest_start/shared_profession_trader_20.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_profession_trader_30 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_profession_trader_30.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_profession_trader_30, "object/tangible/quest/quest_start/shared_profession_trader_30.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_som_kenobi_hidden_treasure_plaque = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_som_kenobi_hidden_treasure_plaque.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_som_kenobi_hidden_treasure_plaque, "object/tangible/quest/quest_start/shared_som_kenobi_hidden_treasure_plaque.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_som_kenobi_reunite_shard = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_som_kenobi_reunite_shard.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_som_kenobi_reunite_shard, "object/tangible/quest/quest_start/shared_som_kenobi_reunite_shard.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_som_kenobi_symbiosis_fluid_container = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_som_kenobi_symbiosis_fluid_container.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_som_kenobi_symbiosis_fluid_container, "object/tangible/quest/quest_start/shared_som_kenobi_symbiosis_fluid_container.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_quest_quest_start_shared_update_14_quest_comlink = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/quest/quest_start/shared_update_14_quest_comlink.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_quest_quest_start_shared_update_14_quest_comlink, "object/tangible/quest/quest_start/shared_update_14_quest_comlink.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
local _, ns = ...
local len = string.len
local gsub = string.gsub
local format = string.format
local match = string.match
local floor = math.floor
local tags = oUF.Tags.Methods
local events = oUF.Tags.Events
local function FormatValue(value)
if value >= 1e6 then
return tonumber(format("%.1f", value/1e6)).."m"
elseif value >= 1e3 then
return tonumber(format("%.1f", value/1e3)).."k"
else
return value
end
end
tags["neav:AdditionalPower"] = function(unit)
local min, max = UnitPower(unit, Enum.PowerType.Mana), UnitPowerMax(unit, Enum.PowerType.Mana)
if min == max then
return FormatValue(min)
else
return FormatValue(min).."/"..FormatValue(max)
end
end
events["neav:AdditionalPower"] = "UNIT_POWER_UPDATE UNIT_DISPLAYPOWER UNIT_MAXPOWER"
tags["neav:pvptimer"] = function(unit)
if not IsPVPTimerRunning() or GetPVPTimer() == 301000 or GetPVPTimer() == 999 then
return ""
end
return ns.FormatTime(floor(GetPVPTimer()/1000))
end
events["neav:pvptimer"] = "PLAYER_ENTERING_WORLD PLAYER_FLAGS_CHANGED"
tags["neav:level"] = function(unit)
local r, g, b
local targetEffectiveLevel = UnitEffectiveLevel(unit)
if UnitIsWildBattlePet(unit) or UnitIsBattlePetCompanion(unit) then
targetEffectiveLevel = UnitBattlePetLevel(unit)
r, g, b = 1.0, 0.82, 0.0
elseif targetEffectiveLevel > 0 then
if UnitCanAttack("player", unit) then
local color = GetCreatureDifficultyColor(targetEffectiveLevel)
r, g, b = color.r, color.g, color.b
else
r, g, b = 1.0, 0.82, 0.0
end
else
r, g, b = 1, 0, 0
targetEffectiveLevel = "??"
end
return format("|cff%02x%02x%02x%s|r", r*255, g*255, b*255, targetEffectiveLevel)
end
events["neav:level"] = "UNIT_LEVEL PLAYER_LEVEL_UP UNIT_CLASSIFICATION_CHANGED"
tags["neav:name"] = function(unit)
local r, g, b
local name, _ = UnitName(unit) or UNKNOWN
local _, class = UnitClass(unit)
if unit == "player" or unit:match("party") then
if class then
local color = oUF.colors.class[class]
r, g, b = color[1], color[2], color[3]
else
r, g, b = 0, 1, 0
end
elseif unit == "targettarget" or unit == "focustarget" or unit:match("arena(%d)target") then
r, g, b = GameTooltip_UnitColor(unit)
else
r, g, b = 1, 1, 1
end
name = (len(name) > 15) and gsub(name, "%s?(.[\128-\191]*)%S+%s", "%1. ") or name
return format("|cff%02x%02x%02x%s|r", r*255, g*255, b*255, name)
end
events["neav:name"] = "UNIT_NAME_UPDATE"
local timer = {}
tags["neav:afk"] = function(unit)
local name, _ = UnitName(unit) or UNKNOWN
if UnitIsAFK(unit) then
if not timer[name] then
timer[name] = GetTime()
end
local time = (GetTime() - timer[name])
return ns.FormatTime(time)
elseif timer[name] then
timer[name] = nil
end
end
events["neav:afk"] = "PLAYER_FLAGS_CHANGED"
|
local gamedata = {}
gamedata.map_scroll_speed = 50
gamedata.difficulty = 1
gamedata.pattern_speed = 1
collision_categories = {
player = 1,
player_bullet = 2,
enemy = 3,
enemy_bullet = 4,
}
collision_masks = {
player = 12,
enemy = 2,
}
playerdata = {
movespeed = 300,
slow_mp = 3,
}
screen = {
w = 640,
h = 480,
scale = 1,
}
gamedata.gamearea = {
x = 0,
y = 0,
w = 640,
h = 480,
}
hull_types = {}
hull_types["normal"] = { hp = 5, sprite = "enemy", w = 24, h = 25 }
hull_types["hanger"] = { hp = 10, sprite = "hanger", w = 32, h = 32, price = 3 }
hull_types["shotgunner"] = { hp = 15, sprite = "shotgunner", w = 32, h = 32, price = 4 }
hull_types["sprayer"] = { hp = 7, sprite = "sprayer", w = 32, h = 32, price = 2 }
hull_types["kamikaze"] = { hp = 3, sprite = "kamikaze", w = 24, h = 25 }
hull_types["boss"] = { hp = 200, sprite = "boss_core", w = 134, h = 60, price = 10 }
hull_types["bossgun"] = { hp = 50, sprite = "boss_sidearm", w = 32, h = 72, price = 10 }
patterns = {}
patterns["normal"] = {
{ x = 0, y = 150, t = 0 },
{ x = 0, y = 150, t = 1, gun = "atplayer", rate = 1 },
{ x = 0, y = 150, t = 10 },
{ x = 0, y = 150, t = 12 }, -- dummy
}
patterns["normal_gunfree"] = {
{ x = 0, y = 150, t = 0 },
{ x = 0, y = 150, t = 1 },
{ x = 0, y = 150, t = 10 },
{ x = 0, y = 150, t = 12 }, -- dummy
}
patterns["normal_gunfree_flee"] = {
{ x = 0, y = 150, t = 0 },
{ x = 150, y = 150, t = 1, special = "away", dir = "move" },
{ x = 150, y = 150, t = 10, special = "away", dir = "move" },
{ x = 0, y = 150, t = 12 }, -- dummy
}
patterns["discrete_sine"] = {
{x = 0, y = 100, t = 0},
{x = 100, y = 100, t = 1, gun = "atplayer", rate = 1},
{x = -100, y = 100, t = 2, gun = "atplayer", rate = 1},
{x = 0, y = 100, t = 3, special = "away"},
{x = 0, y = 100, t = 400, special = "away"},
{x = 0, y = 100, t = 500},
}
patterns["hanger"] = {
{x = 0, y = 100, t = 0, dir = "player"},
{x = 0, y = 50, t = 3, gun = "atplayer", rate = 0.5},
{x = 50, y = 100, t = 6, special = "away"},
{x = 50, y = 100, t = 200, special = "away"},
{x = 0, y = 0, t = 400}
}
patterns["hanger_shotgun"] = {
{x = 0, y = 100, t = 0, dir = "player"},
{x = 0, y = 0, t = 2, gun = "shotgun", rate = 1},
{x = 50, y = 100, t = 4, special = "away"},
{x = 50, y = 100, t = 200, special = "away"},
{x = 0, y = 0, t = 400}
}
patterns["suicide"] = {
{x = 0, y = 100, t = 0.5, dir = "player"},
{x = 200, y = 200, t = 2, special = "suicide", gun = "atplayer_fast"},
{x = 0, y = 0, t = 555, dir = "move", special = "float"},
{x = 0, y = 100, t = 500, dir = "move", special = "float"},
}
patterns["spray"] = {
{x = 0, y = 100, t = 0.5, dir = "player"},
{x = 50, y = 50, t = 2, special = "suicide", gun = "spray", rate = 1},
{x = 0, y = 0, t = 5, dir = "move", special = "float"},
{x = 0, y = 100, t = 500, dir = "move", special = "float"}, -- dummy
}
patterns["boss_core"] = {
{ x = 0, y = 60, t = 1 }, -- entry
{ x = 0, y = 0, t = 2 },
{ x = -100, y = 50, t = 3 },
{ x = 0, y = -50, t = 4 },
{ x = 0, y = 0, t = 5, gun = "spray", rate = 0.5 },
{ x = 100, y = 50, t = 6 },
{ x = 0, y = -50, t = 7 },
{ x = 0, y = 0, t = 8, gun = "spray", rate = 0.5 },
{ x = 0, y = 0, t = 9},
{ x = 0, y = 0, t = 20 } -- dummy entry, loops from here
}
patterns["boss"] = {
{ x = 0, y = 60, t = 1 }, -- entry
{ x = 0, y = 0, t = 2 },
{ x = -100, y = 50, t = 3, dir = "player", gun = "shotgun", rate = 0.1 },
{ x = 0, y = -50, t = 4, dir = "player", gun = "atplayer_fast", rate = 0.2 },
{ x = 0, y = 0, t = 5, dir = "keep" }, --, dir = "keep", gun = "beam", rate = 0.1 },
{ x = 100, y = 50, t = 6, dir = "player", gun = "shotgun", rate = 0.1 },
{ x = 0, y = -50, t = 7, dir = "player", gun = "atplayer_fast", rate = 0.2 },
{ x = 0, y = 0, t = 8, dir = "keep" }, --, dir = "keep", gun = "beam", rate = 0.1 },
{ x = 0, y = 0, t = 9},
{ x = 0, y = 0, t = 20 } -- dummy entry, loops from here
}
enemy_types = {
["flee"] = { hull = "normal", pattern = "normal_gunfree_flee" },
["popcorn"] = { hull = "normal", pattern = "normal_gunfree" },
["normal"] = { hull = "normal", pattern = "normal" },
["sine"] = { hull = "normal", pattern = "discrete_sine" },
["hanger"] = { hull = "hanger", pattern = "hanger" },
["bosscore"] = { hull = "boss", pattern = "boss_core"},
["boss"] = { hull = "bossgun", pattern = "boss"},
["suicide"] = { hull = "kamikaze", pattern = "suicide" },
["shotgun"] = { hull = "shotgunner", pattern = "hanger_shotgun" },
["spray"] = { hull = "sprayer", pattern = "spray" }
}
function loadMap()
local sti = require "sti"
map = sti("lvl/level1.lua")
object_list = map.layers["Objects"].objects
for i = #object_list, 1, - 1 do
if object_list[i].name == "player" then
playerstart = object_list[i]
table.remove(object_list, i)
end
end
end
return gamedata
|
local mod_name = minetest.get_current_modname()
local function log(level, message)
minetest.log(level, ('[%s] %s'):format(mod_name, message))
end
log('action', 'CSM loading...')
local mod_storage = minetest.get_mod_storage()
local function load_waypoints()
if string.find(mod_storage:get_string('waypoints'), 'return') then
return minetest.deserialize(mod_storage:get_string('waypoints'))
else
return {}
end
end
local waypoints = load_waypoints()
local function safe(func)
-- wrap a function w/ logic to avoid crashing the game
local f = function(...)
local status, out = pcall(func, ...)
if status then
return out
else
log('warning', 'Error (func): ' .. out)
return nil
end
end
return f
end
local function round(x)
-- approved by kahan
if x % 2 ~= 0.5 then
return math.floor(x+0.5)
else
return x - 0.5
end
end
local function pairsByKeys(t, f)
local a = {}
for n in pairs(t) do
table.insert(a, n)
end
table.sort(a, f)
local i = 0
return function()
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
end
local function lc_cmp(a, b)
return a:lower() < b:lower()
end
local function tostring_point(point)
return ('%i %i %i'):format(round(point.x), round(point.y + 0.5), round(point.z))
end
minetest.register_chatcommand('wp_set', {
params = '<name>',
description = 'set a waypoint',
func = safe(function(param)
waypoints = load_waypoints()
local point = minetest.localplayer:get_pos()
waypoints[param] = point
mod_storage:set_string('waypoints', minetest.serialize(waypoints))
minetest.display_chat_message(
('set waypoint "%s" to "%s"'):format(param, tostring_point(point))
)
end),
})
minetest.register_chatcommand('wp_unset', {
params = '<name>',
description = 'remove a waypoint',
func = safe(function(param)
waypoints = load_waypoints()
waypoints[param] = nil
mod_storage:set_string('waypoints', minetest.serialize(waypoints))
minetest.display_chat_message(
('removed waypoint "%s"'):format(param)
)
end),
})
minetest.register_chatcommand('wp_list', {
params = '',
description = 'lists waypoints',
func = safe(function(_)
for name, point in pairsByKeys(waypoints, lc_cmp) do
minetest.display_chat_message(
('%s -> %s'):format(name, tostring_point(point))
)
end
end),
})
minetest.register_chatcommand('tw', {
params = '(<playernamename>) <waypoint>',
description = 'teleport (a player) to a waypoint',
func = safe(function(param)
local playername, wpname = string.match(param, '^(%S+)%s+(%S+)$')
if playername and wpname then
local waypoint = waypoints[wpname]
if waypoint ~= nil then
local args = ('%s %s'):format(playername, tostring_point(waypoint))
minetest.run_server_chatcommand('teleport', args)
else
minetest.display_chat_message(('waypoint "%s" not found.'):format(wpname))
end
else
local wpname = param
local waypoint = waypoints[wpname]
if waypoint ~= nil then
minetest.run_server_chatcommand('teleport', tostring_point(waypoint))
else
minetest.display_chat_message(('waypoint "%s" not found.'):format(wpname))
end
end
end),
})
minetest.register_chatcommand('tr', {
params = '<ELEV> | <PLAYER> | <PLAYER> <ELEV>',
description = '/teleport (a player) to a random location',
func = safe(function(param)
local x = math.random(-30912, 30927)
local y = math.random(-30912, 30927)
local z = math.random(-30912, 30927)
local name = ''
if string.match(param, '^([%a%d_-]+) (%d+)$') ~= nil then
name, y = string.match(param, "^([%a%d_-]+) (%d+)$")
elseif string.match(param, '^([%d-]+)$') then
y = string.match(param, '^([%d-]+)$')
elseif string.match(param, '^([%a%d_-]+)$') ~= nil then
name = string.match(param, '^([%a%d_-]+)$')
end
local args = ('%s %s %s %s'):format(name, x, y, z)
minetest.run_server_chatcommand('teleport', args)
end),
})
|
--[[==[
TFMv2 (Time Formatting Module version 2) - format time with ease and flexibility.
by TheCarbyneUniverse (inspired by goldenstein64's version of TFM 1)
]==]]
local TFM = {}
TFM._SECS_MIN_ = 60
TFM._SECS_HR_ = 60 * TFM._SECS_MIN_
TFM._SECS_DAY_ = 24 * TFM._SECS_HR_
TFM.SECS_MON = 30 * TFM._SECS_DAY_
TFM.SECS_YR = 365 * TFM._SECS_DAY_
local NUM_UNITS = 7
local IN_SECS = {1, TFM._SECS_MIN_, TFM._SECS_HR_, TFM._SECS_DAY_, TFM.SECS_MON, TFM.SECS_YR}
local IN_MS = {1, 1000, 1000 * TFM._SECS_MIN_, 1000 * TFM._SECS_HR_, 1000 * TFM._SECS_DAY_, 1000 * TFM.SECS_MON, 1000 * TFM.SECS_YR}
local UNITS = {'ms', 'sec', 'min', 'hr', 'day', 'mon', 'yr'}
local FORMATS = {'s', 'S', 'm', 'h', 'd', 'M', 'y'}
--> IN_SECS = {sec, min, hr, day, mon, yr}
--> IN_MS = {ms, sec, min, hr, day, mon, yr}
--> FORMATS = {ms, sec, min, hr, day, mon, yr}
---------------------------------------------==========[[ PRIVATE FUNCTIONS ]]==========---------------------------------------------
-- custom assert with a higher stack level
local function assert(condition, msg, lvl)
if condition then return end
error(msg, (lvl or 1) + 2)
end
-- function used by Convert() and ConvertMil()
local function convert(num, isMil, max)
max = max or 'hr'
do
assert(type(num) == 'number', 'expected int, got ' .. type(num) .. ' (arg #1)', 2)
assert(num % 1 == 0, 'expected int, got float (arg #1)', 2)
assert(table.find(UNITS, max), 'invalid max unit (arg #2)', 2)
end
local converted = {}
local sub = isMil and 1 or 0
local start = 2 - sub
local toUse = isMil and IN_MS or IN_SECS
-- init to 0
for i = start, NUM_UNITS do
converted[UNITS[i]] = 0
end
start = table.find(UNITS, max) - 1 + sub
-- fill it up
for i = start, 1, -1 do
if num == 0 then break end
converted[UNITS[i + 1 - sub]] = math.floor(num / toUse[i])
num %= toUse[i]
end
return converted
end
---------------------------------------------==========[[ CONSUMER FUNCTIONS ]]==========---------------------------------------------
function TFM.Convert(sec, max)
assert(max ~= 'ms' and max ~= 'sec', 'cannot set max to ms or sec (arg #2)')
return convert(sec, false, max)
end
function TFM.ConvertMil(ms, max)
assert(max ~= 'ms', 'cannot set max to ms (arg #2)')
return convert(ms, true, max)
end
function TFM.FormatStr(converted, formatStr)
for i = 1, NUM_UNITS do
-- %% for a literal % and * is for 0 or more of that char
-- this line determines how many times to iterate, which is to do it for as many formating parts found
-- it includes %a, %a(sin/plu), %02a, etc.
local _, iter = formatStr:gsub('%%%A*' .. FORMATS[i], '')
for _ = 1, iter do
-- check any conditional plurals (in the format of %a(singular_term[control_char]plural_term))
local capture = formatStr:match('%%' .. FORMATS[i] .. '%(([%C]*%c[%C]*)%)') -- use %c for control char, %C for everything else
if capture then -- singular-plural syntax found
local controlChar = capture:match('%c')
local sin, plu = unpack(capture:split(controlChar)) -- split into singular & plural
local val = converted[UNITS[i]] ~= 1 and plu or sin
local toRepl = '%%' .. FORMATS[i] .. '%([%C]*%c[%C]*%)'
formatStr = formatStr:gsub(toRepl, converted[UNITS[i]] and val or '', 1) -- if key doesn't exist, replace with ''
else -- no singular-plural syntax found
-- captures the parts between % and the specifier for string.format
capture = formatStr:match('%%(%A*)' .. FORMATS[i])
local repl = converted[UNITS[i]] and string.format('%' .. capture .. 's', converted[UNITS[i]]) or ''
formatStr = formatStr:gsub('%%%A*' .. FORMATS[i], repl)
end
end
end
return formatStr
end
function TFM.SetSeconds(dict)
for i, v in pairs(dict) do
if not (i:match('SECS_%u+') and TFM[i]) then
warn('TFMv2: key ' .. i .. ' not found; nothing has been changed')
return
end
local unit = i:split('_')[2]:lower()
local index = table.find(UNITS, unit)
TFM[i] = v
IN_SECS[index - 1] = v
IN_MS[index] = 1000 * v
end
end
return TFM
|
function Create_XSYS_initiator(CustomGroup, playerIndex, shipID)
_ALERT("Initializing X System in CustomCode Scope...")
SobGroup_CreateIfNotExist("X_RunningGroup")
dofilepath("data:leveldata/multiplayer/resdata/XCustomCodeFunction.lua")
dofilepath("data:leveldata/multiplayer/resdata/CustomCode_Custom.lua")
end
function Update_XSYS_initiator(CustomGroup, playerIndex, shipID)
SobGroup_MakeDead(CustomGroup)
_ALERT("Initialized X System in CustomCode Scope...")
end
|
local bytecode = require "luavm.bytecode"
print "required bytecode"
local args = {...}
print("Got args: ",args[1])
local file = table.remove(args,1)
print("File: ",file)
local bc = bytecode.load(string.dump(loadfile(file)))
print("Loaded bytecode")
bytecode.dump(bc)
|
--------------------------------------------------------------------------------
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Dresaron", 1466, 1656)
if not mod then return end
mod:RegisterEnableMob(99200)
--mod.engageId = 1838 -- START fires prior to engaging the boss
local first = true
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
199345, -- Down Draft
199460, -- Falling Rocks
191325, -- Breath of Corruption
}
end
function mod:OnBossEnable()
self:Log("SPELL_CAST_START", "DownDraft", 199345)
self:Log("SPELL_AURA_APPLIED", "FallingRocksDamage", 199460)
self:Log("SPELL_PERIODIC_DAMAGE", "FallingRocksDamage", 199460)
self:Log("SPELL_PERIODIC_MISSED", "FallingRocksDamage", 199460)
self:RegisterUnitEvent("UNIT_SPELLCAST_SUCCEEDED", nil, "boss1")
self:RegisterEvent("INSTANCE_ENCOUNTER_ENGAGE_UNIT", "CheckBossStatus")
self:Death("Win", 99200)
end
function mod:OnEngage()
first = true
self:CDBar(199345, 21) -- Down Draft
self:CDBar(191325, 13.5) -- Breath of Corruption
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:DownDraft(args)
self:Message(args.spellId, "red", "Warning")
self:CDBar(args.spellId, 30) -- pull:20.8, 34.7 / hc pull:21.7, 30.3, 30.4 / m pull:21.8, 34.0, 35.2
end
do
local prev = 0
function mod:FallingRocksDamage(args)
if self:Me(args.destGUID) then
local t = GetTime()
if t-prev > 2 then
prev = t
self:Message(args.spellId, "blue", "Alarm", CL.you:format(args.spellName))
end
end
end
end
function mod:UNIT_SPELLCAST_SUCCEEDED(_, _, _, spellId)
if spellId == 199332 then -- Breath of Corruption
self:Message(191325, "yellow", "Info")
self:CDBar(191325, first and 20 or 30) -- XXX m pull:13.5, 21.5, 13.8, 20.6, 14.6, 20.6
first = false
end
end
|
return PlaceObj("ModDef", {
"title", "Rotate All Buildings",
"version", 1,
"version_major", 0,
"version_minor", 1,
"image", "Preview.png",
"id", "ChoGGi_RotateAllBuildings",
"steam_id", "1566471085",
"pops_any_uuid", "e22c2a8a-60a1-4736-9c11-b4ecbe14dce0",
"author", "ChoGGi",
"lua_revision", 1001569,
"code", {
"Code/Script.lua",
},
"description", [[Removes rotate limit imposed on certain buildings (large wind turbine).
]],
})
|
local files = require 'files'
local vm = require 'vm'
local lang = require 'language'
local config = require 'config'
local guide = require 'parser.guide'
local define = require 'proto.define'
local requireLike = {
['include'] = true,
['import'] = true,
['require'] = true,
['load'] = true,
}
return function (uri, callback)
local ast = files.getAst(uri)
if not ast then
return
end
-- 遍历全局变量,检查所有没有 set 模式的全局变量
guide.eachSourceType(ast.ast, 'getglobal', function (src)
local key = guide.getKeyName(src)
if not key then
return
end
if config.config.diagnostics.globals[key] then
return
end
if config.config.runtime.special[key] then
return
end
if #vm.getGlobalSets(key) == 0 then
local message = lang.script('DIAG_UNDEF_GLOBAL', key)
if requireLike[key:lower()] then
message = ('%s(%s)'):format(message, lang.script('DIAG_REQUIRE_LIKE', key))
end
callback {
start = src.start,
finish = src.finish,
message = message,
}
return
end
if not vm.isDeprecated(src, 0) then
return
end
local message = lang.script('DIAG_UNDEF_GLOBAL', key)
local defs = vm.getDefs(src, 0)
local validVersions
for _, def in ipairs(defs) do
if def.bindDocs then
for _, doc in ipairs(def.bindDocs) do
if doc.type == 'doc.version' then
validVersions = vm.getValidVersions(doc)
break
end
end
end
end
local versions
if validVersions then
versions = {}
for version, valid in pairs(validVersions) do
if valid then
versions[#versions+1] = version
end
end
table.sort(versions)
if #versions > 0 then
message = ('%s(%s)'):format(message, lang.script('DIAG_DEFINED_VERSION', table.concat(versions, '/'), config.config.runtime.version))
end
end
callback {
start = src.start,
finish = src.finish,
tags = { define.DiagnosticTag.Deprecated },
message = message,
data = {
versions = versions,
}
}
end)
end
|
--[[
s:UI Class Power Bar
Martin Karer / Sezz, 2014
http://www.sezz.at
--]]
local S = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:GetAddon("SezzUI");
local M = S:CreateSubmodule("PowerBar", "Gemini:Hook-1.0");
local log, cfg;
-----------------------------------------------------------------------------
-- Initialization
-----------------------------------------------------------------------------
function M:OnInitialize()
log = S.Log;
self:InitializeForms();
self.PowerButtons = {};
self.DB = {
["alwaysVisible"] = false,
["buttonSize"] = 36,
["buttonPadding"] = 4,
["barHeight"] = 6,
};
end
function M:OnEnable()
log:debug("%s enabled.", self:GetName());
-- Create Anchor
self.wndAnchor = Apollo.LoadForm(self.xmlDoc, "PowerBarAnchor", nil, self);
self.wndAnchor:Show(false);
-- Load Class Configuration
if (S.bCharacterLoaded) then
self:ReloadConfiguration();
else
self:RegisterEvent("Sezz_CharacterLoaded", "ReloadConfiguration");
end
end
function M:OnDisable()
log:debug("%s disabled.", self:GetName());
end
function M:ReloadConfiguration()
log:debug("ReloadConfiguration");
-- Class Configuration (TEMP)
self.DB.classConfiguration = {
[GameLib.CodeEnumClass.Spellslinger] = {
["numButtons"] = 4,
["buttonEmpowerFunc"] = GameLib.IsSpellSurgeActive,
["buttonPowerFunc"] = self.GetPowerSpell,
["barEnabled"] = true,
["barPowerFunc"] = self.GetPowerMana,
},
[GameLib.CodeEnumClass.Esper] = {
["numButtons"] = 5,
["buttonEmpowerFunc"] = GameLib.IsCurrentInnateAbilityActive,
["buttonPowerFunc"] = self.GetPowerActuators,
["barEnabled"] = true,
["barPowerFunc"] = self.GetPowerMana,
},
[GameLib.CodeEnumClass.Medic] = {
["numButtons"] = 4,
["buttonEmpowerFunc"] = GameLib.IsCurrentInnateAbilityActive,
["buttonPowerFunc"] = self.GetPowerActuators,
["barEnabled"] = true,
["barPowerFunc"] = self.GetPowerMana,
},
[GameLib.CodeEnumClass.Engineer] = {
["numButtons"] = 0,
["barEnabled"] = true,
["barPowerFunc"] = self.GetPowerVolatility,
},
[GameLib.CodeEnumClass.Stalker] = {
["numButtons"] = 0,
["barEnabled"] = true,
["barPowerFunc"] = self.GetPowerSuit,
},
[GameLib.CodeEnumClass.Warrior] = {
["numButtons"] = 4,
["buttonEmpowerFunc"] = GameLib.IsOverdriveActive,
["buttonPowerFunc"] = self.GetPowerKineticEnergy,
["barEnabled"] = false,
},
};
cfg = self.DB.classConfiguration[S.myClassId];
-- Resize Anchor
local nBarWidth = cfg.numButtons > 0 and (cfg.numButtons * self.DB.buttonSize + (cfg.numButtons - 1) * self.DB.buttonPadding) or 156;
self.wndAnchor:SetAnchorOffsets(-nBarWidth / 2, 100, nBarWidth / 2, 200);
-- Create Buttons
if (cfg.numButtons > 0) then
for i = 1, cfg.numButtons do
local button = Apollo.LoadForm(self.xmlDoc, "PowerButton", self.wndAnchor, self);
if (i > 1) then
local nAnchorOffsetLeft = (i - 1) * (self.DB.buttonSize + self.DB.buttonPadding);
button:SetAnchorOffsets(nAnchorOffsetLeft, 0, nAnchorOffsetLeft + self.DB.buttonSize, self.DB.buttonSize);
end
self.PowerButtons[i] = button;
end
end
-- Create Bar
if (cfg.barEnabled) then
local bar = Apollo.LoadForm(self.xmlDoc, "PowerBar", self.wndAnchor, self);
local nAnchorOffsetTop = self.DB.buttonSize + self.DB.buttonPadding;
bar:SetAnchorOffsets(0, nAnchorOffsetTop, 0, nAnchorOffsetTop + self.DB.barHeight);
self.wndPowerBar = bar;
self.wndPowerBarProgress = bar:FindChild("Progress");
end
-- Add Events
-- Carbine uses OnUpdate, I'll use that too (although this propably sucks)
Apollo.RegisterEventHandler("VarChange_FrameCount", "UpdatePower", self);
-- Show/Hide
if (not self.DB.alwaysVisible) then
self:RegisterEvent("Sezz_PlayerRegenDisabled", "ChangeVisibility");
self:RegisterEvent("Sezz_PlayerRegenEnabled", "ChangeVisibility");
self:ChangeVisibility();
else
self.wndAnchor:Show(true);
end
-- Done
log:debug("%s ready!", self:GetName());
end
-----------------------------------------------------------------------------
-- Bar/Button Updates
-----------------------------------------------------------------------------
function M:UpdatePower()
if (not S.inCombat and not self.DB.alwaysVisible) then return; end
-- Buttons
if (cfg.numButtons > 0) then
local powerCurrent, powerMax = cfg.buttonPowerFunc();
log:debug("Power Buttons: %d/%d", powerCurrent, powerMax);
local bEmpowered = cfg.buttonEmpowerFunc and cfg.buttonEmpowerFunc() or false;
for i = 1, cfg.numButtons do
if (powerCurrent >= i) then
self.PowerButtons[i]:FindChild("Icon"):SetSprite("PowerBarButton"..(bEmpowered and "Surged" or "Filled"));
else
self.PowerButtons[i]:FindChild("Icon"):SetSprite("PowerBarButtonEmpty");
end
end
end
-- Bar
if (cfg.barEnabled and self.wndPowerBarProgress) then
local powerCurrent, powerMax = cfg.barPowerFunc();
log:debug("Power Bar: %d/%d", powerCurrent, powerMax);
self.wndPowerBarProgress:SetMax(powerMax);
self.wndPowerBarProgress:SetProgress(powerCurrent);
end
end
function M:ChangeVisibility()
self.wndAnchor:Show(S.inCombat, false, S.inCombat and 0.2 or 0.5);
end
-----------------------------------------------------------------------------
-- Power Functions
-----------------------------------------------------------------------------
function M:GetPowerMana()
return math.floor(S.myCharacter:GetMana()), math.floor(S.myCharacter:GetMaxMana());
end
function M:GetPowerSpell()
local powerMax = S.myCharacter:GetMaxResource(4);
local powerCurrent = S.myCharacter:GetResource(4);
local powerDivider = powerMax / cfg.numButtons;
return math.floor(powerCurrent / powerDivider), math.floor(powerMax / powerDivider);
end
function M:GetPowerSuit()
return S.myCharacter:GetResource(3), S.myCharacter:GetMaxResource(3);
end
function M:GetPowerActuators()
return S.myCharacter:GetResource(1), S.myCharacter:GetMaxResource(1);
end
function M:GetPowerVolatility()
local powerMax = S.myCharacter:GetMaxResource(1);
local powerCurrent = S.myCharacter:GetResource(1);
local powerPercent = powerCurrent / powerMax * 100;
return powerPercent, powerMax;
end
function M:GetPowerKineticEnergy()
local powerMax = S.myCharacter:GetMaxResource(1);
local powerCurrent = S.myCharacter:GetResource(1);
local powerDivider = powerMax / cfg.numButtons;
return math.floor(powerCurrent / powerDivider), math.floor(powerMax / powerDivider);
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.