content
stringlengths
5
1.05M
--Custom Audio Peripheral for LD Jam return function(config) --A function that creates a new Keyboard peripheral. if not love.audio then error("love.audio module is disabled !") end local au, devkit = {}, {} local musiclist = {"BounceMan.ogg"} local sfxlist = { "DoorClose.wav", --1 "DoorOpen.wav", --2 "Jump.wav", --3 "PickUp.wav", --4 "Tick.wav", --5 "BoxDown.wav", --6 "BoxUp.wav", --7 "BoxLand.wav", --8 "PlayerLand.wav", --9 "GameWin.ogg", --10 "GameOver.ogg" --11 } local musicdata = {} local sfxdata = {} function devkit.loadAudio() --Load Music print("Loading Music ("..#musiclist..")") for k, file in ipairs(musiclist) do print("Loading "..file.." ("..k.."/"..#musiclist..")") local data = love.audio.newSource("/Audio/"..file,"stream") data:setLooping(true) data:setVolume(0.5) table.insert(musicdata,data) end print("Loading SFX ("..#sfxlist..")") for k, file in ipairs(sfxlist) do print("Loading "..file.." ("..k.."/"..#sfxlist..")") local data = love.audio.newSource("/Audio/"..file,"static") table.insert(sfxdata,data) end print("Finished Loading Audio") end function au.StopAudio() love.audio.stop() return true end function au.SFX(id,stop) if not sfxdata[id] then return false, "SFX "..id.." Doesn't exists" end if stop then love.audio.stop(sfxdata[id]) else love.audio.play(sfxdata[id]) end return true end function au.Music(id,stop) if not musicdata[id] then return false, "Music "..id.." Doesn't exists" end if stop then love.audio.stop(musicdata[id]) else love.audio.play(musicdata[id]) end return true end return au, devkit end
dofile("urlcode.lua") dofile("table_show.lua") JSON = (loadfile "JSON.lua")() local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} downloaded["http://genforum.genealogy.com/javascript/TSpacer_wrapper.js"] = true load_json_file = function(file) if file then local f = io.open(file) local data = f:read("*all") f:close() return JSON:decode(data) else return nil end end read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if downloaded[url] == true or addedtolist[url] == true then return false end if (item_type == "genforum" and (downloaded[url] ~= true or addedtolist[url] ~= true)) then if (string.match(url, "%?"..item_value) or string.match(url, "="..item_value) or string.match(url, "%."..item_value) or string.match(url, "/"..item_value) or string.match(url, "/3/") or string.match(url, "/images/") or string.match(url, "/javascript/") or string.match(url, "gco%.[0-9]+%.[0-9a-zA-Z]+%.net") or string.match(url, "email%.cgi") or string.match(url, "picture%.cgi") or string.match(url, "%.jpg") or string.match(url, "%.gif") or string.match(url, "%.png") or string.match(url, "%.jpeg") or string.match(url, "%.css") or string.match(url, "%.js") or html == 0 or string.match(url, "service%.ancestry%.com")) then return true addedtolist[url] = true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if item_type == "genforum" then if string.match(url, "http[s]?://genforum%.genealogy%.com/") then local newurl = string.gsub(url, "http[s]?://genforum%.genealogy%.com/", "http://genforum%.com/") if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "http[s]?://genforum%.com/") then local newurl = string.gsub(url, "http[s]?://genforum%.com/", "http://genforum%.genealogy%.com/") if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, item_value) then html = read_file(html) for customurl in string.gmatch(html, '"(http[s]?://[^"]+)"') do if string.match(customurl, "%?"..item_value) or string.match(customurl, "="..item_value) or string.match(customurl, "%."..item_value) or string.match(customurl, "/"..item_value) or string.match(customurl, "/3/") or string.match(customurl, "/images/") or string.match(customurl, "/javascript/") or string.match(customurl, "gco%.[0-9]+%.[0-9a-zA-Z]+%.net") or string.match(customurl, "email%.cgi") or string.match(customurl, "picture%.cgi") or string.match(customurl, "%.jpg") or string.match(customurl, "%.gif") or string.match(customurl, "%.png") or string.match(customurl, "%.jpeg") or string.match(customurl, "%.css") or string.match(customurl, "%.js") or string.match(customurl, "service%.ancestry%.com") then if (string.match(url, ":::") and string.match(customurl, ":::") and not string.match(html, '<FONT FACE="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^>]+">[^<]+</A></B></FONT><BR>[^<]+<UL>[^<]+</UL>[^<]+<font face="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^"]+">[^<]+</A></B></font><BR>')) or not string.match(url, ":::") then if (downloaded[customurl] ~= true and addedtolist[customurl] ~= true) then table.insert(urls, { url=customurl }) addedtolist[customurl] = true end end end end for customurlnf in string.gmatch(html, '"(/[^"]+)"') do if string.match(customurlnf, "%?"..item_value) or string.match(customurlnf, "="..item_value) or string.match(customurlnf, "%."..item_value) or string.match(customurlnf, "/"..item_value) or string.match(customurlnf, "/3/") or string.match(customurlnf, "/images/") or string.match(customurlnf, "/javascript/") or string.match(customurlnf, "email%.cgi") or string.match(customurlnf, "picture%.cgi") or string.match(customurlnf, "%.jpg") or string.match(customurlnf, "%.gif") or string.match(customurlnf, "%.png") or string.match(customurlnf, "%.jpeg") or string.match(customurlnf, "%.css") or string.match(customurlnf, "%.js") then local base = string.match(url, "(http[s]?://[^/]+)") local customurl = base..customurlnf if (string.match(url, ":::") and string.match(customurl, ":::") and not string.match(html, '<FONT FACE="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^>]+">[^<]+</A></B></FONT><BR>[^<]+<UL>[^<]+</UL>[^<]+<font face="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^"]+">[^<]+</A></B></font><BR>')) or not string.match(url, ":::") then if (downloaded[customurl] ~= true and addedtolist[customurl] ~= true) then table.insert(urls, { url=customurl }) addedtolist[customurl] = true end end end end for customurlnf in string.gmatch(html, '="([^"]+)"') do local base = string.match(url, "(http[s]?://.+/)") local customurl = base..customurlnf if (string.match(url, ":::") and string.match(customurl, ":::") and not string.match(html, '<FONT FACE="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^>]+">[^<]+</A></B></FONT><BR>[^<]+<UL>[^<]+</UL>[^<]+<font face="[^"]+"><B><A HREF="[^"]+">[^<]+</A>[^<]+<A HREF="[^"]+">[^<]+</A></B></font><BR>')) or not string.match(url, ":::") then if (downloaded[customurl] ~= true and addedtolist[customurl] ~= true) then table.insert(urls, { url=customurl }) addedtolist[customurl] = true end end end end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) or status_code == 403 then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0) local sleep_time = 0 -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
ACF.MenuOptions = ACF.MenuOptions or {} ACF.MenuLookup = ACF.MenuLookup or {} ACF.MenuCount = ACF.MenuCount or 0 local Options = ACF.MenuOptions local Lookup = ACF.MenuLookup do -- Menu population functions local function DefaultAction(Menu) Menu:AddTitle("There's nothing here.") Menu:AddLabel("This option is either a work in progress or something isn't working as intended.") end function ACF.AddMenuOption(Index, Name, Icon, Enabled) if not Index then return end if not Name then return end if not isfunction(Enabled) then Enabled = nil end if not Lookup[Name] then local Count = ACF.MenuCount + 1 Options[Count] = { Icon = "icon16/" .. (Icon or "plugin") .. ".png", IsEnabled = Enabled, Index = Index, Name = Name, Lookup = {}, List = {}, Count = 0, } Lookup[Name] = Options[Count] ACF.MenuCount = Count else local Option = Lookup[Name] Option.Icon = "icon16/" .. (Icon or "plugin") .. ".png" Option.IsEnabled = Enabled Option.Index = Index end end function ACF.AddMenuItem(Index, Option, Name, Icon, Action, Enabled) if not Index then return end if not Option then return end if not Name then return end if not Lookup[Option] then return end if not isfunction(Enabled) then Enabled = nil end local Items = Lookup[Option] local Item = Items.Lookup[Name] if not Item then Items.Count = Items.Count + 1 Items.List[Items.Count] = { Icon = "icon16/" .. (Icon or "plugin") .. ".png", Action = Action or DefaultAction, IsEnabled = Enabled, Option = Option, Index = Index, Name = Name, } Items.Lookup[Name] = Items.List[Items.Count] else Item.Icon = "icon16/" .. (Icon or "plugin") .. ".png" Item.Action = Action or DefaultAction Item.IsEnabled = Enabled Item.Option = Option Item.Index = Index Item.Name = Name end end ACF.AddMenuOption(1, "About the Addon", "information") ACF.AddMenuOption(101, "Settings", "wrench") ACF.AddMenuOption(201, "Entities", "brick") ACF.AddMenuOption(9999, "Fun Stuff", "bricks") end do -- ACF Menu context panel local function GetSortedList(List) local Result = {} for K, V in ipairs(List) do Result[K] = V end table.SortByMember(Result, "Index", true) return Result end local function AllowOption(Option) if Option.IsEnabled and not Option:IsEnabled() then return false end return hook.Run("ACF_AllowMenuOption", Option.Index, Option.Name) ~= false end local function AllowItem(Item) if Item.IsEnabled and not Item:IsEnabled() then return false end return hook.Run("ACF_AllowMenuItem", Item.Index, Item.Option, Item.Name) ~= false end local function UpdateTree(Tree, Old, New) local OldParent = Old and Old.Parent local NewParent = New.Parent if OldParent == NewParent then return end if OldParent then OldParent.AllowExpand = true OldParent:SetExpanded(false) end NewParent.AllowExpand = true NewParent:SetExpanded(true) Tree:SetHeight(Tree:GetLineHeight() * (Tree.BaseHeight + NewParent.Count)) end local function PopulateTree(Tree) local OptionList = GetSortedList(Options) local First Tree.BaseHeight = 0.5 for _, Option in ipairs(OptionList) do if not AllowOption(Option) then continue end local Parent = Tree:AddNode(Option.Name, Option.Icon) local SetExpanded = Parent.SetExpanded local Expander = Parent.Expander Parent.Action = Option.Action Parent.Master = true Parent.Count = 0 function Parent:SetExpanded(Bool) if not self.AllowExpand then return end SetExpanded(self, Bool) self.AllowExpand = nil end function Expander:DoClick() local Node = Parent:GetParentNode() Node:OnNodeSelected(Parent) end Tree.BaseHeight = Tree.BaseHeight + 1 local ItemList = GetSortedList(Option.List) for _, Item in ipairs(ItemList) do if not AllowItem(Item) then continue end local Child = Parent:AddNode(Item.Name, Item.Icon) Child.Action = Item.Action Child.Parent = Parent Parent.Count = Parent.Count + 1 if not Parent.Selected then Parent.Selected = Child if not First then First = Child end end end end Tree:SetSelectedItem(First) end function ACF.CreateSpawnMenu(Panel) local Menu = ACF.SpawnMenu if not IsValid(Menu) then Menu = vgui.Create("ACF_Panel") Menu.Panel = Panel Panel:AddItem(Menu) ACF.SpawnMenu = Menu else Menu:ClearAllTemporal() Menu:ClearAll() end local Reload = Menu:AddButton("Reload Menu") Reload:SetTooltip("You can also type 'acf_reload_spawn_menu' in console.") function Reload:DoClickInternal() ACF.CreateSpawnMenu(Panel) end local Tree = Menu:AddPanel("DTree") function Tree:OnNodeSelected(Node) if self.Selected == Node then return end if Node.Master then self:SetSelectedItem(Node.Selected) return end UpdateTree(self, self.Selected, Node) Node.Parent.Selected = Node self.Selected = Node ACF.SetToolMode("acf_menu", "Main", "Idle") ACF.SetClientData("Destiny") Menu:ClearTemporal() Menu:StartTemporal() Node.Action(Menu) Menu:EndTemporal() end PopulateTree(Tree) end end do -- Client and server settings ACF.SettingsPanels = ACF.SettingsPanels or { Client = {}, Server = {}, } local Settings = ACF.SettingsPanels --- Generates the following functions: -- ACF.AddClientSettings(Index, Name, Function) -- ACF.RemoveClientSettings(Name) -- ACF.GenerateClientSettings(MenuPanel) -- ACF.AddServerSettings(Index, Name, Function) -- ACF.RemoveServerSettings(Name) -- ACF.GenerateServerSettings(MenuPanel) for Realm, Destiny in pairs(Settings) do local Hook = "ACF_On" .. Realm .. "SettingsLoaded" local Message = "No %sside settings have been registered." ACF["Add" .. Realm .. "Settings"] = function(Index, Name, Function) if not isnumber(Index) then return end if not isstring(Name) then return end if not isfunction(Function) then return end Destiny[Name] = { Create = Function, Index = Index, } end ACF["Remove" .. Realm .. "Settings"] = function(Name) if not isstring(Name) then return end Destiny[Name] = nil end ACF["Generate" .. Realm .. "Settings"] = function(Menu) if not ispanel(Menu) then return end if not next(Destiny) then Menu:AddTitle("Nothing to see here.") Menu:AddLabel(Message:format(Realm)) return end for Name, Data in SortedPairsByMemberValue(Destiny, "Index") do local Base, Section = Menu:AddCollapsible(Name, false) function Section:OnToggle(Bool) if not Bool then return end if self.Created then return end Data.Create(Base) hook.Run(Hook, Name, Base) self.Created = true end end end end end
local BUILDER, PART = pac.PartTemplate("base") PART.ClassName = "player_config" PART.Group = "entity" PART.Icon = 'icon16/brick.png' local blood_colors = { dont_bleed = _G.DONT_BLEED, red = _G.BLOOD_COLOR_RED, yellow = _G.BLOOD_COLOR_YELLOW, green = _G.BLOOD_COLOR_GREEN, mech = _G.BLOOD_COLOR_MECH, antlion = _G.BLOOD_COLOR_ANTLION, zombie = _G.BLOOD_COLOR_ZOMBIE, antlion_worker = _G.BLOOD_COLOR_ANTLION_WORKER, } BUILDER:StartStorableVars() BUILDER:SetPropertyGroup() BUILDER:GetSet("MuteSounds", false) BUILDER:GetSet("AllowOggWhenMuted", false) BUILDER:GetSet("HideBullets", false) BUILDER:GetSet("HidePhysgunBeam", false) BUILDER:GetSet("UseLegacyScale", false) BUILDER:GetSet("BloodColor", "red", {enums = blood_colors}) BUILDER:SetPropertyGroup("behavior") BUILDER:GetSet("MuteFootsteps", false) BUILDER:SetPropertyGroup("death") BUILDER:GetSet("FallApartOnDeath", false) BUILDER:GetSet("DeathRagdollizeParent", true) BUILDER:GetSet("DrawPlayerOnDeath", false) BUILDER:GetSet("HideRagdollOnDeath", false) BUILDER:EndStorableVars() local ent_fields = {} function BUILDER:EntityField(name, field) field = "pac_" .. field ent_fields[field] = name self.PART["Set" .. name] = function(self, val) self[name] = val local owner = self:GetActualOwner() if owner:IsValid() then owner[field] = val end end end BUILDER:EntityField("InverseKinematics", "enable_ik") BUILDER:EntityField("MuteFootsteps", "hide_weapon") BUILDER:EntityField("AnimationRate", "global_animation_rate") BUILDER:EntityField("FallApartOnDeath", "death_physics_parts") BUILDER:EntityField("DeathRagdollizeParent", "death_ragdollize") BUILDER:EntityField("HideRagdollOnDeath", "death_hide_ragdoll") BUILDER:EntityField("DrawPlayerOnDeath", "draw_player_on_death") BUILDER:EntityField("HidePhysgunBeam", "hide_physgun_beam") BUILDER:EntityField("MuteSounds", "mute_sounds") BUILDER:EntityField("AllowOggWhenMuted", "allow_ogg_sounds") BUILDER:EntityField("HideBullets", "hide_bullets") function PART:GetActualOwner() local owner = self:GetOwner() if owner:IsValid() and owner:GetRagdollOwner():IsPlayer() then return owner:GetRagdollOwner() end return owner end function PART:GetNiceName() local ent = self:GetActualOwner() if ent:IsValid() then if ent:IsPlayer() then return ent:Nick() else return language.GetPhrase(ent:GetClass()) end end return self.ClassName end function PART:OnShow() local ent = self:GetActualOwner() if ent:IsValid() then pac.emut.MutateEntity(self:GetPlayerOwner(), "blood_color", ent, blood_colors[self.BloodColor == "" and "red" or self.BloodColor]) end if ent:IsValid() then for _, field in pairs(ent_fields) do self["Set" .. field](self, self[field]) end end end function PART:OnThink() local ent = self:GetActualOwner() if ent:IsValid() then ent.pac_mute_footsteps = self.MuteFootsteps end end function PART:OnHide() local ent = self:GetActualOwner() if ent:IsValid() then local player_owner = self:GetPlayerOwner() pac.emut.RestoreMutations(player_owner, "blood_color", ent) for key in pairs(ent_fields) do ent[key] = nil end end end function PART:SetBloodColor(str) self.BloodColor = str local ent = self:GetActualOwner() if ent:IsValid() then pac.emut.MutateEntity(self:GetPlayerOwner(), "blood_color", ent, blood_colors[self.BloodColor == "" and "red" or self.BloodColor]) end end BUILDER:Register()
vim.cmd [[ syntax enable ]] local config_dir = vim.env.XDG_CONFIG_HOME or "~/.config" local bin_dir = config_dir .. '/bin' local cache_dir = vim.env.XDG_CACHE_HOME or "~/.cache" local backup_dir = cache_dir .. '/nvim/backup' local undo_dir = cache_dir .. '/nvim/undo' os.execute('mkdir -p ' .. backup_dir) os.execute('mkdir -p ' .. undo_dir) vim.g.did_load_filetypes = 1 vim.g.do_filetype_lua = 1 vim.g.signify_sign_change = '~' -- https://neovim.io/doc/user/options.html#options vim.o.background = 'dark' vim.o.backupdir = backup_dir vim.o.clipboard = 'unnamedplus' vim.o.completeopt = 'menuone,noinsert,noselect' vim.o.confirm = true vim.o.fsync = true vim.o.ignorecase = true vim.o.inccommand = 'split' vim.o.incsearch = true vim.o.mouse = 'a' vim.o.mousefocus = true vim.o.scrolloff = 4 vim.o.shortmess = 'aoOtTIc' vim.o.sidescrolloff = 4 vim.o.signcolumn = 'yes' vim.o.smartcase = true vim.o.smarttab = true vim.o.termguicolors = true vim.o.undodir = undo_dir vim.o.updatetime = 300 vim.o.wildignorecase = true vim.o.wildmode = 'longest,list:longest,full' vim.wo.breakindent = true vim.wo.foldenable = false vim.wo.number = true vim.wo.statusline = '%-F %-r %-m %= %{&fileencoding} | %y | %3.l/%3.L:%3.c' vim.bo.autoindent = true vim.bo.autoread = true vim.bo.commentstring = '#\\ %s' vim.bo.copyindent = true vim.bo.expandtab = true vim.bo.grepprg = 'rg' vim.bo.modeline = false vim.bo.shiftwidth = 0 vim.bo.smartindent = true vim.bo.swapfile = false vim.bo.tabstop = 4 vim.bo.undofile = true if vim.env.SSH_CONNECTION ~= nil then vim.g.clipboard = { name = 'osc52clip', copy = { ['+'] = 'osc52clip copy', }, paste = { ['+'] = 'osc52clip paste', }, } local osc52clip = io.open(bin_dir .. '/osc52clip', 'w') if osc52clip ~= nil then osc52clip:write([[#!/bin/bash : ${TTY:=$((tty || tty </proc/$PPID/fd/0) 2>/dev/null | grep /dev/)} case $1 in copy) buffer=$(base64) [ -n "$TTY" ] && printf $'\e]52;c;%s\a' "$buffer" > "$TTY" ;; paste) exit 1 ;; esac ]]) osc52clip:close() os.execute('chmod +x ' .. bin_dir .. '/osc52clip') end end local packer_install_path = vim.env.XDG_DATA_HOME .. '/nvim/site/pack/packer/start/packer.nvim' local packer_dir_file = io.open(packer_install_path) local packer_install = false if packer_dir_file ~= nil then packer_dir_file:close() else os.execute('git clone https://github.com/wbthomason/packer.nvim ' .. packer_install_path) vim.cmd [[ packadd packer.nvim ]] packer_install = true end require'packer'.startup(function() use {'wbthomason/packer.nvim'} use {'fcpg/vim-fahrenheit'} use {'lukas-reineke/indent-blankline.nvim'} use {'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}} use {'sheerun/vim-polyglot'} use {'jjo/vim-cue'} use {'tyru/caw.vim'} use {'windwp/nvim-autopairs'} use {'mhartington/formatter.nvim'} use {'nvim-treesitter/nvim-treesitter',run = ':TSUpdate'} use {'hrsh7th/nvim-cmp'} use {'hrsh7th/cmp-buffer'} use {'hrsh7th/cmp-path'} use {'hrsh7th/cmp-cmdline'} use {'neovim/nvim-lspconfig'} use {'hrsh7th/cmp-nvim-lsp'} use {'L3MON4D3/LuaSnip'} use {'saadparwaiz1/cmp_luasnip'} end) if packer_install then require('packer').install() end local autopairs = require('nvim-autopairs') local cmp = require('cmp') local formatter = require('formatter') local gitsigns = require('gitsigns') local indent_blankline = require('indent_blankline') local lspconfig = require('lspconfig') local luasnip = require('luasnip') local treesitter = require('nvim-treesitter.configs') autopairs.setup { check_ts = true, } local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end cmp.setup{ mapping = { ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, }, ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() else fallback() end end, { "i", "s" }), ['<Down>'] = cmp.mapping(cmp.mapping.select_next_item({ behavior = cmp.SelectBehavior.Select }), {'i'}), ['<Up>'] = cmp.mapping(cmp.mapping.select_prev_item({ behavior = cmp.SelectBehavior.Select }), {'i'}), }, snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, sources = { { name = 'buffer' }, { name = 'cmdline'}, { name = 'luasnip'}, { name = 'nvim_lsp'}, { name = 'path'}, }, } formatter.setup { filetype = { markdown = { function() return { exe = "prettier", args = {"--stdin-filepath", vim.fn.fnameescape(vim.api.nvim_buf_get_name(0))}, stdin = true, } end }, terraform = { function() return { exe = "terraform", args = {"fmt", "-"}, stdin = true, } end }, }, } gitsigns.setup { signs = { add = { hl = 'DiffAdd', text = '+' }, change = { hl = 'DiffChange', text = '~'}, delete = { hl = 'DiffDelete'}, topdelete = { hl = 'DiffDelete'}, changedelete = { hl = 'DiffChange'}, }, } indent_blankline.setup { buftype_exclude = { 'terminal', 'nofile', }, char_highlight_list = { 'IndentBlankline1', }, show_first_indent_level = false, } local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) lspconfig.bashls.setup { capabilities = capabilities } lspconfig.dockerls.setup { capabilities = capabilities -- root_dir = root_pattern("*Dockerfile*") } lspconfig.gopls.setup { capabilities = capabilities, settings = { gopls = { gofumpt = true, staticcheck = true, }, }, } lspconfig.jsonls.setup { capabilities = capabilities } lspconfig.terraformls.setup{} lspconfig.yamlls.setup { capabilities = capabilities -- settings = { -- yaml = { -- schemas = { -- [".."] = "..." -- } -- } -- } } treesitter.setup { ensure_installed = {'bash','c','cpp','comment','css','dockerfile','dot','go','gomod','gowork','html','java','javascript', 'json','json5','kotlin','lua','make','python','regex','toml','yaml'}, sync_install = true, highlight = { enable = true }, incremental_selection = { enable = true }, } vim.cmd [[ colorscheme fahrenheit ]] local set_hl = { IndentBlankline1 = {fg="#262626"}, DiffAdd = {ctermbg=235, ctermfg=108, bg="#A3BE8C", fg="#262626"}, DiffChange = {ctermbg=235, ctermfg=103, bg="#B48EAD", fg="#262626"}, DiffDelete = {ctermbg=235, ctermfg=131, bg="#BF616A", fg="#262626"}, DiffText = {ctermbg=235, ctermfg=208, bg="#5E81AC", fg="#262626"}, } for k,v in pairs(set_hl) do vim.api.nvim_set_hl(0, k, v) end function sudowrite() local tmpfilename = os.tmpname() local tmpfile = io.open(tmpfilename, 'w') for i, line in ipairs(vim.api.nvim_buf_get_lines(0, 0, -1, false)) do tmpfile:write(line .. '\n') end tmpfile:close() local curfilename = vim.api.nvim_buf_get_name(0) os.execute(string.format("sudo tee %s < %s > /dev/null", curfilename, tmpfilename)) vim.cmd [[ edit! ]] os.remove(tmpfilename) end vim.cmd [[ command W :lua sudowrite() ]] vim.api.nvim_set_keymap('c', 'WQ', 'wq', {noremap = true}) vim.api.nvim_set_keymap('v', 's', '"_d', {noremap = true}) vim.api.nvim_set_keymap('n', 'ss', '"_dd', {noremap = true}) vim.api.nvim_set_keymap('n', ';', ':', {noremap = true, silent = true}) function goimports(timeout_ms) local context = { only = { "source.organizeImports" } } vim.validate { context = { context, "t", true } } local params = vim.lsp.util.make_range_params() params.context = context -- See the implementation of the textDocument/codeAction callback -- (lua/vim/lsp/handler.lua) for how to do this properly. local result = vim.lsp.buf_request_sync(0, "textDocument/codeAction", params, timeout_ms) if not result or next(result) == nil then return end local actions = result[1].result if not actions then return end local action = actions[1] -- textDocument/codeAction can return either Command[] or CodeAction[]. If it -- is a CodeAction, it can have either an edit, a command or both. Edits -- should be executed first. if action.edit or type(action.command) == "table" then if action.edit then vim.lsp.util.apply_workspace_edit(action.edit) end if type(action.command) == "table" then vim.lsp.buf.execute_command(action.command) end else vim.lsp.buf.execute_command(action) end end vim.api.nvim_exec([[ augroup Clean autocmd! autocmd BufWritePre *.go silent :lua goimports(1000) autocmd BufWritePre *.go silent :lua vim.lsp.buf.formatting_sync() autocmd BufWritePre *.md,*.tf silent :FormatWrite autocmd BufWritePre * silent :%s/\s\+$//e autocmd BufWritePre * silent :v/\_s*\S/d autocmd BufWritePre * silent :nohlsearch augroup END ]], false) local ft_tab_width = { [2] = {"html", "javascript", "markdown", "toml", "yaml"}, [8] = {"go"}, } for k,v in pairs(ft_tab_width) do vim.api.nvim_create_autocmd("FileType", { pattern = v, callback = function() vim.opt_local.shiftwidth=k vim.opt_local.softtabstop=k vim.opt_local.tabstop=k end, }) end
function showText_Create(red, green, blue, text, time, thePlayer) showText_Display = textCreateDisplay () showText_Text = textCreateTextItem ( "", 0.5, 0.3, 2, 0, 255, 0, 255, 2.3, "center", "center", 255 ) textDisplayAddText ( showText_Display, showText_Text ) end function showText ( red, green, blue, text, time, thePlayer ) textItemSetColor ( showText_Text, red, green, blue, 255 ) textItemSetText ( showText_Text, text ) outputChatBox(RGBToHex(red, green, blue)..text, thePlayer, red, green, blue, true) if ( showText_timer ) then killTimer ( showText_timer ) else if thePlayer == all then local players = getElementsByType( "player" ) for k,v in ipairs(players) do textDisplayAddObserver ( showText_Display, v ) end else textDisplayAddObserver ( showText_Display, thePlayer ) end end showText_timer = setTimer( showText_Remove, time, 1 ) end function showText_Remove() showText_timer = nil local players = getElementsByType( "player" ) for k,v in ipairs(players) do textDisplayRemoveObserver( showText_Display, v ) end end function RGBToHex(red, green, blue, alpha) if((red < 0 or red > 255 or green < 0 or green > 255 or blue < 0 or blue > 255) or (alpha and (alpha < 0 or alpha > 255))) then return nil end if(alpha) then return string.format("#%.2X%.2X%.2X%.2X", red,green,blue,alpha) else return string.format("#%.2X%.2X%.2X", red,green,blue) end end
LinkLuaModifier("modifier_boss_capture_point", "modifiers/modifier_boss_capture_point.lua", LUA_MODIFIER_MOTION_NONE) -- Taken from bb template if BossAI == nil then DebugPrint ( 'creating new BossAI object' ) BossAI = class({}) BossAI.hasFarmingCore = {} BossAI.hasSecondBoss = {} Debug.EnabledModules['boss:ai'] = false CustomNetTables:SetTableValue("stat_display_team", "BK", { value = {} }) end BossAI.IDLE = 1 BossAI.AGRO = 2 BossAI.LEASHING = 3 BossAI.DEAD = 4 function BossAI:Create (unit, options) options = options or {} options.tier = options.tier or 1 local state = { handle = unit, origin = unit:GetAbsOrigin(), leash = options.leash or BOSS_LEASH_SIZE, agroDamage = options.agroDamage or BOSS_AGRO_FACTOR * options.tier, tier = options.tier, currentDamage = 0, state = BossAI.IDLE, customAgro = options.customAgro or false, owner = options.owner, isProtected = options.isProtected, deathEvent = Event() } --unit:OnHurt(function (keys) --self:HurtHandler(state, keys) --end) unit:OnDeath(function (keys) self:DeathHandler(state, keys) end) unit:SetIdleAcquire(false) unit:SetAcquisitionRange(0) return { onDeath = state.deathEvent.listen } end --[[ function BossAI:HurtHandler (state, keys) if state.state == BossAI.IDLE then DebugPrint('Checking boss agro...') DebugPrintTable(keys) state.currentDamage = state.currentDamage + keys.damage if state.currentDamage > state.agroDamage then self:Agro(state, EntIndexToHScript(keys.entindex_attacker)) state.currentDamage = 0 end elseif state.state == BossAI.AGRO then --luacheck: ignore end end ]] function BossAI:GiveItemToWholeTeam (item, teamId) PlayerResource:GetPlayerIDsForTeam(teamId):each(function (playerId) local hero = PlayerResource:GetSelectedHeroEntity(playerId) if hero then hero:AddItemByName(item) end end) end function BossAI:RewardBossKill(state, deathEventData, teamId) if type(state) == "number" then state = { tier = state } teamId = teamId or deathEventData else state.deathEvent.broadcast(deathEventData) end local team = GetShortTeamName(teamId) if not IsPlayerTeam(teamId) then return end PointsManager:AddPoints(teamId) local bossKills = CustomNetTables:GetTableValue("stat_display_team", "BK").value if bossKills[tostring(teamId)] then bossKills[tostring(teamId)] = bossKills[tostring(teamId)] + 1 else bossKills[tostring(teamId)] = 1 end DebugPrint("Setting team " .. teamId .. " boss kills to " .. bossKills[tostring(teamId)]) CustomNetTables:SetTableValue("stat_display_team", "BK", { value = bossKills }) local tier = state.tier if tier == 1 then self:GiveItemToWholeTeam("item_upgrade_core", teamId) if not self.hasFarmingCore[team] then self.hasFarmingCore[team] = true elseif not self.hasSecondBoss[team] then self.hasSecondBoss[team] = true BossSpawner[team .. "Zone1"].disable() BossSpawner[team .. "Zone2"].disable() end elseif tier == 2 then -- NGP:GiveItemToTeam(BossItems["item_upgrade_core_2"], team) -- NGP:GiveItemToTeam(BossItems["item_upgrade_core"], team) self:GiveItemToWholeTeam("item_upgrade_core_2", teamId) elseif tier == 3 then -- NGP:GiveItemToTeam(BossItems["item_upgrade_core_3"], team) self:GiveItemToWholeTeam("item_upgrade_core_3", teamId) elseif tier == 4 then -- NGP:GiveItemToTeam(BossItems["item_upgrade_core_4"], team) self:GiveItemToWholeTeam("item_upgrade_core_4", teamId) elseif tier == 5 then PointsManager:AddPoints(teamId) -- NGP:GiveItemToTeam(BossItems["item_upgrade_core_4"], team) self:GiveItemToWholeTeam("item_upgrade_core_4", teamId) elseif tier == 6 then PointsManager:AddPoints(teamId) -- NGP:GiveItemToTeam(BossItems["item_upgrade_core_4"], team) self:GiveItemToWholeTeam("item_upgrade_core_4", teamId) end end function BossAI:DeathHandler (state, keys) DebugPrint('Handling death of boss ' .. state.tier) state.state = BossAI.DEAD if state.isProtected then self:RewardBossKill(state, keys, state.owner) state.handle = nil return end -- Create under spectator team so that spectators can always see the capture point local capturePointThinker = CreateModifierThinker(state.handle, nil, "modifier_boss_capture_point", nil, state.origin, DOTA_TEAM_SPECTATOR, false) local capturePointModifier = capturePointThinker:FindModifierByName("modifier_boss_capture_point") capturePointModifier:SetCallback(partial(self.RewardBossKill, self, state, keys)) -- Give the thinker some vision so that spectators can always see the capture point capturePointThinker:SetDayTimeVisionRange(1) capturePointThinker:SetNightTimeVisionRange(1) state.handle = nil end --[[ function BossAI:Agro (state, target) if state.customAgro then DebugPrint('Running custom agro ai') return end Timers:CreateTimer(1, function () if state.state == BossAI.DEAD then return end if not self:Think(state) or state.state == BossAI.IDLE then DebugPrint('Stopping think timer') return end return 1 end) state.state = BossAI.AGRO state.agroTarget = target state.handle:SetIdleAcquire(true) state.handle:SetAcquisitionRange(128) ExecuteOrderFromTable({ UnitIndex = state.handle:entindex(), -- OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET, OrderType = DOTA_UNIT_ORDER_ATTACK_MOVE, Position = target:GetAbsOrigin(), Queue = 0, }) ExecuteOrderFromTable({ UnitIndex = state.handle:entindex(), -- OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET, OrderType = DOTA_UNIT_ORDER_ATTACK_MOVE, Position = state.origin, Queue = 1, }) end ]] --[[ function BossAI:Think (state) if state.handle:IsNull() then -- this shouldn't happen, but sometimes other bugs can cause it -- try to keep the bugged game running return false end local distance = (state.handle:GetAbsOrigin() - state.origin):Length() DebugPrint(distance) if distance > state.leash then self:Leash(state) elseif distance < state.leash / 2 and state.state == BossAI.LEASHING then state.state = BossAI.IDLE return false elseif distance == 0 and state.state == BossAI.AGRO then state.state = BossAI.IDLE return false end return true end ]] --[[ function BossAI:Leash (state) local difference = state.handle:GetAbsOrigin() - state.origin local location = state.origin + (difference / 8) if state.state ~= BossAI.LEASHING then state.handle:Stop() end state.state = BossAI.LEASHING state.handle:SetIdleAcquire(false) state.handle:SetAcquisitionRange(0) ExecuteOrderFromTable({ UnitIndex = state.handle:entindex(), -- OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET, OrderType = DOTA_UNIT_ORDER_MOVE_TO_POSITION, Position = location, Queue = 0, }) end ]]
require "Global.guard_types" local NullGuard = require("Battle.model.guard.NullGuard") local KnightGuard = require("Battle.model.guard.KnightGuard") local RogueGuard = require("Battle.model.guard.RogueGuard") -------------------------------------------------------------------------------------------------------- local guards = {} guards[NULL_GUARD_TYPE] = NullGuard guards[KNIGHT_GUARD_TYPE] = KnightGuard guards[ROGUE_GUARD_TYPE] = RogueGuard return guards
modernUI.questInterface = function(self) local id = self.id local player = self.player local width = self.width local height = self.height local x = (400 - 270/2) local y = (200 - 90/2) - 30 local images = {'174070bd0ec.png', '174070e21a1.png'} -- available, unavailaible local playerData = players[player] local getLang = playerData.lang for i = 1, 2 do local icon = 1 local title, min, max, goal = '', 0, 100, '<p align="center"><font color="#999999">'..translate('newQuestSoon', player):format(questsAvailable+1, '<CE>'..syncData.quests.newQuestDevelopmentStage) if i == 1 then if playerData.questStep[1] > questsAvailable then icon = 2 else title = lang[getLang].quests[playerData.questStep[1]].name min = playerData.questStep[2] max = #lang['en'].quests[playerData.questStep[1]] goal = string.format(lang[getLang].quests[playerData.questStep[1]][playerData.questStep[2]]._add, quest_formatText(player, playerData.questStep[1], playerData.questStep[2])) end else local sideQuestID = sideQuests[playerData.sideQuests[1]].alias or playerData.sideQuests[1] local currentAmount = playerData.sideQuests[2] local requiredAmount = playerData.sideQuests[7] or sideQuests[playerData.sideQuests[1]].amount local description = sideQuests[sideQuestID].formatDescription and sideQuests[sideQuestID].formatDescription(player) or {"<vp>"..currentAmount .. '/' .. requiredAmount.."</vp>"} title = '['..translate('_2ndquest', player)..']' min = currentAmount max = requiredAmount goal = lang[getLang].sideQuests[sideQuestID]:format(table.unpack(description)) end local progress = floor(min / max * 100) local progress2 = floor(min / max * 250/11.5) showTextArea(id..(890+i), '<font color="#caed87" size="14"><b>'..title, player, x+2, y+5 + (i-1)*100, 270, nil, 1, 0x24474, 0, true) showTextArea(id..(892+i), '<font color="#ebddc3" size="13">'..goal, player, x+2, y+30 + (i-1)*100, 270, 40, 0x1, 0x1, 0, true) players[player]._modernUIImages[id][#players[player]._modernUIImages[id]+1] = addImage(images[icon], ":26", x - 5, y + (i-1)*100, player) for ii = 1, progress2 do players[player]._modernUIImages[id][#players[player]._modernUIImages[id]+1] = addImage('171d74086d8.png', ":25", x+17 + (ii-1)*11, y+77 + (i-1)*100, player) end showTextArea(id..(900+i), '<p align="center"><font color="#000000" size="14"><b>'..translate('percentageFormat', player):format(progress), player, x+11, y+73 + (i-1)*100, 250, nil, 0, 0x24474, 0, true) showTextArea(id..(902+i), '<p align="center"><font color="#c6bb8c" size="14"><b>'..translate('percentageFormat', player):format(progress), player, x+10, y+72 + (i-1)*100, 250, nil, 0, 0x24474, 0, true) players[player]._modernUIImages[id][#players[player]._modernUIImages[id]+1] = addImage('171d736325c.png', ":27", x + 10, y + 70 + (i-1)*100, player) if i == 2 then -- Skip Side Quest -- If the player already skipped a quest today, end the function if players[player].sideQuests[5] == floor(os_time() / (24*60*60*1000)) then return end local mirrorButton = players[player].settings.mirroredMode == 1 and 10 or 246 players[player]._modernUIImages[id][#players[player]._modernUIImages[id]+1] = addImage('174077c73af.png', ":28", x + mirrorButton, y + 8 + (i-1)*100, player) showTextArea(id..(905), "<textformat leftmargin='1' rightmargin='1'>" .. string.rep('\n', 4), player, x + mirrorButton, y + 8 + (i-1)*100, 20, 20, 0, 0x24474, 0, true, function() -- If the player already skipped a quest today, end the function to avoid double click if players[player].sideQuests[5] == floor(os_time() / (24*60*60*1000)) then return end eventTextAreaCallback(0, player, 'modernUI_Close_'..id, true) modernUI.new(player, 240, 170, translate('skipQuest', player), translate('skipQuestTxt', player), 0) :build() :addConfirmButton(function() players[player].sideQuests[5] = floor(os_time() / (24*60*60*1000)) players[player].sideQuests[6] = sideQuests[players[player].sideQuests[1]].alias or players[player].sideQuests[1] sideQuest_new(player) end, translate('confirmButton_skipQuest', player)) end) end end return setmetatable(self, modernUI) end
-- sendloop.lua -- 通过mqtt方式发送登录及状态信息到服务器 -- by leonstill@163.com 2018-12-13 local conf = ... or { host = "114.215.120.146", port = 1883, interval = 1000} local json = sjson if (wifi.getmode() ~= wifi.STATION and wifi.getmode() ~= wifi.STATIONAP) then syslog.print(syslog.WARN, "wifi mode should be 'wifi.STATION' or 'wifi.STATIONAP', but now is "..wifi.getmode().."!") return end m_dis={} function dispatch(m,t,pl) print(t .. ":" .. (pl or "nil")) if pl~=nil and m_dis[t] then m_dis[t](m,pl) end end function topic1func(m,pl) print("get1: "..pl) end m_dis["/topic1"]=topic1func -- check mqtt is exist or not if not mqtt then syslog.print(syslog.FATAL, "MQTT module is not installed!") return end -- init mqtt client with logins, keepalive timer 120sec local id = "esp8266_" .. node.chipid() local m = mqtt.Client(id, 60, "liang", "peng") -- setup Last Will and Testament (optional) -- Broker will publish a message with qos = 0, retain = 0, data = "offline" -- to topic "/lwt" if client don't send keepalive packet m:lwt("/lwt", "offline", 0, 0) m:on("connect", function(client) print("connected , heap size:"..node.heap()) end) m:on("offline", function(client) print ("offline") end) -- on publish message receive event m:on("message", dispatch) -- for TLS: m:connect("192.168.11.118", secure-port, 1) m:connect(conf.host, conf.port, 0, function(client) print("client connected") local data = { time=rtctime.get() } client:publish("/wifi/login", json.encode(data), 1, 0, function(client) end) -- Calling subscribe/publish only makes sense once the connection -- was successfully established. You can do that either here in the -- 'connect' callback or you need to otherwise make sure the -- connection was established (e.g. tracking connection status or in -- m:on("connect", function)). -- subscribe topic with qos = 0 --client:subscribe({["/topic"]=0, ["/blink"]=0}, function(client) print("subscribe success") end) -- publish a message with data = hello, QoS = 0, retain = 0 local mytimer = tmr.create() mytimer:register(10, tmr.ALARM_SEMI, function() mytimer:stop() wifi.sta.getap(1, function (t) -- (SSID : Authmode, RSSI, BSSID, Channel) local index = 1 --print("nt: " .. sjson.encode(nt)) client:publish("/wifi/status", json.encode(t), 1, 0) print('.') mytimer:start() end) end) mytimer:start() end, function(client, reason) print("connection failed reason: " .. reason) end) --m:close(); -- you can call m:connect again
--A lot of Thanks to iUltimateLP and his mod SimpleTeleporters for inspiration and for the use of His Code and graphics data:extend({ { type = "explosion", name = "teleport-sound", animation_speed = 5, animations = { { filename = "__PersonalTeleporter__/graphics/empty.png", priority = "extra-high", width = 33, height = 32, frame_count = 1, line_length = 1, shift = {0, 0} } }, light = {intensity = 1, size = 20, color={r=0,g=0.3,b=1} }, smoke = "smoke", smoke_count = 1, smoke_slow_down_factor = 1, } })
local core = require "core" local config = require "core.config" local tokenizer = require "core.tokenizer" local Object = require "core.object" local highlighter = Object:extend() function highlighter:new(doc) self.doc = doc self:reset() -- init incremental syntax highlighting core.add_thread(function() while true do if self.first_invalid_line > self.max_wanted_line then self.max_wanted_line = 0 coroutine.yield(1 / config.fps) else local max = math.min(self.first_invalid_line + 40, self.max_wanted_line) for i = self.first_invalid_line, max do local state = (i > 1) and self.lines[i - 1].state local line = self.lines[i] if not (line and line.init_state == state) then self.lines[i] = self:tokenize_line(i, state) end end self.first_invalid_line = max + 1 core.redraw = true coroutine.yield() end end end, self) end function highlighter:reset() self.lines = {} self.first_invalid_line = 1 self.max_wanted_line = 0 end function highlighter:invalidate(idx) self.first_invalid_line = math.min(self.first_invalid_line, idx) self.max_wanted_line = math.min(self.max_wanted_line, #self.doc.lines) end function highlighter:tokenize_line(idx, state) local res = {} res.init_state = state res.text = self.doc.lines[idx] res.tokens, res.state = tokenizer.tokenize(self.doc.syntax, res.text, state) return res end function highlighter:get_line(idx) local line = self.lines[idx] if not line or line.text ~= self.doc.lines[idx] then local prev = self.lines[idx - 1] line = self:tokenize_line(idx, prev and prev.state) self.lines[idx] = line end self.max_wanted_line = math.max(self.max_wanted_line, idx) return line end function highlighter:each_token(idx) return tokenizer.each_token(self:get_line(idx).tokens) end return highlighter
--- @module Frame -- A simple frame, often used for visually grouping or separating other elements. -- Can also be given text, which will be wrapped to fit. -- @option color string|table A color preset for the frame outline -- @option textColor string|table A color preset -- @option bg string|table A color preset -- @option round number Corner radius -- @option text string Text inside the frame. Will be automatically wrapped to fit. -- @option textIndent number When laying out text, the first line of each -- paragraph will be indented by this many spaces. -- @option textPad number When laying out text, wrapped lines will be indented -- by this many spaces. -- @option font number A font preset -- @option pad number Text padding, on all sides, from the frame local Buffer = require("public.buffer") local Font = require("public.font") local Color = require("public.color") local GFX = require("public.gfx") local Text = require("public.text") local Config = require("gui.config") local Frame = require("gui.element"):new() Frame.__index = Frame Frame.defaultProps = { name = "frame", type = "Frame", x = 0, y = 0, w = 256, h = 256, color = "elementBody", round = 0, text = "", lastText = "", textIndent = 0, textPad = 0, bg = "background", font = 4, textColor = "text", pad = 4, } function Frame:new(props) local frame = self:addDefaultProps(props) return setmetatable(frame, self) end function Frame:init() self.buffer = self.buffer or Buffer.get() gfx.dest = self.buffer gfx.setimgdim(self.buffer, -1, -1) gfx.setimgdim(self.buffer, 2 * self.w + 4, self.h + 2) self:drawFrame() self:drawText() end function Frame:onDelete() Buffer.release(self.buffer) end function Frame:draw() local x, y, w, h = self.x, self.y, self.w, self.h if self.shadow and Config.drawShadows then for i = 1, Config.shadowSize do gfx.blit(self.buffer, 1, 0, w + 2, 0, w + 2, h + 2, x + i - 1, y + i - 1) end end gfx.blit(self.buffer, 1, 0, 0, 0, w + 2, h + 2, x - 1, y - 1) end --- Gets or sets the frame's text -- @option new string New text. Will be automatically wrapped to fit the frame. -- @return string The current text. function Frame:val(new) if new then self.text = new if self.buffer then self:init() end self:redraw() else return self.text:gsub("\n", "") end end ------------------------------------ -------- Drawing methods ----------- ------------------------------------ function Frame:drawFrame() local w, h = self.w, self.h local fill = self.fill local round = self.round -- Frame background if self.bg then Color.set(self.bg) if round > 0 then GFX.roundRect(1, 1, w, h, round, 1, true) else gfx.rect(1, 1, w, h, true) end end -- Shadow local r, g, b, a = table.unpack(Color.colors.shadow) gfx.set(r, g, b, 1) GFX.roundRect(w + 2, 1, w, h, round, 1, 1) gfx.muladdrect(w + 2, 1, w + 2, h + 2, 1, 1, 1, a, 0, 0, 0, 0 ) -- Frame Color.set(self.color) if round > 0 then GFX.roundRect(1, 1, w, h, round, 1, fill) else gfx.rect(1, 1, w, h, fill) end end function Frame:drawText() if self.text and self.text:len() > 0 then -- Rewrap the text if it changed if self.text ~= self.lastText then self.text = self:wrapText(self.text) self.lastText = self.text end Font.set(self.font) Color.set(self.textColor) gfx.x, gfx.y = self.pad + 1, self.pad + 1 if not self.fill then Text.drawBackground(self.text, self.bg) end gfx.drawstr(self.text) end end ------------------------------------ -------- Helpers ------------------- ------------------------------------ function Frame:wrapText(text) return Text.wrapText(text, self.font, self.w - 2*self.pad, self.textIndent, self.textPad) end return Frame
package.path = "../lua/?.lua" local evdtest = require("evdtest") function foo() evdtest.waitevent("foo") end function bar() evdtest.waitevent("bar") end evdtest.startcoroutine(foo) evdtest.startcoroutine(bar) evdtest.waitevent("hello world")
return require "sparse-set.init"
local Tunnel = module("_core", "lib/Tunnel") local Proxy = module("_core", "lib/Proxy") API = Tunnel.getInterface("API") cAPI = {} Tunnel.bindInterface("API", cAPI) Proxy.addInterface("API", cAPI) initializedPlayer = false AddEventHandler( "playerSpawned", function() TriggerServerEvent("pre_playerSpawned") end ) AddEventHandler( "onClientMapStart", function() print("client map initialized") -- exports.spawnmanager:setAutoSpawn(true) -- exports.spawnmanager:forceRespawn() end ) AddEventHandler( "onResourceStart", function(resourceName) -- SetMinimapHideFow(true) -- remove if (GetCurrentResourceName() ~= resourceName) then return end TriggerServerEvent("API:addReconnectPlayer") end ) -- Citizen.CreateThread( -- function() -- Citizen.InvokeNative(0x63E7279D04160477, true) -- Citizen.InvokeNative("0x1E5B70E53DB661E5", 1122662550, 347053089, 0, "Faroeste", "Roleplay", "Bem-vindo!") -- end -- ) Citizen.CreateThread( function() -- N_0xa657ec9dbc6cc900(1) -- Citizen.InvokeNative(0x74E2261D2A66849A, 1) -- Citizen.InvokeNative(0xE8770EE02AEE45C2, 1) while true do Citizen.Wait(0) Citizen.InvokeNative(0xF808475FA571D823, true) --enable friendly fire NetworkSetFriendlyFireOption(true) SetRelationshipBetweenGroups(5, "PLAYER", "PLAYER") SetRelationshipBetweenGroups(5, "PLAYER", "GANG_NIGHT_FOLK" ) SetRelationshipBetweenGroups(5, "GANG_NIGHT_FOLK", "PLAYER" ) local ped = PlayerPedId() if IsPedOnMount(ped) or IsPedInAnyVehicle(ped, false) then SetRelationshipBetweenGroups(1, "PLAYER", "PLAYER") Citizen.Wait(2000) elseif IsPedGettingIntoAVehicle(ped) or Citizen.InvokeNative(0x95CBC65780DE7EB1, ped, false) then SetRelationshipBetweenGroups(1, "PLAYER", "PLAYER") Citizen.Wait(3500) else SetRelationshipBetweenGroups(5, "PLAYER", "PLAYER") end DisableControlAction(0, 0x580C4473, true) -- hud disable DisableControlAction(0, 0xCF8A4ECA, true) -- hud disable -- DisableControlAction(0, 0xE2B557A3, true) -- emote wheel -- DisableControlAction(0, 0x8B3FA65E, true) -- emote wheel horse -- DisableControlAction(0, 0x41AC83D1, true) -- loot DisableControlAction(0, 0x399C6619, true) -- loot 2 -- DisableControlAction(0, 0x27D1C284, false) -- loot 3 -- DisableControlAction(0, 0x14DB6C5E, true) -- loot vehicle -- DisableControlAction(0, 0xC23D7B9E, false) -- loot ammo DisableControlAction(0, 0xFF8109D8, true) -- loot Alive -- DisableControlAction(0, 0xD2CC4644, true) -- soltar corda DisableControlAction(0, 0x6E9734E8, true) -- DESATIVAR DESISTIR DisableControlAction(0, 0x295175BF, true) -- DESATIVAR SOLTAR DA CORDA end end ) Citizen.CreateThread( function() while true do Citizen.Wait(30000) if cAPI.IsPlayerInitialized() then local playerPed = PlayerPedId() if playerPed and playerPed ~= -1 then local x, y, z = table.unpack(GetEntityCoords(playerPed)) x = tonumber(string.format("%.3f", x)) y = tonumber(string.format("%.3f", y)) z = tonumber(string.format("%.3f", z)) local pHealth = GetEntityHealth(playerPed) local pStamina = tonumber(string.format("%.2f", Citizen.InvokeNative(0x775A1CA7893AA8B5, playerPed, Citizen.ResultAsFloat()))) local pHealthCore = Citizen.InvokeNative(0x36731AC041289BB1 , playerPed, 0, Citizen.ResultAsInteger()) local pStaminaCore = Citizen.InvokeNative(0x36731AC041289BB1 , playerPed, 1, Citizen.ResultAsInteger()) TriggerServerEvent("FRP:CacheCharacterStats", {x, y, z}, pHealth, pStamina, pHealthCore, pStaminaCore) end end end end ) function cAPI.getPosition() local x, y, z = table.unpack(GetEntityCoords(PlayerPedId(), true)) return x, y, z end -- return vx,vy,vz function cAPI.getSpeed() local vx, vy, vz = table.unpack(GetEntityVelocity(PlayerPedId())) return math.sqrt(vx * vx + vy * vy + vz * vz) end function cAPI.GetCoordsFromCam(distance) local rot = GetGameplayCamRot(2) local coord = GetGameplayCamCoord() local tZ = rot.z * 0.0174532924 local tX = rot.x * 0.0174532924 local num = math.abs(math.cos(tX)) newCoordX = coord.x + (-math.sin(tZ)) * (num + distance) newCoordY = coord.y + (math.cos(tZ)) * (num + distance) newCoordZ = coord.z + (math.sin(tX) * 8.0) return newCoordX, newCoordY, newCoordZ end function cAPI.Target(Distance, Ped) local Entity = nil local camCoords = GetGameplayCamCoord() local farCoordsX, farCoordsY, farCoordsZ = cAPI.GetCoordsFromCam(Distance) local RayHandle = StartShapeTestRay(camCoords.x, camCoords.y, camCoords.z, farCoordsX, farCoordsY, farCoordsZ, -1, Ped, 0) local A, B, C, D, Entity = GetShapeTestResult(RayHandle) return Entity, farCoordsX, farCoordsY, farCoordsZ end -- function cAPI.getNearestPlayers(radius) -- local r = {} -- local ped = PlayerPedId() -- local pid = PlayerId() -- local pCoords = GetEntityCoords(ped) -- for _, v in pairs(GetActivePlayers()) do -- local player = GetPlayerFromServerId(v) -- local pPed = GetPlayerPed(player) -- local pPCoords = GetEntityCoords(pPed) -- local distance = #(pCoords - pPCoords) -- if distance <= radius then -- r[GetPlayerServerId(player)] = distance -- end -- end -- return r -- end -- function cAPI.getNearestPlayer(radius) -- local p = nil -- local players = cAPI.getNearestPlayers(radius) -- local min = radius + 10.0 -- for k, v in pairs(players) do -- if v < min then -- min = v -- p = k -- end -- end -- return p -- end -- return map of player id => distance function cAPI.getNearestPlayers(radius) local r = {} local ped = PlayerPedId() local pid = PlayerId() local px,py,pz = GetEntityCoords(ped) for k in pairs(GetActivePlayers()) do local player = GetPlayerFromServerId(k) if player ~= pid and NetworkIsPlayerConnected(player) then local oped = GetPlayerPed(player) local x,y,z = table.unpack(GetEntityCoords(oped,true)) local distance = GetDistanceBetweenCoords(x,y,z,px,py,pz,true) if distance <= radius then r[GetPlayerServerId(player)] = distance end end end return r end -- return player id or nil function cAPI.getNearestPlayer(radius) local p = nil local players = cAPI.getNearestPlayers(radius) local min = radius+10.0 for k,v in pairs(players) do if v < min then min = v p = k end end return p end local weaponModels = { "weapon_fishingrod", "weapon_moonshinejug", "weapon_bow", "weapon_lasso", "weapon_kit_camera", "weapon_kit_binoculars", "weapon_melee_knife_hunter", "weapon_melee_lantern_electric", "weapon_melee_torch", "weapon_melee_broken_sword", "weapon_melee_hatchet", "weapon_melee_cleaver", "weapon_melee_ancient_hatchet", "weapon_melee_hatchet_viking", "weapon_melee_hatchet_hewing", "weapon_melee_hatchet_double_bit", "weapon_melee_hatchet_double_bit_rusted", "weapon_melee_hatchet_hunter", "weapon_melee_hatchet_hunter_rusted", "weapon_melee_knife_john", "weapon_melee_knife", "weapon_melee_knife_jawbone", "weapon_melee_knife_miner", "weapon_melee_knife_civil_war", "weapon_melee_knife_bear", "weapon_melee_knife_vampire", "weapon_melee_machete", "weapon_pistol_m1899", "weapon_pistol_mauser", "weapon_pistol_mauser_drunk", "weapon_pistol_semiauto", "weapon_pistol_volcanic", "weapon_revolver_cattleman", "weapon_revolver_cattleman_john", "weapon_revolver_cattleman_mexican", "weapon_revolver_cattleman_pig", "weapon_revolver_doubleaction", "weapon_revolver_doubleaction_exotic", "weapon_revolver_doubleaction_gambler", "weapon_revolver_doubleaction_micah", "weapon_revolver_lemat", "weapon_revolver_schofield", "weapon_revolver_schofield_golden", "weapon_revolver_schofield_calloway", "weapon_repeater_winchester", "weapon_repeater_carbine", "weapon_repeater_evans", "weapon_rifle_boltaction", "weapon_rifle_springfield", "weapon_rifle_varmint", "weapon_sniperrifle_carcano", "weapon_sniperrifle_rollingblock", "weapon_sniperrifle_rollingblock_exotic", "weapon_shotgun_doublebarrel", "weapon_shotgun_doublebarrel_exotic", "weapon_shotgun_pump", "weapon_shotgun_repeating", "weapon_shotgun_sawedoff", "weapon_shotgun_semiauto", "weapon_thrown_throwing_knives", "weapon_thrown_dynamite", "weapon_thrown_molotov", "weapon_thrown_tomahawk", "weapon_thrown_tomahawk_ancient" } function cAPI.getWeapons() local ped = PlayerPedId() local ammo_types = {} local weapons = {} for k, v in pairs(weaponModels) do local hash = GetHashKey(v) if HasPedGotWeapon(ped, hash) then local atype = GetPedAmmoTypeFromWeapon(ped, hash) if ammo_types[atype] == nil then ammo_types[atype] = true weapons[v] = GetAmmoInPedWeapon(ped, hash) else weapons[v] = 0 end end end return weapons end -- function cAPI.removeWeapon(weapon) -- local weapons = cAPI.getWeapons() -- if weapons[weapon] then -- weapons[weapon] = nil -- end -- cAPI.replaceWeapons(weapons) -- end function cAPI.replaceWeapons(weapons) local old_weapons = cAPI.getWeapons() cAPI.giveWeapons(weapons, true) return old_weapons end function cAPI.giveWeapon(weapon, ammo, clear_before) cAPI.giveWeapons( { weapon = ammo }, clear_before ) end function cAPI.giveWeapons(weapons, clear_before) local ped = PlayerPedId() if clear_before then RemoveAllPedWeapons(ped, true, true) end for weapon, ammo in pairs(weapons) do local hash = GetHashKey(weapon) GiveWeaponToPed_2(PlayerPedId(), hash, ammo or 0, false, true, GetWeapontypeGroup(hash), ammo > 0, 0.5, 1.0, 0, true, 0, 0) Citizen.InvokeNative(0x5E3BDDBCB83F3D84, PlayerPedId(), hash, 0, false, true) Citizen.InvokeNative(0x5FD1E1F011E76D7E, PlayerPedId(), GetPedAmmoTypeFromWeapon(PlayerPedId(), hash), ammo) end end function cAPI.setArmour(amount) SetPedArmour(PlayerPedId(), amount) end function cAPI.getArmour() return GetPedArmour(PlayerPedId()) end function cAPI.setHealth(amount) SetEntityHealth(PlayerPedId(), math.floor(amount)) end function cAPI.getHealth() return GetEntityHealth(PlayerPedId()) end local prompResult = nil function cAPI.prompt(title, default_text) SendNUIMessage({act = "prompt", title = title, text = tostring(default_text)}) SetNuiFocus(true) while prompResult == nil do Citizen.Wait(10) end local _temp = prompResult prompResult = nil return _temp end RegisterNUICallback( "prompt", function(data, cb) if data.act == "close" then SetNuiFocus(false) prompResult = data.result end end ) local requests = {} function cAPI.request(text, time) local id = math.random(999999) SendNUIMessage({act = "request", id = id, text = tostring(text), time = time}) -- !!! OPTIMIZATION -- Stop the loop while the time has passed while requests[id] == nil do Citizen.Wait(10) end local _temp = requests[id] or false requests[id] = nil return _temp end RegisterNUICallback( "request", function(data, cb) if data.act == "response" then requests[data.id] = data.ok end end ) Citizen.CreateThread( function() while true do Citizen.Wait(3) if IsControlJustPressed(0, 0xCEFD9220) then SendNUIMessage({act = "event", event = "yes"}) end if IsControlJustPressed(0, 0x4BC9DABB) then SendNUIMessage({act = "event", event = "no"}) end end end ) local Invinsible function cAPI.toggleInvinsible() Invinsible = not Invinsible if Invinsible then SetEntityInvincible(PlayerPedId(), true) else SetEntityInvincible(PlayerPedId(), false) end end local noclip = false local noclip_speed = 10.0 function cAPI.toggleNoclip() noclip = not noclip if noclip then SetEntityInvincible(PlayerPedId(), true) SetEntityVisible(PlayerPedId(), false) NetworkSetEntityInvisibleToNetwork(PlayerPedId(), true) else SetEntityInvincible(PlayerPedId(), false) SetEntityVisible(PlayerPedId(), true) NetworkSetEntityInvisibleToNetwork(PlayerPedId(), false) end end local function getCamDirection() local heading = GetGameplayCamRelativeHeading() + GetEntityHeading(PlayerPedId()) local pitch = GetGameplayCamRelativePitch() local x = -math.sin(heading * math.pi / 180.0) local y = math.cos(heading * math.pi / 180.0) local z = math.sin(pitch * math.pi / 180.0) local len = math.sqrt(x * x + y * y + z * z) if len ~= 0 then x = x / len y = y / len z = z / len end return x, y, z end Citizen.CreateThread( function() while true do Citizen.Wait(0) SetEntityMaxHealth(PlayerPedId(), 150) SetPlayerHealthRechargeMultiplier(PlayerId(), 0.0) if noclip then local ped = PlayerPedId() local x, y, z = cAPI.getPosition() local dx, dy, dz = getCamDirection() local speed = noclip_speed SetEntityVelocity(ped, 0.0001, 0.0001, 0.0001) if IsControlPressed(0, 0x8FD015D8) then x = x + speed * dx y = y + speed * dy z = z + speed * dz end if IsControlPressed(0, 0xD27782E3) then x = x - speed * dx y = y - speed * dy z = z - speed * dz end if IsControlPressed(0, 0x8FFC75D6) then -- SHIFT noclip_speed = 10.0 elseif IsControlPressed(0, 0xDB096B85) then -- CTRL noclip_speed = 0.2 else noclip_speed = 1.0 end SetEntityCoordsNoOffset(ped, x, y, z, true, true, true) end end end ) function cAPI.playAnim(dict, anim, speed) if not IsEntityPlayingAnim(PlayerPedId(), dict, anim) then RequestAnimDict(dict) while not HasAnimDictLoaded(dict) do Citizen.Wait(100) end TaskPlayAnim(PlayerPedId(), dict, anim, speed, 1.0, -1, 0, 0, 0, 0, 0, 0, 0) end end function cAPI.isPlayingAnimation(dict, anim) local ped = PlayerPedId() return IsEntityPlayingAnim(ped, dict, anim, 3) end function cAPI.clientConnected(bool) if bool then ShutdownLoadingScreenNui() ShutdownLoadingScreen() end end function cAPI.LoadModel(hash) local waiting = 0 if IsModelValid(hash) then if not HasModelLoaded(hash) then RequestModel(hash) while not HasModelLoaded(hash) do Citizen.Wait(10) end return true end end return false end function cAPI.StartFade(timer) DoScreenFadeOut(timer) while IsScreenFadingOut() do Citizen.Wait(1) end end function cAPI.EndFade(timer) ShutdownLoadingScreen() DoScreenFadeIn(timer) while IsScreenFadingIn() do Citizen.Wait(1) end end local serverToUserChanged = false local serverToUser = {} RegisterNetEvent('FRP:_CORE:SetServerIdAsUserId') AddEventHandler('FRP:_CORE:SetServerIdAsUserId', function(serverid, userid) serverToUser[serverid] = userid serverToUserChanged = true end) RegisterNetEvent('FRP:_CORE:SetServerIdAsUserIdPacked') AddEventHandler('FRP:_CORE:SetServerIdAsUserIdPacked', function(r) serverToUser = r serverToUserChanged = true end) function cAPI.GetUserIdFromServerId(serverid) return serverToUser[serverid] or 0 end function cAPI.GetServerIdFromUserId(userid) for serverid, _userid in pairs(serverToUser) do if _userid == userid then return serverid end end return 0 end
local anim = false function onRender() local forcedanimation = getElementData(getLocalPlayer(), "forcedanimation") if (getPedAnimation(getLocalPlayer())) and not (forcedanimation) then local screenWidth, screenHeight = guiGetScreenSize() anim = true dxDrawText("Press Spacebar to Cancel Animation", screenWidth-420, screenHeight-91, screenWidth, screenHeight, tocolor ( 0, 0, 0, 255 ), 1, "pricedown") dxDrawText("Press Spacebar to Cancel Animation", screenWidth-422, screenHeight-93, screenWidth-30, screenHeight, tocolor ( 255, 255, 255, 255 ), 1, "pricedown") end if not (getPedAnimation(getLocalPlayer())) and (anim) then anim = false toggleAllControls(true, true, false) end end addEventHandler("onClientRender", getRootElement(), onRender)
local libcore = require "core.libcore" local Class = require "Base.Class" local Unit = require "Unit" local OptionControl = require "Unit.ViewControl.OptionControl" local RectifierUnit = Class {} RectifierUnit:include(Unit) function RectifierUnit:init(args) args.title = "Rectify" args.mnemonic = "Re" Unit.init(self, args) end function RectifierUnit:onLoadGraph(channelCount) if channelCount == 2 then self:loadStereoGraph() else self:loadMonoGraph() end end function RectifierUnit:loadMonoGraph() local rectify = self:addObject("rectify", libcore.Rectify()) connect(self, "In1", rectify, "In") connect(rectify, "Out", self, "Out1") end function RectifierUnit:loadStereoGraph() local rectify1 = self:addObject("rectify1", libcore.Rectify()) local rectify2 = self:addObject("rectify2", libcore.Rectify()) connect(self, "In1", rectify1, "In") connect(self, "In2", rectify2, "In") connect(rectify1, "Out", self, "Out1") connect(rectify2, "Out", self, "Out2") tie(rectify2, "Type", rectify1, "Type") self.objects.rectify = self.objects.rectify1 end local views = { expanded = { "type" }, collapsed = {} } function RectifierUnit:onLoadViews(objects, branches) local controls = {} controls.type = OptionControl { button = "o", description = "Type", option = objects.rectify:getOption("Type"), choices = { "positive half", "negative half", "full" }, muteOnChange = true } return controls, views end return RectifierUnit
local function printInterpol(yazi) MsgC( Color(0,245,163), "[gInterpol] ", Color( 255, 255, 255),yazi, "\n") end hook.Add( "PlayerInitialSpawn", "whitelist_uyari", function( ply ) if gInterpolWhitelist[ ply:SteamID64() ] then printInterpol("--------------------------------------------------------------------------") printInterpol("Sunucuya gInterpol tarafından yasaklanmış whiteliste eklenmis oyuncu girdi") printInterpol("--------------------------------------------------------------------------") printInterpol("Oyuncu Adı : "..ply:Nick()) printInterpol("--------------------------------------------------------------------------") printInterpol("Oyuncu SteamID64 : "..ply:SteamID64()) printInterpol("--------------------------------------------------------------------------") end end )
#!/usr/bin/env tarantool test = require("sqltester") test:plan(3) --!./tcltestrunner.lua -- 2011 July 8 -- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, never taking more than you give. -- ------------------------------------------------------------------------- -- This file implements regression tests for sql library. The -- focus of this file is testing that bug [54844eea3f] has been fixed. -- -- ["set","testdir",[["file","dirname",["argv0"]]]] -- ["source",[["testdir"],"\/tester.tcl"]] testprefix = "tkt-54844eea3f" test:do_execsql_test( "1.0", [[ CREATE TABLE t1(a INTEGER PRIMARY KEY); INSERT INTO t1 VALUES(1); INSERT INTO t1 VALUES(4); CREATE TABLE t2(b INTEGER PRIMARY KEY); INSERT INTO t2 VALUES(1); INSERT INTO t2 VALUES(2); INSERT INTO t2 SELECT b+2 FROM t2; INSERT INTO t2 SELECT b+4 FROM t2; INSERT INTO t2 SELECT b+8 FROM t2; INSERT INTO t2 SELECT b+16 FROM t2; CREATE TABLE t3(c INTEGER PRIMARY KEY); INSERT INTO t3 VALUES(1); INSERT INTO t3 VALUES(2); INSERT INTO t3 VALUES(3); ]], { -- <1.0> -- </1.0> }) test:do_execsql_test( "1.1", [[ SELECT 'test-2', t3.c, ( SELECT count(*) FROM t1 JOIN (SELECT DISTINCT t3.c AS p FROM t2) AS x ON t1.a=x.p ) FROM t3; ]], { -- <1.1> "test-2", 1, 1, "test-2", 2, 0, "test-2", 3, 0 -- </1.1> }) test:do_execsql_test( "1.2", [[ CREATE TABLE t4(id INT primary key, a TEXT, b TEXT, c TEXT); INSERT INTO t4 VALUES(1, 'a', 1, 'one'); INSERT INTO t4 VALUES(2, 'a', 2, 'two'); INSERT INTO t4 VALUES(3, 'b', 1, 'three'); INSERT INTO t4 VALUES(4, 'b', 2, 'four'); SELECT ( SELECT c FROM ( SELECT a,b,c FROM t4 WHERE a=output.a ORDER BY b LIMIT 10 OFFSET 1 ) WHERE b=output.b ) FROM t4 AS output; ]], { -- <1.2> "", "two", "", "four" -- </1.2> }) test:finish_test()
--Resource monitoring local monitor = {} --Unit:MB monitor.memory_used = 0 -- script memory being used by Lua (Unit:) monitor.objects_rendered = 0 monitor.light_sources = 0 monitor.draw_calls = 0 -- Number of draw calls made in a frame monitor.texture_memory = 0 -- VRam being used (Unit:) monitor.shader_switches = 0 monitor.ms = 0 -- Delta time monitor.images_loaded = 0 -- number of images loaded local Str = string.sub local Tostr = tostring local Coll = collectgarbage local timer = 0 local timer_max = 60 local FPS = 0 local function get_stats() -- update variables monitor.memory_used = Str(Tostr(Coll("count")/1024),0,5) local stats = love.graphics.getStats() monitor.draw_calls = stats.drawcalls monitor.texture_memory = stats.texturememory/1024/1024 monitor.shader_switches = stats.shaderswitches monitor.images_loaded = stats.images stats = nil end monitor.update = function(dt) FPS = 1/dt timer = timer + 1 if timer >= timer_max then timer = 0 get_stats() monitor.ms = Str(Tostr(dt*1000),0,5) end end monitor.draw = function() love.graphics.print("FPS: "..FPS,10,10) love.graphics.print("MS: "..monitor.ms,10,30) love.graphics.print("Script Memory(KB): "..monitor.memory_used,10,50) love.graphics.print("Texture Memory(MB): "..monitor.texture_memory,10,70) love.graphics.print("Draw Calls: "..monitor.draw_calls,10,90) love.graphics.print("Images Loaded: "..monitor.images_loaded,10,110) love.graphics.print("Shader Switches: "..monitor.shader_switches,10,130) love.graphics.print("Light Sources: "..monitor.light_sources,10,150) love.graphics.print("Objects Rendered: "..monitor.objects_rendered,10,170) end return monitor
local playsession = { {"Redbeard28", {71876}}, {"BlkKnight", {69684}}, {"Krengrus", {24469}} } return playsession
#!/usr/bin/env lua file = io.open(arg[1]) io.write("<html>\n") io.write("<head>\n") io.write("<title>Soundpipe</title>\n") io.write("<link rel=\"stylesheet\" href=\"css/skeleton.css\">\n") io.write("<link rel=\"stylesheet\" href=\"css/normalize.css\">\n") io.write("</head>\n") io.write("<body>\n<div class=\"container\">\n") io.write("<h1>Soundpipe Modules</h1><table>\n") for line in file:lines() do sptbl = {} dofile(string.format("modules/data/%s.lua", line)) io.write("<tr><td>\n") io.write(string.format("<a href=\"%s.html\">%s</a></td><td><nobr>\n", line, line)) firstline = string.gsub(sptbl[line].description, "\n.+", "") -- newstring = string.gsub(string,"Tutorial","Language") io.write(string.format("%s\n", string.sub(firstline, 0, 80))) if string.len(firstline) > 80 then io.write("...") end io.write("</nobr></td></tr>\n") end io.write("</table></body></html>\n")
--GPU: Image Object. --luacheck: push ignore 211 local Config, GPU, yGPU, GPUVars, DevKit = ... --luacheck: pop local SharedVars = GPUVars.Shared local RenderVars = GPUVars.Render local CalibrationVars = GPUVars.Calibration local VRamVars = GPUVars.VRam --==Varss Constants==-- local Verify = SharedVars.Verify local ofs = CalibrationVars.Offsets local UnbindVRAM = VRamVars.UnbindVRAM --==GPU Image API==-- function GPU.quad(x,y,w,h,sw,sh) local ok, err = pcall(love.graphics.newQuad,x,y,w,h,sw,sh) if ok then return err else return error(err) end end function GPU.image(data) local Image, SourceData if type(data) == "string" then --Load liko12 specialized image format local ok, imageData = pcall(GPU.imagedata,data) if not ok then return error(imageData) end return imageData:image() elseif type(data) == "userdata" and data.typeOf and data:typeOf("ImageData") then local ok, err = pcall(love.graphics.newImage,data) if not ok then return error("Invalid image data") end Image = err Image:setWrap("repeat") SourceData = data end local i = {} function i:draw(x,y,r,sx,sy,quad) UnbindVRAM() x, y, r, sx, sy = x or 0, y or 0, r or 0, sx or 1, sy or 1 GPU.pushColor() love.graphics.setShader(RenderVars.ImageShader) love.graphics.setColor(1,1,1,1) if quad then love.graphics.draw(Image,quad,math.floor(x+ofs.quad[1]),math.floor(y+ofs.quad[2]),r,sx,sy) else love.graphics.draw(Image,math.floor(x+ofs.image[1]),math.floor(y+ofs.image[2]),r,sx,sy) end love.graphics.setShader(RenderVars.DrawShader) GPU.popColor() RenderVars.ShouldDraw = true return self end function i:refresh() Image:replacePixels(SourceData) return self end function i:size() return Image:getDimensions() end function i:width() return Image:getWidth() end function i:height() return Image:getHeight() end function i:data() return GPU.imagedata(SourceData) end function i:quad(x,y,w,h) return love.graphics.newQuad(x,y,w or self:width(),h or self:height(),self:width(),self:height()) end function i:batch(bufferSize, usage) bufferSize, usage = bufferSize or 1000, usage or "static" Verify(bufferSize,"bufferSize","number") if not (bufferSize >= 1) then return error("Buffersize should be 1 or bigger, provided: "..bufferSize) end Verify(usage,"usage","string") if usage ~= "dynamic" and usage ~= "static" and usage ~= "stream" then return error("Invalid usage: "..usage) end local spritebatch = love.graphics.newSpriteBatch(Image,bufferSize, usage) local sb = {} function sb:usage() return usage end function sb:clear() spritebatch:clear() return self end function sb:flush() spritebatch:flush() return self end function sb:setBufferSize(size) Verify(size,"bufferSize","number") if not (size >= 1) then return error("Buffersize should be 1 or bigger, provided: "..size) end spritebatch:setBufferSize(size) return self end function sb:getBufferSize() return spritebatch:getBufferSize() end function sb:getCount() return spritebatch:getCount() end function sb:add(quad,x,y,r,sx,sy,ox,oy,kx,ky) x,y,r,sx,sy,ox,oy,kx,ky = x or 0, y or 0, r or 0, sx or 1, sy or sx or 1, ox or 0, oy or 0, kx or 0, ky or 0 if type(quad) ~= "userdata" then return error("Quad should be provided, ("..type(quad)..") is not accepted.") end Verify(x,"x","number") Verify(y,"y","number") Verify(r,"r","number") Verify(sx,"sx","number") Verify(sy,"sy","number") Verify(ox,"ox","number") Verify(ox,"ox","number") Verify(kx,"kx","number") Verify(kx,"kx","number") return spritebatch:add(quad,x,y,r,sx,sy,ox,oy,kx,ky) end function sb:set(id,quad,x,y,r,sx,sy,ox,oy,kx,ky) x,y,r,sx,sy,ox,oy,kx,ky = x or 0, y or 0, r or 0, sx or 1, sy or sx or 1, ox or 0, oy or 0, kx or 0, ky or 0 if type(quad) ~= "userdata" then return error("Quad should be provided, ("..type(quad)..") is not accepted.") end Verify(id,"id","number") Verify(x,"x","number") Verify(y,"y","number") Verify(r,"r","number") Verify(sx,"sx","number") Verify(sy,"sy","number") Verify(ox,"ox","number") Verify(ox,"ox","number") Verify(kx,"kx","number") Verify(kx,"kx","number") local ok, err = pcall(spritebatch.set,spritebatch,id,quad,x,y,r,sx,sy,ox,oy,kx,ky) if not ok then return error(err) end return self end function sb:draw(x,y,r,sx,sy,quad) UnbindVRAM() x, y, r, sx, sy = x or 0, y or 0, r or 0, sx or 1, sy or 1 GPU.pushColor() love.graphics.setShader(RenderVars.ImageShader) love.graphics.setColor(1,1,1,1) if quad then love.graphics.draw(spritebatch,quad,math.floor(x+ofs.quad[1]),math.floor(y+ofs.quad[2]),r,sx,sy) else love.graphics.draw(spritebatch,math.floor(x+ofs.image[1]),math.floor(y+ofs.image[2]),r,sx,sy) end love.graphics.setShader(RenderVars.DrawShader) GPU.popColor() RenderVars.ShouldDraw = true return self end return sb end function i:type() return "GPU.image" end function i:typeOf(t) if t == "GPU" or t == "image" or t == "GPU.image" or t == "LK12" then return true end end return i end
local sh = setmetatable({}, { __index = function(_, k) return _3DreamEngine.lightShaders["point_shadow"][k] end }) sh.func = "sampleShadowPointSmoothDynamic" function sh:constructDefinesGlobal(dream) return [[ float sampleShadowPointSmoothDynamic(vec3 lightVec, samplerCube tex) { float sharpness = 10.0; float depth = length(lightVec); float bias = depth * 0.01 + 0.01; //direction vec3 n = normalize(-lightVec * vec3(1.0, -1.0, 1.0)); //fetch vec2 r = texture(tex, n).xy; return ( clamp(exp(sharpness * (r.x - depth)), 0.0, 1.0) * (r.y + bias > depth ? 1.0 : 0.0) ); } ]] end return sh
-- // Remove Duplicate GUIS for _, v in ipairs(game.CoreGui:GetChildren()) do if v.Name == "ScreenGui" then v:Destroy() end end -- // UI Library Depedency local library = loadstring(game:HttpGet("https://raw.githubusercontent.com/wally-rblx/uwuware-ui/main/main.lua"))() -- // Services local players = game:GetService("Players") local runService = game:GetService("RunService") -- // Variables local localPlayer = players.LocalPlayer local playerChar = localPlayer.Character or localPlayer.Character:Wait() -- // UI Components local window = library:CreateWindow("Floppa Hub") do local mainFolder = window:AddFolder("Main") do mainFolder:AddToggle({text = "Spam Toilets Flush", flag = "spamFlush"}) mainFolder:AddToggle({text = "Spam Toilets Seats", flag = "spamSeat"}) mainFolder:AddToggle({text = "Spam Sinks", flag = "spamSinks"}) mainFolder:AddToggle({text = "Spam Dryers", flag = "spamSinks"}) mainFolder:AddToggle({text = "Spam All", flag = "spamAll"}) end end -- // Heartbeat Listener runService.Heartbeat:Connect( function() for _, v in pairs(game.Workspace:GetDescendants()) do if v:IsA("ClickDetector") then if v.Parent.Name == "Push" and library.flags.spamFlush then fireclickdetector(v, math.huge) end if string.find(v.Parent.Name, "ToiletSeat") and library.flags.spamSeat then fireclickdetector(v, math.huge) end if v.Parent.Name == "Faucet" and library.flags.spamSinks then fireclickdetector(v, math.huge) end if v.Parent.Name == "Button" and v.Parent.Parent.Name == "Hand Dryer" and library.flags.spamDryer then fireclickdetector(v, math.huge) end if library.flags.spamAll then fireclickdetector(v, math.huge) end end end end ) -- // Init Library library:Init()
translations.id = { name = "id", fullname = "Bahasa Indonesia", -- Error messages corrupt_map = "<r>Peta rusak. Sedang Memuat peta lainnya.", corrupt_map_vanilla = "<r>[KESALAHAN] <n>Tidak bisa mendapatkan informasi dari peta ini.", corrupt_map_mouse_start = "<r>[KESALAHAN] <n>Peta ini harus memiliki posisi awal (titik spawn tikus).", corrupt_map_needing_chair = "<r>[KESALAHAN] <n>Peta harus memiliki kursi di akhir.", corrupt_map_missing_checkpoints = "<r>[KESALAHAN] <n>Peta harus memiliki setidaknya satu cekpoin (paku kuning).", corrupt_data = "<r>Sayangnya, data anda rusak dan telah disetel ulang.", min_players = "<r>Untuk menyimpan data anda, setidaknya ada 4 pemain unik di ruangan ini. <bl>[%s/%s]", tribe_house = "<r>Data tidak akan tersimpan di Rumah suku.", invalid_syntax = "<r>Sintaks tidak valid.", code_error = "<r>Terjadi kesalahan: <bl>%s-%s-%s %s", emergency_mode = "<r>Penghentian darurat, tidak ada pemain baru diizinkan. Dimohon untuk pergi ke ruangan #parkour lain.", leaderboard_not_loaded = "<r>Papan peringkat belum bisa dimuat. Mohon Tunggu sebentar.", max_power_keys = "<v>[#] <r>Anda hanya bisa memiliki paling banyak %s kemampuan dengan kata kunci yang sama.", -- Help window help = "Bantuan", staff = "Staff", rules = "Peraturan", contribute = "Kontribusi", changelog = "Berita", help_help = "<p align = 'center'><font size = '14'>Selamat datang di ruangan <T>#parkour!</T></font></p>\n<font size = '12'><p align='center'><J>Tujuan anda adalah meraih semua cekpoin sebelum menyelesaikan peta</J></p>\n\n<N>• Tekan <O>O</O>, ketik <O>!op</O> atau klik pada <O>tombol konfigurasi</O> untuk membuka <T>menu Opsi</T>.\n• Tekan <O>P</O> atau klik <O>ikon kepalan tangan</O> pada kanan atas untuk membuka <T>menu Kemampuan</T>.\n• Tekan <O>L</O> atau ketik <O>!lb</O> untuk membuka <T>Papan Peringkat</T>.\n• Tekan <O>M</O> atau tombol <O>Delete</O> untuk <T>/mort</T>, anda bisa mengaktifkan tombol di menu <J>Opsi</J>.\n• Untuk mengetahui <O>staf</O> kami dan <O>aturan parkour</O>, klik pada tab <T>Staf</T> dan <T>Peraturan</T>.\n• Klik <a href='event:discord'><o>disini</o></a> untuk mendapatkan tautan discord dan <a href='event:map_submission'><o>disini</o></a> untuk mendapatkan tautan topik mengenai pengajuan peta.\n• Gunakan <o>atas</o> dan <o>bawah</o> tombol panah ketika anda ingin melakukan scroll.\n\n<p align = 'center'><font size = '13'><T>Kontribusi telah dibuka! Untuk info lebih lanjut, klik pada tab <O>Kontribusi</O>!</T></font></p>", help_staff = "<p align = 'center'><font size = '13'><r>DISCLAIMER: Staf Parkour BUKAN staf Transformice dan TIDAK memiliki wewenang apapun didalam game itu sendiri, hanya di dalam modul.</r>\nStaf parkour memastikan modul berjalan sempurna dengan masalah yang minim, dan akan selalu tersedia untuk membantu pemain kapan pun dibutuhkan.</font></p>\nanda bisa mengetik <D>!staff</D> di chat untuk melihat list staf.\n\n<font color = '#E7342A'>Admin:</font> Mereka bertanggung jawab dalam mengembangkan modul dengan menambahkan update baru ataupun memperbaiki bug.\n\n<font color = '#D0A9F0'>Manager Tim:</font> Mereka mengawasi tim dari moderator dan mappers untuk memastikan mereka mengerjakan perkerjaan mereka dengan baik. Mereka juga bertanggung jawab untuk merekrut anggota baru ke tim staf.\n\n<font color = '#FFAAAA'>Moderator:</font> Mereka bertanggung jawab untuk menegakkan aturan dari modul dan memberikan sanksi untuk individu yang tidak mengikutinya.\n\n<font color = '#25C059'>Mappers:</font> Mereka bertanggung jawab dalam meninjau, menambahkan, menghapus peta yang ada di modul untuk memastikan permainan yang menyenangkan.", help_rules = "<font size='13'><B><J>Semua aturan dalam Syarat dan Ketentuan Transformice berlaku juga di #parkour</J></B></font>\n\nJika anda menemukan pemain yang melanggar aturan tersebut, bisik moderator di game. Jika tidak ada moderator yang online, dianjurkan untuk melaporkan melalui server discord. \nKetika melaporkan, mohon untuk melampirkan server, nama ruangan, dan nama pemain. \n• Contoh: en-#parkour10 Blank#3495 trolling\nBukti seperti tangkapan layar, video, atau gif sangat membantu dan dihargai, tetapi tidak perlu.\n\n<font size='11'>• Tidak ada <font color='#ef1111'>hacks, glitches or bugs</font> yang digunakan di ruangan #parkour.\n• <font color='#ef1111'>VPN farming</font> akan dianggap sebagai <B>mengeksploitasi</B> dan tidak diizinkan.<p align='center'><font color='#cc2222' size='12'><B>\nSiapapun yang ketahuan melanggar aturan ini akan segera diblokir.</B></font></p>\n\n<font size='12'>Transformice mengizinkan konsep trolling. Namun, <font color='#cc2222'><B>kami tidak mengizinkannya di parkour.</B></font></font>\n\n<p align='center'><J>Trolling adalah ketika seorang pemain dengan sengaja menggunakan kemampuan atau consumables untuk mencegah pemain lain dalam menyelesaikan peta.</j></p>\n• Trolling balas dendam<B> bukan sebuah alasan yang valid</B> untuk melakukan troll kepada seseorang dan anda akan tetap diberi hukuman.\n• Memaksa membantu pemain yang mencoba untuk menyelesaikan peta sendirian dan menolak untuk berhenti melakukannya jika diminta juga termasuk sebagai trolling\n• <J>Jika seorang pemain tidak ingin bantuan dan lebih memilih solo, lebih baik membantu pemain yang lain</J>. Namun jika ada pemain lain yang meminta bantuan di cekpoin yang sama dengan pemain solo, anda bisa membantu mereka [Keduanya].\n\nJika pemain tertangkap melakukan trolling, mereka akan mendapatkan hukuman berbasis waktu. Perlu diperhatikan bahwa trolling yang berulang akan mengakibatkan hukuman yang lebih lama dan lebih berat.", help_contribute = "<font size='14'>\n<p align='center'>Tim managemen parkour menyukai kode sumber terbuka karena itu <t>membantu komunitas</t>. anda bisa <o>melihat</o> dan <o>memodifikasi</o> kode sumber dari <o><u><a href='event:github'>GitHub</a></u></o>.\n\nMemelihara modul <t>sepenuhnya bersifat sukarela</t>, sehingga bantuan mengenai <t>kode</t>, <t>laporan bug</t>, <t>saran</t> dan <t>pembuatan peta</t> selalu <u>diterima dan dihargai</u>.\nanda bisa <vp>melaporkan bug</vp> dan <vp>memberikan saran</vp> pada <o><u><a href='event:discord'>Discord</a></u></o> dan/atau <o><u><a href='event:github'>GitHub</a></u></o>.\nanda bisa <vp>mengirimkan peta anda</vp> di <o><u><a href='event:map_submission'>Forum Thread</a></u></o> kami.\n\nMemelihara parkour memang tidak mahal, tapi juga tidak gratis. Kami akan senang jika anda bisa membantu kami dengan <t>berdonasi berapapun jumlahnya</t> <o><u><a href='event:donate'>disini</a></u></o>.\n<u>Semua donasi akan digunakan untuk meningkatkan modul.</u></p>", help_changelog = "<font size='13'><p align='center'><o>Versi 2.9.0 - 13/12/2020</o></p>\n\n<font size='11'>• Perubahan beberapa sprite untuk <ch>natal</ch>!\n• Perbaikan <r>bug visual</r>\n• <vp>Infrastruktur modul</vp> telah ditingkatkan\n• Anda sekarang bisa <t>menyetel ulang kekuatan</t> ke <t>kunci default</t>\n• <cep>Ketika semua pemain menyelesaikan peta</cep>, timer akan disetel ke <cep>5 detik dibandingkan 20</cep>.\n• <cs>Penambahan mode AFK</cs>\n• Meningkatkan <ps>cooldown salju</ps>", -- Congratulation messages reached_level = "<d>Selamat! anda telah meraih level <vp>%s</vp>. (<t>%ss</t>)", finished = "<d><o>%s</o> telah menyelesaikan parkour dalam <vp>%s</vp> detik, <fc>selamat!", unlocked_power = "<ce><d>%s</d> telah membuka kemampuan <vp>%s</vp>.", -- Information messages mod_apps = "<j>Aplikasi untuk moderator parkour telah dibuka! Gunakan link ini: <rose>%s", staff_power = "<p align='center'><font size='12'><r>Staf parkour <b>tidak memiliki</b> wewenang apapun di selain ruangan #parkour.", donate = "<vp>Ketik <b>!donate</b> jika anda ingin berdonasi untuk modul ini!", paused_events = "<cep><b>[Perhatian!]</b> <n>Modul mencapai batas kritis terpaksa dihentikan sementara.", resumed_events = "<n2>Modul telah dimulai kembali.", welcome = "<n>Selamat datang di <t>#parkour</t>!", module_update = "<r><b>[Perhatian!]</b> <n>Modul akan diperbarui dalam waktu <d>%02d:%02d</d>.", leaderboard_loaded = "<j>Papan peringkat sudah dimuat. Ketuk L untuk membukanya.", kill_minutes = "<R>Kemampuan anda dimatikan paksa selama %s menit.", permbanned = "<r>Anda telah diblokir selamanya di #parkour.", tempbanned = "<r>Anda telah diblokir dari #parkour selama %s menit.", forum_topic = "<rose>Untuk informasi lebih lanjut mengenai modul kunjungi tautan: %s", report = "<j>Ingin melaporkan seorang pemain? <t><b>/c Parkour#8558 .report Username#0000</b></t>", -- Records records_enabled = "<v>[#] <d>Mode rekor diaktifkan di room ini. Statistik tidak dihitung dan kekuatan tidak diaktifkan!\nAnda bisa mencari informasi lebih lanjut mengenai rekor di <b>%s</b>", records_admin = "<v>[#] <d>Anda adalah admin di ruangan rekor ini. Anda bisa menggunakan perintah <b>!map</b>, <b>!setcp</b>, <b>!pw</b> dan <b>!time</b>.", records_completed = "<v>[#] <d>Anda telah menyelesaikan peta! Jika anda ingin mengulangi-nya lagi, ketik <b>!redo</b>.", records_submit = "<v>[#] <d>Wow! Sepertinya anda memiliki waktu tercepat di ruangan. Jika anda ingin mengirimkan rekor anda, ketik <b>!submit</b>.", records_invalid_map = "<v>[#] <r>Sepertinya ruangan ini tidak masuk dalam rotasi parkour... Anda tidak bisa mengirim rekor ini!", records_not_fastest = "<v>[#] <r>Sepertinya anda bukan pemain tercepat di ruangan ini...", records_already_submitted = "<v>[#] <r>Anda sudah mengirimkan rekor anda untuk peta ini!", records_submitted = "<v>[#] <d>Rekor anda untuk peta <b>%s</b> telah dikirim.", -- Miscellaneous afk_popup = "\n<p align='center'><font size='30'><bv><b>ANDA DALAM MODE AFK</b></bv>\nPINDAH UNTUK RESPAWN</font>\n\n<font size='30'><u><t>Pengingat:</t></u></font>\n\n<font size='15'><r>Pemain dengan simbol merah tidak menginginkan bantuan!\nTrolling/pemblokiran pemain lain di parkur TIDAK dizinkan!<d>\nBergabung dengan <cep><a href='event:discord'>discord server</a> kami</cep>!\nIngin berkontribusi dengan kode? Lihat <cep><a href='event:github'>repository github</a> kami</cep>\nKamu memiliki peta bagus untuk diajukan? Posting di <cep><a href='event:map_submission'>topik pengajuan peta</a> kami</cep>\nCek <cep><a href='event:forum'>topik resmi</a></cep> kami untuk informasi lebih lanjut!\nDukung kami dengan <cep><a href='event:donate'>donasi!</a></cep>", options = "<p align='center'><font size='20'>Opsi Parkour</font></p>\n\nGunakan keyboard <b>QWERTY</b> (nonaktifkan jika <b>AZERTY</b>)\n\nTekan <b>M</b> hotkey untuk <b>/mort</b> (jika dinonaktifkan menjadi <b>DEL</b>)\n\nPerlihatkan cooldown kemampuan anda\n\nPerlihatkan tombol kemampuan\n\nPerlihatkan tombol bantuan\n\nAktifkan pengumuman penyelesaian peta\n\nAktifkan simbol tidak memerlukan bantuan", cooldown = "<v>[#] <r>Mohon Tunggu beberapa detik untuk melakukan-nya kembali.", power_options = ("<font size='13' face='Lucida Console,Liberation Mono,Courier New'>Keyboard <b>QWERTY</b>" .. "\n\n<b>Tutup</b> penghitung peta" .. "\n\nGunakan <b>kunci default</b>"), unlock_power = ("<font size='13' face='Lucida Console,Liberation Mono,Courier New'><p align='center'>Selesaikan <v>%s</v> peta" .. "<font size='5'>\n\n</font>untuk membuka" .. "<font size='5'>\n\n</font><v>%s</v>"), upgrade_power = ("<font size='13' face='Lucida Console,Liberation Mono,Courier New'><p align='center'>Selesaikan <v>%s</v> peta" .. "<font size='5'>\n\n</font>untuk meningkatkan ke" .. "<font size='5'>\n\n</font><v>%s</v>"), unlock_power_rank = ("<font size='13' face='Lucida Console,Liberation Mono,Courier New'><p align='center'>Peringkat <v>%s</v>" .. "<font size='5'>\n\n</font>untuk membuka" .. "<font size='5'>\n\n</font><v>%s</v>"), upgrade_power_rank = ("<font size='13' face='Lucida Console,Liberation Mono,Courier New'><p align='center'>Peringkat <v>%s</v>" .. "<font size='5'>\n\n</font>untuk meningkatkan ke" .. "<font size='5'>\n\n</font><v>%s</v>"), maps_info = ("<p align='center'><font size='11' face='Lucida Console,Liberation Mono,Courier New'><b><v>%s</v></b>" .. "<font size='5'>\n\n</font>Peta yang diselesaikan"), overall_info = ("<p align='center'><font size='11' face='Lucida Console,Liberation Mono,Courier New'><b><v>%s</v></b>" .. "<font size='5'>\n\n</font>Papan Peringkat Keseluruhan"), weekly_info = ("<p align='center'><font size='11' face='Lucida Console,Liberation Mono,Courier New'><b><v>%s</v></b>" .. "<font size='5'>\n\n</font>Papan Peringkat Mingguan"), badges = "<font size='14' face='Lucida Console,Liberation Mono,Courier New,Verdana'>Lencana (%s): <a href='event:_help:badge'><j>[?]</j></a>", private_maps = "<bl>Jumlah peta pada pemain ini bersifat Pribadi. <a href='event:_help:private_maps'><j>[?]</j></a></bl>\n", profile = ("<font size='12' face='Lucida Console,Liberation Mono,Courier New,Verdana'>%s%s %s\n\n" .. "Posisi papan peringkat keseluruhan: <b><v>%s</v></b>\n\n" .. "Posisi papan peringkat mingguan: <b><v>%s</v></b>"), map_count = "Jumlah peta: <b><v>%s</v> / <a href='event:_help:yellow_maps'><j>%s</j></a> / <a href='event:_help:red_maps'><r>%s</r></a></b>", help_badge = "Lencana adalah pencapaian yang bisa didapatkan pemain. Klik diatasnya untuk melihat deskripsi-nya.", help_private_maps = "Pemain ini tidak mau memperlihatkan jumlah peta mereka ke publik! jika ingin, anda juga bisa menyembunyikan-nya di profil anda.", help_yellow_maps = "Peta dengan warna kuning adalah peta yang sudah diselesaikan dalam minggu ini.", help_red_maps = "Peta dengan warna merah adalah peta yang sudah diselelesaikan dalam satu jam terakhir.", help_badge_1 = "Pemain ini pernah menjadi anggota staf parkour sebelumnya.", help_badge_2 = "Pemain ini berada atau pernah di halaman 1 dari papan peringkat keseluruhan.", help_badge_3 = "Pemain ini berada atau pernah di halaman 2 dari papan peringkat keseluruhan.", help_badge_4 = "Pemain ini berada atau pernah di halaman 3 dari papan peringkat keseluruhan.", help_badge_5 = "Pemain ini berada atau pernah di halaman 4 dari papan peringkat keseluruhan.", help_badge_6 = "Pemain ini berada atau pernah di halaman 5 dari papan peringkat keseluruhan.", help_badge_7 = "Pemain ini pernah berada di podium pada akhir papan peringkat mingguan.", help_badge_8 = "Pemain ini memiliki rekor menyelesaikan 30 peta per jam.", help_badge_9 = "Pemain ini memiliki rekor menyelesaikan 35 peta per jam.", help_badge_10 = "Pemain ini memiliki rekor menyelesaikan 40 peta per jam.", help_badge_11 = "Pemain ini memiliki rekor menyelesaikan 45 peta per jam.", help_badge_12 = "Pemain ini memiliki rekor menyelesaikan 50 peta per jam.", help_badge_13 = "Pemain ini memiliki rekor menyelesaikan 55 peta per jam.", help_badge_14 = "Pemain ini telah memverifikasi akun mereka di server discord resmi parkour (ketik <b>!discord</b>).", help_badge_15 = "Pemain ini menjadi yang tercepat pada 1 peta.", help_badge_16 = "Pemain ini menjadi yang tercepat pada 5 peta.", help_badge_17 = "Pemain ini menjadi yang tercepat pada 10 peta.", help_badge_18 = "Pemain ini menjadi yang tercepat pada 15 peta.", help_badge_19 = "Pemain ini menjadi yang tercepat pada 20 peta.", help_badge_20 = "Pemain ini menjadi yang tercepat pada 25 peta.", help_badge_21 = "Pemain ini menjadi yang tercepat pada 30 peta.", help_badge_22 = "Pemain ini menjadi yang tercepat pada 35 peta.", help_badge_23 = "Pemain ini menjadi yang tercepat pada 40 peta.", make_public = "publikasikan", make_private = "privasikan", moderators = "Moderator", mappers = "Mappers", managers = "Manager", administrators = "Admin", close = "Tutup", cant_load_bot_profile = "<v>[#] <r>Anda tidak bisa melihat profil bot ketika #parkour menggunakan-nya secara internal untuk bekerja lebih baik.", cant_load_profile = "<v>[#] <r>Pemain <b>%s</b> sepertinya sedang offline atau nama pemain ini tidak tersedia.", like_map = "Apakah anda menyukai peta ini?", yes = "Ya", no = "Tidak", idk = "Tidak tahu", unknown = "Tidak diketahui", powers = "Kemampuan", press = "<vp>Tekan %s", click = "<vp>Klik kiri", ranking_pos = "Peringkat #%s", completed_maps = "<p align='center'><BV><B>Peta diselesaikan: %s</B></p></BV>", leaderboard = "Papan Peringkat", position = "Peringkat", username = "Nama panggilan", community = "Komunitas", completed = "Peta diselesaikan", overall_lb = "Keseluruhan", weekly_lb = "Mingguan", new_lang = "<v>[#] <d>Bahasa telah diubah ke Bahasa Indonesia", -- Power names balloon = "Balon", masterBalloon = "Master Balon", bubble = "Gelembung", fly = "Terbang", snowball = "Bola Salju", speed = "Speed", teleport = "Teleportasi", smallbox = "Kotak Kecil", cloud = "Awan", rip = "Batu Nisan", choco = "Papan Cokelat", bigBox = "Kotak besar", trampoline = "Trampolin", toilet = "Toilet", pig = "Babi", sink = "Wastafel", bathtub = "Bak Mandi", campfire = "Api Unggun", chair = "Kursi", }
------------------------------------------------------------------------------- -- Mob Framework Mod by Sapier -- -- You may copy, use, modify or do nearly anything except removing this -- copyright notice. -- And of course you are NOT allow to pretend you have written it. -- --! @file main_follow.lua --! @brief component containing a movement generator based uppon jordan4ibanez code --! @copyright Sapier --! @author Sapier --! @date 2012-08-09 -- --! @defgroup mgen_jordan4ibanez MGEN: a velocity based movement generator --! @brief A movement generator creating simple random movement --! @ingroup framework_int --! @{ -- Contact sapier a t gmx net ------------------------------------------------------------------------------- --! @class mgen_jordan4ibanez --! @brief a movement generator trying to follow or reach a target --!@} mgen_jordan4ibanez = {} --! @brief chillaxin_speed --! @memberof mgen_jordan4ibanez mgen_jordan4ibanez.chillaxin_speed = 0.1 --! @brief movement generator identifier --! @memberof mgen_jordan4ibanez mgen_jordan4ibanez.name = "jordan4ibanez_mov_gen" ------------------------------------------------------------------------------- -- name: callback(entity,now) -- --! @brief main callback to make a mob follow its target --! @memberof mgen_jordan4ibanez -- --! @param entity mob to generate movement for --! @param now current time ------------------------------------------------------------------------------- function mgen_jordan4ibanez.callback(entity,now) --update timers entity.dynamic_data.movement.timer = entity.dynamic_data.movement.timer + 0.01 entity.dynamic_data.movement.turn_timer = entity.dynamic_data.movement.turn_timer + 0.01 entity.dynamic_data.movement.jump_timer = entity.dynamic_data.movement.jump_timer + 0.01 entity.dynamic_data.movement.door_timer = entity.dynamic_data.movement.door_timer + 0.01 if entity.dynamic_data.movement.direction ~= nil then entity.object:setvelocity({x=entity.dynamic_data.movement.direction.x*mgen_jordan4ibanez.chillaxin_speed, y=entity.object:getvelocity().y, z=entity.dynamic_data.movement.direction.z*mgen_jordan4ibanez.chillaxin_speed}) end if entity.dynamic_data.movement.turn_timer > math.random(1,4) then entity.dynamic_data.movement.yaw = 360 * math.random() graphics.setyaw(entity, entity.dynamic_data.movement.yaw) entity.dynamic_data.movement.turn_timer = 0 entity.dynamic_data.movement.direction = {x = math.sin(entity.dynamic_data.movement.yaw)*-1, y = -10, z = math.cos(entity.dynamic_data.movement.yaw)} --entity.object:setvelocity({x=entity.dynamic_data.movement.direction.x,y=entity.object:getvelocity().y,z=entity.dynamic_data.movement.direction.z}) --entity.object:setacceleration(entity.dynamic_data.movement.direction) end --TODO update animation --open a door [alpha] if entity.dynamic_data.movement.direction ~= nil then if entity.dynamic_data.movement.door_timer > 2 then local is_a_door = minetest.get_node({x=entity.object:getpos().x + entity.dynamic_data.movement.direction.x, y=entity.object:getpos().y,z=entity.object:getpos(). z + entity.dynamic_data.movement.direction.z}).name if is_a_door == "doors:door_wood_t_1" then minetest.punch_node({x=entity.object:getpos().x + entity.dynamic_data.movement.direction.x, y=entity.object:getpos().y-1, z=entity.object:getpos().z + entity.dynamic_data.movement.direction.z}) entity.dynamic_data.movement.door_timer = 0 end local is_in_door = minetest.get_node(entity.object:getpos()).name if is_in_door == "doors:door_wood_t_1" then minetest.punch_node(entity.object:getpos()) end end end --jump if entity.dynamic_data.movement.direction ~= nil then if entity.dynamic_data.movement.jump_timer > 0.3 then if minetest.registered_nodes[minetest.get_node({x=entity.object:getpos().x + entity.dynamic_data.movement.direction.x, y=entity.object:getpos().y-1, z=entity.object:getpos().z + entity.dynamic_data.movement.direction.z}).name].walkable then entity.object:setvelocity({x=entity.object:getvelocity().x,y=5,z=entity.object:getvelocity().z}) entity.dynamic_data.movement.jump_timer = 0 end end end end ------------------------------------------------------------------------------- -- name: initialize() -- --! @brief initialize movement generator --! @memberof mgen_jordan4ibanez --! @public ------------------------------------------------------------------------------- function mgen_jordan4ibanez.initialize(entity,now) --intentionaly doing nothing this function is for symmetry reasons only end ------------------------------------------------------------------------------- -- name: init_dynamic_data(entity,now) -- --! @brief initialize dynamic data required by movement generator --! @memberof mgen_jordan4ibanez --! @public -- --! @param entity mob to initialize dynamic data --! @param now current time ------------------------------------------------------------------------------- function mgen_jordan4ibanez.init_dynamic_data(entity,now) local data = { timer = 0, turn_timer = 0, jump_timer = 0, door_timer = 0, direction = nil, yaw = nil, } entity.dynamic_data.movement = data end ------------------------------------------------------------------------------- -- name: set_target(entity, target, follow_speedup, max_distance) -- --! @brief set target for movgen --! @memberof mgen_jordan4ibanez -- --! @param entity mob to apply to --unused here --! @param target to set --unused here --! @param follow_speedup --unused here --! @param max_distance --unused here ------------------------------------------------------------------------------- function mgen_jordan4ibanez.set_target(entity,target) return false end --register this movement generator registerMovementGen(mgen_jordan4ibanez.name,mgen_jordan4ibanez)
-- Usage: -- local mastNames = require '__radio__/mast_names' if _G.stations then return end _G.stations = { 'Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'X-ray', 'Yankee', 'Zulu' }
data:extend({ { type = "recipe", name = "processed-sand", enabled = "false", ingredients = { {"unprocessed-sand",1}, {"stone-brick",1}, }, result = "processed-sand" }, })
--[[ bbbbbbbb b::::::b kkkkkkkk hhhhhhh b::::::b k::::::k h:::::h b::::::b k::::::k h:::::h b:::::b k::::::k h:::::h b:::::bbbbbbbbb aaaaaaaaaaaaa k:::::k kkkkkkkaaaaaaaaaaaaa h::::h hhhhh aaaaaaaaaaaaa xxxxxxx xxxxxxxxxxxxxx xxxxxxx b::::::::::::::bb a::::::::::::a k:::::k k:::::k a::::::::::::a h::::hh:::::hhh a::::::::::::a x:::::x x:::::x x:::::x x:::::x b::::::::::::::::b aaaaaaaaa:::::a k:::::k k:::::k aaaaaaaaa:::::a h::::::::::::::hh aaaaaaaaa:::::a x:::::x x:::::x x:::::x x:::::x b:::::bbbbb:::::::b a::::a k:::::k k:::::k a::::a h:::::::hhh::::::h a::::a x:::::xx:::::x x:::::xx:::::x b:::::b b::::::b aaaaaaa:::::a k::::::k:::::k aaaaaaa:::::a h::::::h h::::::h aaaaaaa:::::a x::::::::::x x::::::::::x b:::::b b:::::b aa::::::::::::a k:::::::::::k aa::::::::::::a h:::::h h:::::h aa::::::::::::a x::::::::x x::::::::x b:::::b b:::::b a::::aaaa::::::a k:::::::::::k a::::aaaa::::::a h:::::h h:::::h a::::aaaa::::::a x::::::::x x::::::::x b:::::b b:::::ba::::a a:::::a k::::::k:::::k a::::a a:::::a h:::::h h:::::ha::::a a:::::a x::::::::::x x::::::::::x b:::::bbbbbb::::::ba::::a a:::::a k::::::k k:::::k a::::a a:::::a h:::::h h:::::ha::::a a:::::a x:::::xx:::::x x:::::xx:::::x b::::::::::::::::b a:::::aaaa::::::a k::::::k k:::::ka:::::aaaa::::::a h:::::h h:::::ha:::::aaaa::::::a x:::::x x:::::x x:::::x x:::::x b:::::::::::::::b a::::::::::aa:::ak::::::k k:::::ka::::::::::aa:::ah:::::h h:::::h a::::::::::aa:::a x:::::x x:::::x x:::::x x:::::x bbbbbbbbbbbbbbbb aaaaaaaaaa aaaakkkkkkkk kkkkkkkaaaaaaaaaa aaaahhhhhhh hhhhhhh aaaaaaaaaa aaaaxxxxxxx xxxxxxxxxxxxxx xxxxxxx --]] -- haha look at my messy code local a=nil;local b=" v1.0"function Arrest(c)local d=game:GetService("Workspace")[c].HumanoidRootPart;local e=game:GetService("Workspace").Remote.arrest;e:InvokeServer(d)end;rconsoleprint("@@RED@@")rconsoleprint[[ 88 88 88 88 88 88 88 88 88 88,dPPYba, ,adPPYYba, 88 ,d8 ,adPPYYba, 88,dPPYba, ,adPPYYba, 8b, ,d8 8b, ,d8 88P' "8a "" `Y8 88 ,a8" "" `Y8 88P' "8a "" `Y8 `Y8, ,8P' `Y8, ,8P' 88 d8 ,adPPPPP88 8888[ ,adPPPPP88 88 88 ,adPPPPP88 )888( )888( 88b, ,a8" 88, ,88 88`"Yba, 88, ,88 88 88 88, ,88 ,d8" "8b, ,d8" "8b, 8Y"Ybbd8"' `"8bbdP"Y8 88 `Y8a `"8bbdP"Y8 88 88 `"8bbdP"Y8 8P' `Y8 8P' `Y8 ]]if game.GameId==73885730 then rconsoleprint("@@LIGHT_BLUE@@")rconsoleprint("Prison Life")rconsoleprint("\n")rconsolename("bakahaxx"..b)a="prison_life"else rconsoleprint("\nGame is unsupported!")rconsoleprint("\n")a="universal"rconsolename("bakahaxx"..b)end;while a=="prison_life"do rconsoleprint("@@WHITE@@")rconsoleprint("> ")local f=rconsoleinput("")local g=f:split(" ")if f=="arrest all"then local h=game.Players.LocalPlayer;local i=h.Character.HumanoidRootPart.CFrame;for j,k in pairs(game.Teams.Criminals:GetPlayers())do if k.Name~=h.Name then local j=10;repeat wait()j=j-1;game.Workspace.Remote.arrest:InvokeServer(k.Character.HumanoidRootPart)h.Character.HumanoidRootPart.CFrame=k.Character.HumanoidRootPart.CFrame*CFrame.new(0,0,1)until j==0;rconsoleinfo(game:GetService("Lighting").TimeOfDay..": "..k.Name.." was arrested.")end end;h.Character.HumanoidRootPart.CFrame=i elseif f=="superpunch"then mainRemotes=game.ReplicatedStorage;meleeRemote=mainRemotes["meleeEvent"]mouse=game.Players.LocalPlayer:GetMouse()punching=false;cooldown=false;function punch()cooldown=true;local l=Instance.new("Part",game.Players.LocalPlayer.Character)l.Transparency=1;l.Size=Vector3.new(5,2,3)l.CanCollide=false;local m=Instance.new("Weld",l)m.Part0=game.Players.LocalPlayer.Character.Torso;m.Part1=l;m.C1=CFrame.new(0,0,2)l.Touched:connect(function(n)if game.Players:FindFirstChild(n.Parent.Name)then local o=game.Players:FindFirstChild(n.Parent.Name)if o.Name~=game.Players.LocalPlayer.Name then l:Destroy()for j=1,100 do meleeRemote:FireServer(o)end end end end)wait(1)cooldown=false;l:Destroy()end;mouse.KeyDown:connect(function(p)if cooldown==false then if p:lower()=="f"then punch()end end end)rconsolewarn("Super punch enabled")elseif f=="removewalls"then wait(0.1)game.Workspace.Prison_Halls.walls:Remove()wait(0.1)game.Workspace.Prison_Halls.roof:Remove()wait(0.1)game.Workspace.Prison_Halls.outlines:Remove()wait(0.1)game.Workspace.Prison_Halls.lights:Remove()wait(0.1)Workspace.Prison_Halls.accent:Remove()wait(0.1)game.Workspace.Prison_Halls.glass:Remove()wait(0.1)game.Workspace.Prison_Cellblock.b_front:Remove()wait(0.1)game.Workspace.Prison_Cellblock.doors:Remove()wait(0.1)game.Workspace.Prison_Cellblock.c_tables:Remove()wait(0.1)game.Workspace.Prison_Cellblock.a_front:Remove()wait(0.1)game.Workspace.Prison_Cellblock.b_outerwall:Remove()wait(0.1)game.Workspace.Prison_Cellblock.c_wall:Remove()wait(0.1)game.Workspace.Prison_Cellblock.b_wall:Remove()wait(0.1)game.Workspace.Prison_Cellblock.c_hallwall:Remove()wait(0.1)game.Workspace.Prison_Cellblock.a_outerwall:Remove()wait(0.1)game.Workspace.Prison_Cellblock.b_ramp:Remove()wait(0.1)game.Workspace.Prison_Cellblock.a_ramp:Remove()wait(0.1)game.Workspace.Prison_Cellblock.a_walls:Remove()wait(0.1)game.Workspace.Prison_Cellblock.Cells_B:Remove()wait(0.1)game.Workspace.Prison_Cellblock.Cells_A:Remove()wait(0.1)game.Workspace.Prison_Cellblock.c_corner:Remove()wait(0.1)game.Workspace.Prison_Cellblock.Wedge:Remove()wait(0.1)game.Workspace.Prison_Cellblock.a_ceiling:Remove()wait(0.1)game.Workspace.Prison_Cellblock.b_ceiling:Remove()wait(0.1)game.Workspace.City_buildings:Remove()wait(0.1)game.Workspace.Prison_OuterWall:Remove()wait(0.1)game.Workspace.Prison_Fences:Remove()rconsoleinfo("Walls removed")rconsolewarn("DO NOT run the removewalls command again! If done so, the script will break!")elseif f=="m9"then local q=game:GetService("Workspace")["Prison_ITEMS"].giver.M9.ITEMPICKUP;local r=game:GetService("Workspace").Remote.ItemHandler;r:InvokeServer(q)rconsoleinfo("You were given an M9.")elseif f=="ak47"then local q=game:GetService("Workspace")["Prison_ITEMS"].giver["AK-47"].ITEMPICKUP;local r=game:GetService("Workspace").Remote.ItemHandler;r:InvokeServer(q)rconsoleinfo("You were given an AK47.")elseif f=="fly"or f=="Fly me"or f=="Fly"then repeat wait()until game.Players.LocalPlayer and game.Players.LocalPlayer.Character and game.Players.LocalPlayer.Character:findFirstChild("Torso")and game.Players.LocalPlayer.Character:findFirstChild("Humanoid")local mouse=game.Players.LocalPlayer:GetMouse()repeat wait()until mouse;local o=game.Players.LocalPlayer;local s=o.Character.Torso;local t=true;local u=true;local v={f=0,b=0,l=0,r=0}local w={f=0,b=0,l=0,r=0}local x=35;local y=35;function Fly()local z=Instance.new("BodyGyro",s)z.P=9e4;z.maxTorque=Vector3.new(9e9,9e9,9e9)z.cframe=s.CFrame;local A=Instance.new("BodyVelocity",s)A.velocity=Vector3.new(0,0.1,0)A.maxForce=Vector3.new(9e9,9e9,9e9)repeat wait()o.Character.Humanoid.PlatformStand=true;if v.l+v.r~=0 or v.f+v.b~=0 then y=y+.5+y/x;if y>x then y=x end elseif not(v.l+v.r~=0 or v.f+v.b~=0)and y~=0 then y=y-1;if y<0 then y=0 end end;if v.l+v.r~=0 or v.f+v.b~=0 then A.velocity=(game.Workspace.CurrentCamera.CoordinateFrame.lookVector*(v.f+v.b)+game.Workspace.CurrentCamera.CoordinateFrame*CFrame.new(v.l+v.r,(v.f+v.b)*.2,0).p-game.Workspace.CurrentCamera.CoordinateFrame.p)*y;w={f=v.f,b=v.b,l=v.l,r=v.r}elseif v.l+v.r==0 and v.f+v.b==0 and y~=0 then A.velocity=(game.Workspace.CurrentCamera.CoordinateFrame.lookVector*(w.f+w.b)+game.Workspace.CurrentCamera.CoordinateFrame*CFrame.new(w.l+w.r,(w.f+w.b)*.2,0).p-game.Workspace.CurrentCamera.CoordinateFrame.p)*y else A.velocity=Vector3.new(0,0.1,0)end;z.cframe=game.Workspace.CurrentCamera.CoordinateFrame*CFrame.Angles(-math.rad((v.f+v.b)*50*y/x),0,0)until not t;v={f=0,b=0,l=0,r=0}w={f=0,b=0,l=0,r=0}y=0;z:Destroy()A:Destroy()o.Character.Humanoid.PlatformStand=false end;mouse.KeyDown:connect(function(p)if p:lower()=="e"then if t then t=false else t=true;Fly()end elseif p:lower()=="w"then v.f=1 elseif p:lower()=="s"then v.b=-1 elseif p:lower()=="a"then v.l=-1 elseif p:lower()=="d"then v.r=1 end end)mouse.KeyUp:connect(function(p)if p:lower()=="w"then v.f=0 elseif p:lower()=="s"then v.b=0 elseif p:lower()=="a"then v.l=0 elseif p:lower()=="d"then v.r=0 end end)Fly()rconsoleinfo("Made "..game:GetService("Players").LocalPlayer.Name.." fly.")rconsoleinfo("Press E to toggle fly mode.")elseif f=="cmds"then rconsoleinfo[[ bakahaxx - Prison Life Commands [1] arrest all - Arrests all players. [2] superpunch - Become saitama. (Your punches instantly kill anyone) [3] removewalls - Remove the prison walls. [4] m9 - Gives you an M9. [5] ak47 - Gives you an AK-47. [6] fly - Makes you fly. Press E to toggle. [-] Yeah. There aren't that many commands. [+] I'm focusing on adding more to the commands menu, [+] and I'll a "help" command. It shows people cool things about bakahaxx. ]]else rconsoleerr("Invalid command!")end;while a=="universal"do game.Players.LocalPlayer:Kick("\nUniversal is being worked on!\nWe currently only support Prison Life.")end end
object_tangible_collection_reward_hanging_light_reward_02 = object_tangible_collection_reward_shared_hanging_light_reward_02:new { } ObjectTemplates:addTemplate(object_tangible_collection_reward_hanging_light_reward_02, "object/tangible/collection/reward/hanging_light_reward_02.iff")
if nil ~= require then require "wow/FontString"; require "wow/Frame-Container"; require "wow/Frame-Layer"; require "wow/Frame-Alpha"; require "fritomod/Functions"; require "fritomod/Lists"; require "fritomod/Ordering"; require "fritomod/Anchors"; require "fritomod/Tables"; require "fritomod/Frames"; require "fritomod/OOP-Class"; require "fritomod/Media-Color"; require "fritomod/Media-Font"; require "fritomod/Media-Texture"; end; UI = UI or {}; local Layered = OOP.Class("UI.Layered"); UI.Layered = Layered; local DRAW_LAYERS = { BACKGROUND = 0, BORDER = 1, ARTWORK = 2, OVERLAY = 3 -- We don't use highlight since it has special behaviors if -- mouse input is enabled. }; local REVERSED_DRAW_LAYERS = {}; for layer, offset in pairs(DRAW_LAYERS) do REVERSED_DRAW_LAYERS[offset] = layer; end; local SUBLEVELS = 16; function Layered:Constructor(parent, baseLayer) assert(type(baseLayer) == "string" or baseLayer == nil, "baseLayer must a string"); self.frame = Frames.New(parent); self:AddDestructor(Frames.Destroy, self.frame); baseLayer = baseLayer or "BACKGROUND"; baseLayer = baseLayer:upper(); assert(baseLayer ~= "HIGHLIGHT", "HIGHLIGHT base layer is not allowed"); self.baseLayer = DRAW_LAYERS[baseLayer]; assert(self.baseLayer ~= nil, "Unknown or invalid layer name: "..baseLayer); self.layers = {}; self.order = Ordering:New(); self:AddDestructor(self.order, "Destroy"); end; function Layered:AddTexture(name, ...) return self:Add(name, Frames.Texture(self, ...)); end; function Layered:AddColor(name, ...) return self:Add(name, Frames.Color(self, ...)); end; function Layered:AddText(name, ...) local element = Frames.Text(self, ...); Anchors.ShareAll(element); return self:Add(name, element); end; function Layered:Add(name, layer) self.order:Order(name); self.layers[name] = layer; self:Update(); return Functions.OnlyOnce(self, "Remove", name); end; function Layered:Get(name) return self.layers[name]; end; function Layered:Raise(name) self.order:Raise(name); self:Update(); end; function Layered:Lower(name) self.order:Lower(name); self:Update(); end; function Layered:Order(...) self.order:Order(...); self:Update(); end; function Layered:GetOrder() return Tables.Clone(self.order:Get()); end; local function ConvertToDrawLayer(count) local layer = math.floor(count / SUBLEVELS); local drawLayer = REVERSED_DRAW_LAYERS[layer]; local subLayer = count % SUBLEVELS - (SUBLEVELS / 2); assert(drawLayer ~= nil, "drawLayer was out of bounds: "..tostring(layer)); assert(subLayer >= -(SUBLEVELS / 2) and subLayer <= (SUBLEVELS / 2) - 1, "subLayer out of bounds: "..tostring(subLayer)); return drawLayer, subLayer; end; function Layered:Update() local count = self.baseLayer * SUBLEVELS; Lists.EachV(self.order:Get(), function(name) local layer = self.layers[name]; if layer then local l, sl = ConvertToDrawLayer(count); tracef("Layered - Name:%s Layer:%s Sublayer:%d", tostring(name), l, sl); layer:SetDrawLayer(l, sl); count = count + 1; end; end); end; function Layered:Remove(name) local layer = self.layers[name]; self.layers[name] = nil; if layer then Anchors.Clear(layer); self:Update(); return; end; end; function Layered:RemoveOrder(name) self:Remove(name); self.order:Remove(name); end;
function loadSAESModelsLua() local file = fileOpen("models_client.lua") local content = fileRead(file, fileGetSize(file)) fileClose(file) loadstring(content)() end function overwriteDownloadExport() exports.RPGfile = { downloadFile = function(this, filepath) return fileExists(filepath) end, } end function init() loadSAESModelsLua() overwriteDownloadExport() startModels() end init()
local format_identifier, identifier_pattern, escape, special_functions_names, pretty_signature, signature -- try to define an alias using rem, the text that follows the identifier -- returns true, new_rem, alias_name in case of success -- returns true, rem in case of no alias and no error -- returns nil, err in case of alias and error local function maybe_alias(rem, fqm, namespace, line, state) local alias if rem:match("^%:[^%:%=]") then local param_content = rem:sub(2) alias, rem = param_content:match("^("..identifier_pattern..")(.-)$") if not alias then return nil, ("expected an identifier in alias, but got %q; at %s"):format(param_content, line.source) end alias = format_identifier(alias) -- format alias local aliasfqm = ("%s%s"):format(namespace, alias) -- define alias if state.aliases[aliasfqm] ~= nil and state.aliases[aliasfqm] ~= fqm then return nil, ("trying to define alias %q for %q, but already exist and refer to %q; at %s"):format(aliasfqm, fqm, state.aliases[aliasfqm], line.source) end state.aliases[aliasfqm] = fqm end return true, rem, alias end -- * ast: if success -- * nil, error: in case of error local function parse_line(line, state, namespace) local l = line.content local r = { source = line.source } -- else-condition, condition & while if l:match("^~[~%?]?") then if l:match("^~~") then r.type = "else-condition" elseif l:match("^~%?") then r.type = "while" else r.type = "condition" end r.child = true local expr = l:match("^~[~%?]?(.*)$") if expr:match("[^%s]") then r.expression = expr else r.expression = "1" end -- choice elseif l:match("^>") then r.type = "choice" r.child = true r.text = l:match("^>%s*(.-)$") -- function & checkpoint elseif l:match("^%$") or l:match("^§") then -- § is a 2-bytes caracter, DO NOT USE LUA PATTERN OPERATORS as they operate on single bytes r.type = l:match("^%$") and "function" or "checkpoint" r.child = true -- store parent function and run checkpoint when line is read if r.type == "checkpoint" then r.parent_function = true end -- don't keep function node in block AST if r.type == "function" then r.remove_from_block_ast = true -- lua function if state.global_state.link_next_function_definition_to_lua_function then r.lua_function = state.global_state.link_next_function_definition_to_lua_function state.global_state.link_next_function_definition_to_lua_function = nil end end -- get identifier local lc = l:match("^%$(.-)$") or l:match("^§(.-)$") local identifier, rem = lc:match("^("..identifier_pattern..")(.-)$") if not identifier then for _, name in ipairs(special_functions_names) do identifier, rem = lc:match("^(%s*"..escape(name).."%s*)(.-)$") if identifier then break end end end if not identifier then return nil, ("no valid identifier in checkpoint/function definition line %q; at %s"):format(lc, line.source) end -- format identifier local fqm = ("%s%s"):format(namespace, format_identifier(identifier)) local func_namespace = fqm .. "." -- get alias local ok_alias ok_alias, rem = maybe_alias(rem, fqm, namespace, line, state) if not ok_alias then return ok_alias, rem end -- anything else are argument, isolate function it its own namespace -- (to not mix its args and variables with the main variant) if rem:match("[^%s]") then func_namespace = ("%s(%s)."):format(fqm, tostring(r)) r.private_namespace = true end -- define function if state.variables[fqm] then return nil, ("trying to define %s %s, but a variable with the same name exists; at %s"):format(r.type, fqm, line.source) end r.namespace = func_namespace r.name = fqm -- get params r.params = {} if r.type == "function" and rem:match("^%b()") then r.scoped = true local content content, rem = rem:match("^(%b())%s*(.*)$") content = content:gsub("^%(", ""):gsub("%)$", "") for param in content:gmatch("[^%,]+") do -- get identifier local param_identifier, param_rem = param:match("^("..identifier_pattern..")(.-)$") if not param_identifier then return nil, ("no valid identifier in function parameter %q; at %s"):format(param, line.source) end param_identifier = format_identifier(param_identifier) -- format identifier local param_fqm = ("%s%s"):format(func_namespace, param_identifier) -- get alias local ok_param_alias, param_alias ok_param_alias, param_rem, param_alias = maybe_alias(param_rem, param_fqm, func_namespace, line, state) if not ok_param_alias then return ok_param_alias, param_rem end -- get potential type annotation and default value local type_annotation, default if param_rem:match("^::") then type_annotation = param_rem:match("^::(.*)$") elseif param_rem:match("^=") then default = param_rem:match("^=(.*)$") elseif param_rem:match("[^%s]") then return nil, ("unexpected characters after parameter %q: %q; at %s"):format(param_fqm, param_rem, line.source) end -- add parameter table.insert(r.params, { name = param_identifier, alias = param_alias, full_name = param_fqm, type_annotation = type_annotation, default = default, vararg = nil }) end end -- get assignment param if r.type == "function" and rem:match("^%:%=") then local param = rem:match("^%:%=(.*)$") -- get identifier local param_identifier, param_rem = param:match("^("..identifier_pattern..")(.-)$") if not param_identifier then return nil, ("no valid identifier in function parameter %q; at %s"):format(param, line.source) end param_identifier = format_identifier(param_identifier) -- format identifier local param_fqm = ("%s%s"):format(func_namespace, param_identifier) -- get alias local ok_param_alias, param_alias ok_param_alias, param_rem, param_alias = maybe_alias(param_rem, param_fqm, func_namespace, line, state) if not ok_param_alias then return ok_param_alias, param_rem end -- get potential type annotation local type_annotation if param_rem:match("^::") then type_annotation = param_rem:match("^::(.*)$") elseif param_rem:match("[^%s]") then return nil, ("unexpected characters after parameter %q: %q; at %s"):format(param_fqm, param_rem, line.source) end -- add parameter r.assignment = { name = param_identifier, alias = param_alias, full_name = param_fqm, type_annotation = type_annotation, default = nil, vararg = nil } elseif rem:match("[^%s]") then return nil, ("expected end-of-line at end of checkpoint/function definition line, but got %q; at %s"):format(rem, line.source) end -- calculate arity local minarity, maxarity = #r.params, #r.params for _, param in ipairs(r.params) do -- params with default values if param.default then minarity = minarity - 1 end end -- varargs if maxarity > 0 and r.params[maxarity].full_name:match("%.%.%.$") then r.params[maxarity].name = r.params[maxarity].name:match("^(.*)%.%.%.$") r.params[maxarity].full_name = r.params[maxarity].full_name:match("^(.*)%.%.%.$") r.params[maxarity].vararg = true minarity = minarity - 1 maxarity = math.huge end r.arity = { minarity, maxarity } r.signature = signature(r) r.pretty_signature = pretty_signature(r) -- check for signature conflict with functions with the same fqm if state.functions[fqm] then for _, variant in ipairs(state.functions[fqm]) do if r.signature == variant.signature then return nil, ("trying to define %s %s, but another function with same signature %s exists; at %s"):format(r.type, r.pretty_signature, variant.pretty_signature, line.source) end end end -- define variables if not line.children then line.children = {} end -- define 👁️ variable local seen_alias = state.global_state.builtin_aliases["👁️"] if seen_alias then table.insert(line.children, 1, { content = (":👁️:%s=0"):format(seen_alias), source = line.source }) else table.insert(line.children, 1, { content = ":👁️=0", source = line.source }) end if r.type == "function" then -- define 🔖 variable local checkpoint_alias = state.global_state.builtin_aliases["🔖"] if checkpoint_alias then table.insert(line.children, 1, { content = (":🔖:%s=\"\""):format(checkpoint_alias), source = line.source }) else table.insert(line.children, 1, { content = ":🔖=\"\"", source = line.source }) end elseif r.type == "checkpoint" then -- define 🏁 variable local reached_alias = state.global_state.builtin_aliases["🏁"] if reached_alias then table.insert(line.children, 1, { content = (":🏁:%s=0"):format(reached_alias), source = line.source }) else table.insert(line.children, 1, { content = ":🏁=0", source = line.source }) end end -- define args for _, param in ipairs(r.params) do if not state.variables[param.full_name] then state.variables[param.full_name] = { type = "undefined argument", value = nil } else return nil, ("trying to define parameter %q, but a variable with the same name exists; at %s"):format(param.full_name, line.source) end end if r.assignment then if not state.variables[r.assignment.full_name] then state.variables[r.assignment.full_name] = { type = "undefined argument", value = nil } else return nil, ("trying to define parameter %q, but a variable with the same name exists; at %s"):format(r.assignment.full_name, line.source) end end -- define new function, no other variant yet if not state.functions[fqm] then state.functions[fqm] = { r } -- overloading else table.insert(state.functions[fqm], r) end -- definition elseif l:match("^:") then r.type = "definition" r.remove_from_block_ast = true -- get identifier local identifier, rem = l:match("^:("..identifier_pattern..")(.-)$") if not identifier then return nil, ("no valid identifier at start of definition line %q; at %s"):format(l, line.source) end -- format identifier local fqm = ("%s%s"):format(namespace, format_identifier(identifier)) -- get alias local ok_alias ok_alias, rem = maybe_alias(rem, fqm, namespace, line, state) if not ok_alias then return ok_alias, rem end -- get expression local exp = rem:match("^=(.*)$") if not exp then return nil, ("expected \"= expression\" after %q in definition line; at %s"):format(rem, line.source) end -- define identifier if state.functions[fqm] then return nil, ("trying to define variable %q, but a function with the same name exists; at %s"):format(fqm, line.source) end if state.variables[fqm] then return nil, ("trying to define variable %q but it is already defined; at %s"):format(fqm, line.source) end r.fqm = fqm r.expression = exp state.variables[fqm] = { type = "pending definition", value = { expression = nil, source = r.source } } -- tag elseif l:match("^%#") then r.type = "tag" r.child = true local expr = l:match("^%#(.*)$") if expr:match("[^%s]") then r.expression = expr else r.expression = "()" end -- return elseif l:match("^%@") then r.type = "return" r.parent_function = true local expr = l:match("^%@(.*)$") if expr:match("[^%s]") then r.expression = expr else r.expression = "()" end -- text elseif l:match("[^%s]") then r.type = "text" r.text = l -- flush events else r.type = "flush_events" end if not r.type then return nil, ("unknown line %s type"):format(line.source) end return r end -- * block: in case of success -- * nil, err: in case of error local function parse_block(indented, state, namespace, parent_function) local block = { type = "block" } for _, l in ipairs(indented) do -- parsable line local ast, err = parse_line(l, state, namespace) if err then return nil, err end -- store parent function if ast.parent_function then ast.parent_function = parent_function end -- add to block AST if not ast.remove_from_block_ast then ast.parent_block = block -- add ast node ast.parent_position = #block+1 table.insert(block, ast) end -- add child if ast.child then ast.child = { type = "block", parent_line = ast } end -- queue in expression evalution table.insert(state.queued_lines, { namespace = ast.namespace or namespace, line = ast }) -- indented block if l.children then if not ast.child then return nil, ("line %s (%s) can't have children"):format(ast.source, ast.type) else local r, e = parse_block(l.children, state, ast.namespace or namespace, ast.type == "function" and ast or parent_function) if not r then return r, e end r.parent_line = ast ast.child = r end end end return block end -- returns new_indented local function transform_indented(indented) local i = 1 while i <= #indented do local l = indented[i] -- comment if l.content:match("^%(") then table.remove(indented, i) else -- function decorator if l.content:match("^.-[^\\]%$"..identifier_pattern.."$") then local name l.content, name = l.content:match("^(.-[^\\])%$("..identifier_pattern..")$") indented[i] = { content = "~"..name, source = l.source } table.insert(indented, i+1, { content = "$"..name, source = l.source, children = { l } }) i = i + 1 -- $ line should not contain any decorator anymore else i = i + 1 -- only increment when no decorator, as there may be several decorators per line end -- indented block if l.children then transform_indented(l.children) end end end return indented end --- returns the nested list of lines {content="", line=1, children={lines...} or nil}, parsing indentation -- multiple empty lines are merged -- * list, last line, insert_empty_line: in case of success -- * nil, err: in case of error local function parse_indent(lines, source, i, indentLevel, insert_empty_line) i = i or 1 indentLevel = indentLevel or 0 local indented = {} while i <= #lines do if lines[i]:match("[^%s]") then local indent, line = lines[i]:match("^(%s*)(.*)$") if #indent == indentLevel then if insert_empty_line then table.insert(indented, { content = "", source = ("%s:%s"):format(source, insert_empty_line) }) insert_empty_line = false end table.insert(indented, { content = line, source = ("%s:%s"):format(source, i) }) elseif #indent > indentLevel then if #indented == 0 then return nil, ("unexpected indentation; at %s:%s"):format(source, i) else local t t, i, insert_empty_line = parse_indent(lines, source, i, #indent, insert_empty_line) if not t then return nil, i end indented[#indented].children = t end else return indented, i-1, insert_empty_line end elseif not insert_empty_line then insert_empty_line = i end i = i + 1 end return indented, i-1, insert_empty_line end --- return the list of raw lines of s local function parse_lines(s) local lines = {} for l in (s.."\n"):gmatch("(.-)\n") do table.insert(lines, l) end return lines end --- preparse shit: create AST structure, define variables and functions, but don't parse expression or perform any type checking -- (wait for other files to be parsed before doing this with postparse) -- * block: in case of success -- * nil, err: in case of error local function parse(state, s, name, source) -- parse lines local lines = parse_lines(s) local indented, e = parse_indent(lines, source or name) if not indented then return nil, e end -- wrap in named function if neccessary if name ~= "" then if not name:match("^"..identifier_pattern.."$") then return nil, ("invalid function name %q"):format(name) end indented = { { content = "$ "..name, source = ("%s:%s"):format(source or name, 0), children = indented }, } end -- transform ast indented = transform_indented(indented) -- build state proxy local state_proxy = { aliases = setmetatable({}, { __index = state.aliases }), variables = setmetatable({}, { __index = state.aliases }), functions = setmetatable({}, { __index = function(self, key) if state.functions[key] then local t = {} -- need to copy to allow ipairs over variants for k, v in ipairs(state.functions[key]) do t[k] = v end self[key] = t return t end return nil end }), queued_lines = {}, global_state = state } -- parse local root, err = parse_block(indented, state_proxy, "") if not root then return nil, err end -- merge back state proxy into global state for k,v in pairs(state_proxy.aliases) do state.aliases[k] = v end for k,v in pairs(state_proxy.variables) do state.variables[k] = v end for k,v in pairs(state_proxy.functions) do if not state.functions[k] then state.functions[k] = v else for i,w in ipairs(v) do state.functions[k][i] = w end end end for _,l in ipairs(state_proxy.queued_lines) do table.insert(state.queued_lines, l) end -- return block return root end package.loaded[...] = parse local common = require((...):gsub("preparser$", "common")) format_identifier, identifier_pattern, escape, special_functions_names, pretty_signature, signature = common.format_identifier, common.identifier_pattern, common.escape, common.special_functions_names, common.pretty_signature, common.signature return parse
local F, C = unpack(select(2, ...)) local ACTIONBAR = F:GetModule('Actionbar') ACTIONBAR.fader = { fadeInAlpha = 1, fadeInDuration = 0.3, fadeInSmooth = 'OUT', fadeOutAlpha = 0, fadeOutDuration = 0.9, fadeOutSmooth = 'OUT', fadeOutDelay = 0, } ACTIONBAR.faderOnShow = { fadeInAlpha = 1, fadeInDuration = 0.3, fadeInSmooth = 'OUT', fadeOutAlpha = 0, fadeOutDuration = 0.9, fadeOutSmooth = 'OUT', fadeOutDelay = 0, trigger = 'OnShow', } local function FaderOnFinished(self) self.__owner:SetAlpha(self.finAlpha) end local function FaderOnUpdate(self) self.__owner:SetAlpha(self.__animFrame:GetAlpha()) end local function CreateFaderAnimation(frame) if frame.fader then return end local animFrame = CreateFrame('Frame', nil, frame) animFrame.__owner = frame frame.fader = animFrame:CreateAnimationGroup() frame.fader.__owner = frame frame.fader.__animFrame = animFrame frame.fader.direction = nil frame.fader.setToFinalAlpha = false --test if this will NOT apply the alpha to all regions frame.fader.anim = frame.fader:CreateAnimation('Alpha') frame.fader:HookScript('OnFinished', FaderOnFinished) frame.fader:HookScript('OnUpdate', FaderOnUpdate) end local function StartFadeIn(frame) if frame.fader.direction == 'in' then return end frame.fader:Pause() frame.fader.anim:SetFromAlpha(frame.faderConfig.fadeOutAlpha or 0) frame.fader.anim:SetToAlpha(frame.faderConfig.fadeInAlpha or 1) frame.fader.anim:SetDuration(frame.faderConfig.fadeInDuration or 0.3) frame.fader.anim:SetSmoothing(frame.faderConfig.fadeInSmooth or 'OUT') --start right away frame.fader.anim:SetStartDelay(frame.faderConfig.fadeInDelay or 0) frame.fader.finAlpha = frame.faderConfig.fadeInAlpha frame.fader.direction = 'in' frame.fader:Play() end local function StartFadeOut(frame) if frame.fader.direction == 'out' then return end frame.fader:Pause() frame.fader.anim:SetFromAlpha(frame.faderConfig.fadeInAlpha or 1) frame.fader.anim:SetToAlpha(frame.faderConfig.fadeOutAlpha or 0) frame.fader.anim:SetDuration(frame.faderConfig.fadeOutDuration or 0.3) frame.fader.anim:SetSmoothing(frame.faderConfig.fadeOutSmooth or 'OUT') --wait for some time before starting the fadeout frame.fader.anim:SetStartDelay(frame.faderConfig.fadeOutDelay or 0) frame.fader.finAlpha = frame.faderConfig.fadeOutAlpha frame.fader.direction = 'out' frame.fader:Play() end local function IsMouseOverFrame(frame) if MouseIsOver(frame) then return true end return false end local function FrameHandler(frame) if IsMouseOverFrame(frame) then StartFadeIn(frame) else StartFadeOut(frame) end end local function OffFrameHandler(self) if not self.__faderParent then return end FrameHandler(self.__faderParent) end local function OnShow(self) if self.fader then StartFadeIn(self) end end local function OnHide(self) if self.fader then StartFadeOut(self) end end local function CreateFrameFader(frame, faderConfig) if frame.faderConfig then return end frame.faderConfig = faderConfig CreateFaderAnimation(frame) if faderConfig.trigger and faderConfig.trigger == 'OnShow' then frame:HookScript('OnShow', OnShow) frame:HookScript('OnHide', OnHide) else frame:EnableMouse(true) frame:HookScript('OnEnter', FrameHandler) frame:HookScript('OnLeave', FrameHandler) FrameHandler(frame) end end function ACTIONBAR:CreateButtonFrameFader(buttonList, faderConfig) CreateFrameFader(self, faderConfig) if faderConfig.trigger and faderConfig.trigger == 'OnShow' then return end for _, button in next, buttonList do if not button.__faderParent then button.__faderParent = self button:HookScript('OnEnter', OffFrameHandler) button:HookScript('OnLeave', OffFrameHandler) end end end -- fix blizzard cooldown flash local function FixCooldownFlash(self) if not self then return end if self:GetEffectiveAlpha() > 0 then self:Show() else self:Hide() end end hooksecurefunc(getmetatable(ActionButton1Cooldown).__index, 'SetCooldown', FixCooldownFlash)
local localization = { mod_description = { en = "Open window with F2 to paste and execute Lua code in." }, } return localization
local housing_libs = {} local MESSAGE_ENTITY_SET_TO_INACTIVE = { "description.entity_set_to_inactive" } local entity_cost = {} ---- base -------------------------------------------------------------------- entity_cost["inserter"] = 0.1 entity_cost["fast-inserter"] = 0.1 entity_cost["filter-inserter"] = 0.1 entity_cost["long-handed-inserter"] = 0.1 entity_cost["burner-inserter"] = 0.1 entity_cost["stack-inserter"] = 0.1 entity_cost["stack-filter-inserter"] = 0.1 -- furnace entity_cost["stone-furnace"] = 1 entity_cost["electric-furnace"] = 2 entity_cost["steel-furnace"] = 3 -- transport-belt entity_cost["transport-belt"] = 0.1 entity_cost["fast-transport-belt"] = 0.1 entity_cost["express-transport-belt"] = 0.1 entity_cost["boiler"] = 0.25 entity_cost["steam-engine"] = 0.025 entity_cost["steam-turbine"] = 1 entity_cost["heat-exchanger"] = 0.1 entity_cost["reactor"] = 10 entity_cost["burner-generator"] = 0.5 entity_cost["offshore-pump"] = 0.5 entity_cost["radar"] = 1 entity_cost["assembling-machine-1"] = 1 entity_cost["assembling-machine-2"] = 2 entity_cost["assembling-machine-3"] = 3 entity_cost["oil-refinery"] = 5 entity_cost["chemical-plant"] = 5 entity_cost["centrifuge"] = 8 entity_cost["lab"] = 1 entity_cost["splitter"] = 0.1 entity_cost["fast-splitter"] = 0.1 entity_cost["express-splitter"] = 0.1 entity_cost["underground-belt"] = 0.1 entity_cost["fast-underground-belt"] = 0.1 entity_cost["express-underground-belt"] = 0.1 -- entity_cost["solar-panel"] = 0.5 entity_cost["loader"] = 0.1 entity_cost["loader-1x1"] = 0.1 entity_cost["fast-loader"] = 0.1 entity_cost["express-loader"] = 0.1 entity_cost["car"] = 1 entity_cost["tank"] = 2 entity_cost["spidertron"] = 4 entity_cost["locomotive"] = 1 entity_cost["cargo-wagon"] = 0.25 entity_cost["fluid-wagon"] = 0.25 entity_cost["artillery-wagon"] = 0.5 entity_cost["rocket-silo"] = 10 entity_cost["roboport"] = 2 entity_cost["pump"] = 0.1 entity_cost["market"] = 0.1 entity_cost["beacon"] = 1 --- COLONISTS ---------------------------------------------- entity_cost["colonists-inserter"] = 0.1 entity_cost["colonists-assembling-machine"] = 0.5 entity_cost["colonists-mining-drill"] = 0.5 entity_cost["colonists-lab"] = 0.5 entity_cost["colonists-reverse-factory"] = 0.5 entity_cost["colonists-splitter"] = 0.1 entity_cost["colonists-workshop-beacon-1"] = 1 entity_cost["colonists-workshop-beacon-2"] = 2 entity_cost["colonists-workshop-beacon-3"] = 3 -- entity_cost["colonists-heat-generator"] = 0.2 -- entity_cost["colonists-electric-heat-generator"] = 0.2 entity_cost["colonists-generator"] = 0.2 entity_cost["colonists-workshop-beacon-3"] = 3 --- REVERSE FACTORY ---------------------------------------------- entity_cost["reverse-factory-1"] = 1 entity_cost["reverse-factory-2"] = 2 entity_cost["reverse-factory-3"] = 3 entity_cost["reverse-factory-4"] = 4 -- FOOD INDUSTRY --------------------------------------------------- entity_cost["fi-basic-farmland"] = 1 entity_cost["fi-greenhouse"] = 1 entity_cost["fi-big-greenhouse"] = 2 entity_cost["fi-incubator"] = 1 entity_cost["fi-composter"] = 0.5 entity_cost["fi-electric-composter"] = 1 entity_cost["burner-cooker"] = 0.5 entity_cost["electric-cooker"] = 0.5 entity_cost["cattle-grabber"] = 0.1 entity_cost["cattle-spawner"] = 1 entity_cost["cattle-butcher"] = 1 entity_cost["fish-farm"] = 1 entity_cost["burner-fishing-inserter"] = 0.1 entity_cost["fishing-inserter"] = 0.1 entity_cost["sturgeon-farm"] = 1 entity_cost["burner-food-picker"] = 0.1 entity_cost["food-picker"] = 0.1 entity_cost["fi-hydroponics-building"] = 1 entity_cost["fi-tree-greenhouse"] = 1 local required_interfaces = { metatable = "table", new = "function", on_removed = "function", update = "function" } local add_housing_lib = function(entity_name, lib, parameters) for name, value_type in pairs(required_interfaces) do if not lib[name] or type(lib[name]) ~= value_type then error( "Trying to add lib without all required interfaces: " .. serpent.block( { entity_name = entity_name, missing_value_key = name, value_type = type(lib[name]), expected_type = value_type } ) ) end end housing_libs[entity_name] = {lib = lib, parameters = parameters } end add_housing_lib("colonists-housing-1", require("prototypes/housing/house_script"), { colonists = 4 }) add_housing_lib("colonists-housing-2", require("prototypes/housing/house_script"), { colonists = 8 }) add_housing_lib("colonists-housing-3", require("prototypes/housing/house_script"), { colonists = 16 }) local script_data = { housings = {}, update_buckets = {}, reset_to_be_taken_again = true, refresh_techs = true, update_rate = 60, forces = {} } local function get_force_data_by_force(force) local force_data = script_data.forces[force.index] if not force_data then force_data = { force = force, housings = {}, } script_data.forces[force.index] = force_data end return force_data end local function get_force_data(entity) return get_force_data_by_force(entity.force) end local function count_active_houses(force_data) local active_houses = 0 local ok_colonists = 0 local nok_colonists = 0 for i, h in pairs(force_data.housings) do active_houses = active_houses + 1 local ok, colonists = h:check_status() if ok then ok_colonists = ok_colonists + colonists else nok_colonists = nok_colonists + colonists end end return active_houses, ok_colonists, nok_colonists end local function update_working_colonists() for fi, force_data in pairs(script_data.forces) do local active_houses, ok_colonists, nok_colonists = count_active_houses(force_data) local surfaces = game.surfaces local total_cost = 0 for si, surface in pairs(surfaces) do local entities = surface.find_entities_filtered{ force = force_data.force } for _, entity in pairs(entities) do local amount = entity_cost[entity.name] if amount then total_cost = total_cost + amount entity.active = total_cost < ok_colonists local player = entity.last_user if player then if entity.active then player.remove_alert({ entity = entity, icon = { type = "item", name = "colonists-hungry" } }) else player.add_custom_alert(entity, { type = "item", name = "colonists-hungry" }, {"description.entity_set_to_inactive", entity.localised_name }, true) end end end end end end end local get_housing_by_index = function(index) return script_data.housings[index] end local get_housing = function(entity) return get_housing_by_index(tostring(entity.unit_number)) end local get_corpse_position = function(entity, corpse_offsets) local position = entity.position local direction = entity.direction local offset = corpse_offsets[direction] return {position.x + offset[1], position.y + offset[2]} end local big = math.huge local insert = table.insert local add_to_update_bucket = function(index) local best_bucket local best_count = big local buckets = script_data.update_buckets for k = 1, script_data.update_rate do local bucket_index = k % script_data.update_rate local bucket = buckets[bucket_index] if not bucket then bucket = {} buckets[bucket_index] = bucket best_bucket = bucket best_count = 0 break end local size = #bucket if size < best_count then best_bucket = bucket best_count = size end end best_bucket[best_count + 1] = index end local on_created_entity = function(event) local entity = event.entity or event.created_entity if not (entity and entity.valid) then return end local name = entity.name local housing_lib = housing_libs[name] if not housing_lib then return end local housing = housing_lib.lib.new(entity, housing_lib.parameters) script.register_on_entity_destroyed(entity) housing.surface_index = entity.surface.index script_data.housings[housing.index] = housing local force_data = get_force_data(entity) force_data.housings[housing.index] = housing add_to_update_bucket(housing.index) end local remove_housing = function(housing, event) -- local surface = housing.surface_index local index = housing.index -- local x, y = housing.node_position[1], housing.node_position[2] -- remove_housing_from_node(surface, x, y, index) script_data.housings[index] = nil local force_data = get_force_data(housing.entity) force_data.housings[housing.index] = nil housing:on_removed(event) end local on_entity_removed = function(event) local entity = event.entity if not (entity and entity.valid) then return end local housing = get_housing(entity) if housing then remove_housing(housing, event) end end local on_entity_destroyed = function(event) local unit_number = event.unit_number if not unit_number then return end local housing = get_housing_by_index(tostring(unit_number)) if housing then remove_housing(housing, event) end end local get_lib = function(housing) local name = housing.entity.name return housing_libs[name] end local load_housing = function(housing) local lib = get_lib(housing).lib if lib and lib.metatable then setmetatable(housing, lib.metatable) end end local update_housings = function(tick) local bucket_index = tick % script_data.update_rate local update_list = script_data.update_buckets[bucket_index] if not update_list then return end local housings = script_data.housings local k = 1 while true do local housing_index = update_list[k] if not housing_index then return end local housing = housings[housing_index] if not (housing and housing.entity.valid) then housings[housing_index] = nil local last = #update_list if k == last then update_list[k] = nil else update_list[k], update_list[last] = update_list[last], nil end else housing:update() k = k + 1 end end end local on_tick = function(event) if event.tick % script_data.update_rate == 0 then update_working_colonists(event.tick) end update_housings(event.tick) end local setup_lib_values = function() for k, lib in pairs(housing_libs) do lib.get_housing = get_housing_by_index end end local insert = table.insert local refresh_update_buckets = function() local count = 1 local interval = script_data.update_rate local buckets = {} for index, housing in pairs(script_data.housings) do local bucket_index = count % interval buckets[bucket_index] = buckets[bucket_index] or {} insert(buckets[bucket_index], index) count = count + 1 end script_data.update_buckets = buckets end local refresh_update_rate = function() local update_rate = settings.global["colonists-update-interval"].value if script_data.update_rate == update_rate then return end script_data.update_rate = update_rate refresh_update_buckets() --game.print(script_data.update_rate) end local on_runtime_mod_setting_changed = function(event) refresh_update_rate() end local OnPlayerCreated = function(event) local player = game.players[event.player_index] get_force_data_by_force(player.force) end local lib = {} lib.events = { [defines.events.on_built_entity] = on_created_entity, [defines.events.on_robot_built_entity] = on_created_entity, [defines.events.script_raised_built] = on_created_entity, [defines.events.script_raised_revive] = on_created_entity, [defines.events.on_entity_died] = on_entity_removed, [defines.events.on_robot_mined_entity] = on_entity_removed, [defines.events.script_raised_destroy] = on_entity_removed, [defines.events.on_player_mined_entity] = on_entity_removed, [defines.events.on_entity_destroyed] = on_entity_destroyed, [defines.events.on_tick] = on_tick, [defines.events.on_runtime_mod_setting_changed] = on_runtime_mod_setting_changed, [defines.events.on_player_created] = OnPlayerCreated, } lib.on_init = function() global.transport_housings = global.transport_housings or script_data setup_lib_values() refresh_update_rate() end lib.on_load = function() script_data = global.transport_housings or script_data setup_lib_values() for k, housing in pairs(script_data.housings) do load_housing(housing) end end lib.on_configuration_changed = function() global.transport_housings = global.transport_housings or script_data for k, housing in pairs(script_data.housings) do if not housing.entity.valid then script_data.housings[k] = nil else script.register_on_entity_destroyed(housing.entity) housing.surface_index = housing.entity.surface.index if housing.on_config_changed then housing:on_config_changed() end end end if not script_data.refresh_techs then script_data.refresh_techs = true for k, force in pairs(game.forces) do force.reset_technology_effects() end end refresh_update_rate() end lib.get_housing = function(entity) return script_data.housings[tostring(entity.unit_number)] end lib.get_housing_by_index = get_housing_by_index return lib
-- ============ -- STRING UTILS -- ============ -- Created by datwaft <github.com/datwaft> local M = require("bubbly.core.module").new("utils.string") -- Returns a titlecase version of the string -- e.g. hello world -> Hello World ---@param str string ---@return string function M.titlecase(str) if not str then return nil end if type(str) ~= "string" then return nil end local result = string.gsub(str, "(%a)([%w_']*)", function(first, rest) return first:upper() .. rest:lower() end) return result end -- Returns a list of strings as a result of splitting the original string by the delimiter ---@param str string ---@param delimiter string ---@return string[] function M.split(str, delimiter) if delimiter == nil then delimiter = "%s" end local result = {} for value in string.gmatch(str, "([^" .. delimiter .. "]+)") do result[#result + 1] = value end return result end return M
return { Name = "blink"; Aliases = {"b"}; Description = "Teleports you to where your mouse is hovering."; Group = "DefaultDebug"; Args = {}; Run = function(context) -- We implement this here because player position is owned by the client. -- No reason to bother the server for this! local mouse = context.Executor:GetMouse() local character = context.Executor.Character if not character then return "You don't have a character." end character:MoveTo(mouse.Hit.p) return "Blinked!" end }
if (SERVER) then AddCSLuaFile() end sound.Add({ name="weapon_kswep.single", volume=1.0, pitch={155,165}, sound="^weapons/sg550/sg550-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_law.single", volume=1.0, pitch={55,60}, sound="^weapons/357_fire2.wav", level=165, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_m4.single", volume=1.0, pitch={155,165}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_akm.single", volume=1.0, pitch={175,185}, sound="^weapons/ak47/ak47-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_ak74.single", volume=1.0, pitch={200,205}, sound="^weapons/ak47/ak47-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_glock19.single", volume=1.0, pitch={185,195}, sound="^weapons/glock/glock18-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_fiveseven.single", volume=1.0, pitch={125,135}, sound="^weapons/fiveseven/fiveseven-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_nagant.single", volume=1.0, pitch={145,155}, sound="^weapons/pistol/pistol_fire3.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p228.single", volume=1.0, pitch={185,195}, sound="^weapons/elite/elite-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_judge.single", volume=0.7, pitch={225,245}, sound="^weapons/deagle/deagle-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mac11.single", volume=1, pitch={225,235}, sound="^weapons/usp/usp_unsil-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p90.single", volume=1, pitch={245,255}, sound="^weapons/p90/p90-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p238.single", volume=1.0, pitch={185,195}, sound="^weapons/g3sg1/g3sg1-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mp5.single", volume=1.0, pitch={185,195}, sound="^weapons/mp5navy/mp5-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mp510.single", volume=1.0, pitch={175,185}, sound="^weapons/mp5navy/mp5-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswep_test.single762", volume=1.0, pitch={125,135}, sound="^weapons/g3sg1/g3sg1-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_awm.single", volume=1.0, pitch={195,205}, sound="^weapons/awp/awp1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_shotgun.single", volume=1.0, pitch={120,120}, sound="^weapons/shotgun/shotgun_fire6.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_ghostgun.single", volume=1.0, pitch={70,75}, sound="^weapons/awp/awp1.wav", level=160, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_j22.single", volume=1, pitch={245,255}, sound="^weapons/sg552/sg552-1.wav", level=135, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswep.singlesilenced", volume=1, pitch={245,255}, sound="^weapons/sg550/sg550-1.wav", level=120, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scout.single", volume=1.0, pitch={75,80}, sound="^weapons/scout/scout_fire-1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scout_556.single", volume=1.0, pitch={95,105}, sound="^weapons/scout/scout_fire-1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scar17.single", volume=1.0, pitch={125,135}, sound="^weapons/g3sg1/g3sg1-1.wav", level=160, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_usp45.single", volume=1.0, pitch={165,170}, sound="^weapons/usp/usp_unsil-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_usp45.single_sup", volume=0.7, pitch={205,210}, sound="^weapons/usp/usp_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_m4.single_sup", volume=1.0, pitch={195,205}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_300blk.single_sup", volume=0.6, pitch={185,190}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kgrent_flashbang.detonate", volume=1, pitch={195,205}, sound="^weapons/aug/aug-1.wav", level=145, channel=CHAN_WEAPON })
local M = {} ---@param config table The configuration object ---@return Theme Returns a theme object which can be given to --`require("nord.util").load` to load the theme. function M.setup(config) config = config or require("nord.config") ---@class Theme local theme = {} theme.config = config theme.colors = require("nord.colors") local c = theme.colors -- local variables to reduce the use of strings local strikethrough = "strikethrough," local inverse = "inverse," -- Config specific theme settings local bold = config.bold and "bold," or "" local italic = config.bold and "italic," or "" local underline = config.bold and "underline," or "" local italic_comments = {} if config.italic_comments then italic_comments = { Comment = { fg = c.nord3_bright, style = italic }, SpecialComment = { fg = c.nord8, style = italic }, } else italic_comments = { Comment = { fg = c.nord3_bright }, SpecialComment = { fg = c.nord8 }, } end local cursorline_number_background = {} if config.cursor_line_number_background then cursorline_number_background = { CursorLineNr = { fg = c.nord4, bg = c.nord1 }, } else cursorline_number_background = { CursorLineNr = { fg = c.nord4 } } end local uniform_status_lines = {} if config.uniform_status_lines then uniform_status_lines = { StatusLine = { fg = c.nord8, bg = c.nord3 }, StatusLineNC = { fg = c.nord4, bg = c.nord3 }, } else uniform_status_lines = { StatusLine = { fg = c.nord8, bg = c.nord3 }, StatusLineNC = { fg = c.nord4, bg = c.nord1 }, } end local bold_vertical_split_line = {} if config.bold_vertical_split_line then bold_vertical_split_line = { VertSplit = { fg = c.nord2, bg = c.nord1 } } else bold_vertical_split_line = { VertSplit = { fg = c.nord2, bg = c.nord0 } } end local uniform_diff_background = {} if config.uniform_diff_background then uniform_diff_background = { DiffAdd = { fg = c.add }, DiffChange = { fg = c.change }, DiffDelete = { fg = c.remove }, DiffText = { fg = c.nord9 }, } else uniform_diff_background = { DiffAdd = { fg = c.add, bg = c.nord0, style = inverse }, DiffChange = { fg = c.change, bg = c.nord0, style = inverse }, DiffDelete = { fg = c.remove, bg = c.nord0, style = inverse }, DiffText = { fg = c.nord9, bg = c.nord0, style = inverse }, } end theme.base = { -- Attributes Bold = { style = bold }, Italic = { style = italic }, Underline = { style = underline }, ColorColumn = { bg = c.nord1 }, -- used for the columns set with 'colorcolumn' Conceal = { bg = c.none }, -- placeholder characters substituted for concealed text (see 'conceallevel') Cursor = { fg = c.nord0, bg = c.nord4 }, -- character under the cursor lCursor = { link = "Cursor" }, -- the character under the cursor when |language-mapping| is used (see 'guicursor') CursorIM = { link = "Cursor" }, -- like Cursor, but used when in IME mode |CursorIM| CursorColumn = { bg = c.nord4 }, -- Screen-column at the cursor, when 'cursorcolumn' is set. CursorLine = { bg = c.nord1 }, -- Screen-line at the cursor, when 'cursorline' is set. Low-priority if foreground (ctermfg OR guifg) is not set. Directory = { fg = c.nord8 }, -- directory names (and other special names in listings) DiffAdd = uniform_diff_background.DiffAdd, -- diff mode: Added line |diff.txt| DiffChange = uniform_diff_background.DiffChange, -- diff mode: Changed line |diff.txt| DiffDelete = uniform_diff_background.DiffDelete, -- diff mode: Deleted line |diff.txt| DiffText = uniform_diff_background.DiffText, -- diff mode: Changed text within a changed line |diff.txt| EndOfBuffer = { fg = c.nord1 }, -- filler lines (~) after the end of the buffer. By default, this is highlighted like |hl-NonText|. TermCursor = { link = "Cursor" }, -- cursor in a focused terminal TermCursorNC = { bg = c.nord1 }, -- cursor in an unfocused terminal ErrorMsg = { fg = c.nord4, bg = c.error }, -- error messages on the command line VertSplit = bold_vertical_split_line.VertSplit, -- the column separating vertically split windows Folded = { fg = c.blue, bg = c.none }, -- line used for closed folds FoldColumn = { fg = c.nord3, bg = c.nord1 }, -- 'foldcolumn' SignColumn = { fg = c.nord1, bg = c.nord0 }, -- column where |signs| are displayed IncSearch = { fg = c.nord6, bg = c.nord10, style = underline }, -- 'incsearch' highlighting; also used for the text replaced with ":s///c" Substitute = { link = "IncSearch" }, -- |:substitute| replacement text highlighting LineNr = { fg = c.nord3 }, -- Line number for ":number" and ":#" commands, and when 'number' or 'relativenumber' option is set. CursorLineNr = cursorline_number_background.CursorLineNr, -- Like LineNr when 'cursorline' or 'relativenumber' is set for the cursor line. MatchParen = { fg = c.nord8, bg = c.nord3 }, -- The character under the cursor or just before it, if it is a paired bracket, and its match. |pi_paren.txt| ModeMsg = { fg = c.nord4 }, -- 'showmode' message (e.g., "-- INSERT -- ") MsgArea = { fg = c.nord4 }, -- Area for messages and cmdline -- MsgSeparator= { }, -- Separator for scrolled messages, `msgsep` flag of 'display' MoreMsg = { fg = c.nord8 }, -- |more-prompt| NonText = { fg = c.nord2 }, -- '@' at the end of the window, characters from 'showbreak' and other characters that do not really exist in the text (e.g., ">" displayed when a double-wide character doesn't fit at the end of the line). See also |hl-EndOfBuffer|. Normal = { fg = c.nord4, bg = c.nord0 }, -- normal text NormalFloat = { fg = c.nord4, bg = c.nord2 }, -- Normal text in floating windows. NormalNC = { link = "Normal" }, -- normal text in non-current windows Pmenu = { fg = c.nord4, bg = c.nord2 }, -- Popup menu: normal item. PmenuSel = { fg = c.nord8, bg = c.nord3 }, -- Popup menu: selected item. PmenuSbar = { fg = c.nord4, bg = c.nord2 }, -- Popup menu: scrollbar. PmenuThumb = { fg = c.nord8, bg = c.nord3 }, -- Popup menu: Thumb of the scrollbar. Question = { fg = c.nord4 }, -- |hit-enter| prompt and yes/no questions QuickFixLine = { link = "CursorLine" }, -- Current |quickfix| item in the quickfix window. Combined with |hl-CursorLine| when the cursor is there. Search = { fg = c.nord1, bg = c.nord8 }, -- Last search pattern highlighting (see 'hlsearch'). Also used for similar items that need to stand out. SpecialKey = { fg = c.nord3 }, -- Unprintable characters: text displayed differently from what it really is. But not 'listchars' whitespace. |hl-Whitespace| SpellBad = { fg = c.none, style = "undercurl", sp = c.nord11, }, -- Word that is not recognized by the spellchecker. |spell| Combined with the highlighting used otherwise. SpellCap = { fg = c.none, style = "undercurl", sp = c.nord13, }, -- Word that should start with a capital. |spell| Combined with the highlighting used otherwise. SpellLocal = { fg = c.none, style = "undercurl", sp = c.nord8, }, -- Word that is recognized by the spellchecker as one that is used in another region. |spell| Combined with the highlighting used otherwise. SpellRare = { fg = c.none, style = "undercurl", sp = c.nord7, }, -- Word that is recognized by the spellchecker as one that is hardly ever used. |spell| Combined with the highlighting used otherwise. StatusLine = uniform_status_lines.StatusLine, -- status line of current window StatusLineNC = uniform_status_lines.StatusLineNC, -- status lines of not-current windows Note: if this is equal to "StatusLine" Vim will use "^^^" in the status line of the current window. TabLine = { fg = c.nord3_bright, bg = c.nord1 }, -- tab pages line, not active tab page label TabLineFill = { fg = c.nord3, bg = c.nord0 }, -- tab pages line, where there are no labelsh TabLineSel = { fg = c.nord4, bg = c.nord0, style = bold .. italic }, -- tab pages line, active tab page label Title = { fg = c.nord4 }, -- titles for output from ":set all", ":autocmd" etc. Visual = { bg = c.nord2 }, -- Visual mode selection VisualNOS = { link = "Visual" }, -- Visual mode selection when vim is "Not Owning the Selection". WarningMsg = { fg = c.nord0, bg = c.nord13 }, -- warning messages Whitespace = { fg = c.nord2 }, -- "nbsp", "space", "tab" and "trail" in 'listchars' WildMenu = { fg = c.nord8, bg = c.nord1 }, -- current match in 'wildmenu' completion -- These groups are not listed as default vim groups, -- but they are defacto standard group names for syntax highlighting. -- commented out groups should chain up to their "preferred" group by -- default, -- Uncomment and edit if you want more specific syntax highlighting. Comment = italic_comments.Comment, -- any comment Constant = { fg = c.nord4 }, -- (preferred) any constant String = { fg = c.nord14 }, -- a string constant: "this is a string" Character = { fg = c.nord14 }, -- a character constant: 'c', '\n' Number = { fg = c.nord15 }, -- a number constant: 234, 0xff Boolean = { fg = c.nord9 }, -- a boolean constant: TRUE, false Float = { fg = c.nord15 }, -- a floating point constant: 2.3e10 Identifier = { fg = c.nord4 }, -- (preferred) any variable name Function = { fg = c.nord8 }, -- function name (also: methods for classes) Statement = { fg = c.nord9 }, -- (preferred) any statement Conditional = { fg = c.nord9 }, -- if, then, else, endif, switch, etc. Repeat = { fg = c.nord9 }, -- for, do, while, etc. Label = { fg = c.nord9 }, -- case, default, etc. Operator = { fg = c.nord9 }, -- "sizeof", "+", "*", etc. Keyword = { fg = c.nord9 }, -- any other keyword Exception = { fg = c.nord9 }, -- try, catch, throw PreProc = { fg = c.nord9 }, -- (preferred) generic Preprocessor Include = { fg = c.nord9 }, -- preprocessor #include Define = { fg = c.nord9 }, -- preprocessor #define Macro = { link = "Define" }, -- same as Define PreCondit = { link = "PreProc" }, -- preprocessor #if, #else, #endif, etc. Type = { fg = c.nord9 }, -- (preferred) int, long, char, etc. StorageClass = { fg = c.nord9 }, -- static, register, volatile, etc. Structure = { fg = c.nord9 }, -- struct, union, enum, etc. Typedef = { fg = c.nord9 }, -- A typedef Special = { fg = c.nord4 }, -- (preferred) any special symbol SpecialChar = { fg = c.nord13 }, -- special character in a constant Tag = { fg = c.nord4 }, -- you can use CTRL-] on this Delimiter = { fg = c.nord6 }, -- character that needs attention SpecialComment = italic_comments.SpecialComment, -- special things inside a comment Debug = { fg = c.nord15 }, -- debugging statements Underlined = { style = underline }, -- text that stands out, HTML links -- Ignore = {}, -- (preferred) left blank, hidden |hl-Ignore| Error = { fg = c.error }, -- (preferred) any erroneous construct Todo = { fg = c.warning }, -- (preferred) anything that needs extra attention; mostly the keywords TODO FIXME and XXX } theme.additional = { -- These groups are for the native LSP client. Some other LSP clients may -- use these groups, or use their own. Consult your LSP client's -- documentation. LspReferenceText = { bg = c.nord2 }, -- used for highlighting "text" references LspReferenceRead = { bg = c.nord2 }, -- used for highlighting "read" references LspReferenceWrite = { bg = c.nord2 }, -- used for highlighting "write" references DiagnosticError = { fg = c.error }, -- Used as the base highlight group. Other LspDiagnostic highlights link to this by default (except Underline) DiagnosticWarn = { fg = c.warning }, -- Used as the base highlight group. Other LspDiagnostic highlights link to this by default (except Underline) DiagnosticInfo = { fg = c.info }, -- Used as the base highlight group. Other LspDiagnostic highlights link to this by default (except Underline) DiagnosticHint = { fg = c.hint }, -- Used as the base highlight group. Other LspDiagnostic highlights link to this by default (except Underline) -- DiagnosticSignError = { }, -- Used for "Error" signs in sign column -- DiagnosticSignWarn = { }, -- Used for "Warning" signs in sign column -- DiagnosticSignInfo = { }, -- Used for "Information" signs in sign column -- DiagnosticSignHint = { }, -- Used for "Hint" signs in sign column -- -- DiagnosticFloatingError = { }, -- Used to color "Error" diagnostic messages in diagnostics float -- DiagnosticFloatingWarn = { }, -- Used to color "Warning" diagnostic messages in diagnostics float -- DiagnosticFloatingInfo = { }, -- Used to color "Information" diagnostic messages in diagnostics float -- DiagnosticFloatingHint = { }, -- Used to color "Hint" diagnostic messages in diagnostics float DiagnosticUnderlineError = { style = "undercurl", sp = c.error }, -- Used to underline "Error" diagnostics DiagnosticUnderlineWarn = { style = "undercurl", sp = c.warning }, -- Used to underline "Warning" diagnostics DiagnosticUnderlineInfo = { style = "undercurl", sp = c.info }, -- Used to underline "Information" diagnostics DiagnosticUnderlineHint = { style = "undercurl", sp = c.hint }, -- Used to underline "Hint" diagnostics -- DiagnosticVirtualTextError = {}, -- Used for "Error" diagnostic virtual text -- DiagnosticVirtualTextWarn = {}, -- Used for "Warning" diagnostic virtual text -- DiagnosticVirtualTextInfo = {}, -- Used for "Information" diagnostic virtual text -- DiagnosticVirtualTextHint = {}, -- Used for "Hint" diagnostic virtual text LspSignatureActiveParameter = { fg = c.nord12 }, LspCodeLens = { link = "Comment" }, } theme.languages = { asciidocAttributeEntry = { fg = c.nord10 }, asciidocAttributeList = { fg = c.nord10 }, asciidocAttributeRef = { fg = c.nord10 }, asciidocHLabel = { fg = c.nord9 }, asciidocListingBlock = { fg = c.nord7 }, asciidocMacroAttributes = { fg = c.nord8 }, asciidocOneLineTitle = { fg = c.nord8 }, asciidocPassthroughBlock = { fg = c.nord9 }, asciidocQuotedMonospaced = { fg = c.nord7 }, asciidocTriplePlusPassthrough = { fg = c.nord7 }, asciidocAdmonition = { link = "Keyword" }, asciidocAttributRef = { link = "markdownH1" }, asciidocBackslash = { link = "Keyword" }, asciidocMacro = { link = "Keyword" }, asciidocQuotedBold = { link = "Bold" }, asciidocQuotedEmphasized = { link = "Italic" }, asciidocQuotedQuotedMonospaced2 = { link = "asciidocQuotedMonospaced", }, asciidocQuotedUnconstrainedBold = { link = "asciidocBold", }, asciidocQuotedUnconstrainedEmphasized = { link = "markdownLinkText", }, asciidocURL = { link = "Keyword" }, awkCharClass = { fg = c.nord7 }, awkPatterns = { fg = c.nord9 }, awkArrayElement = { link = "Identifier" }, awkBoolLogic = { link = "Keyword" }, awkBrktRegExp = { link = "SpecialChar" }, awkComma = { link = "Delimiter" }, awkExpression = { link = "Keyword" }, awkFieldVars = { link = "Identifier" }, awkLineSkip = { link = "Keyword" }, awkOperator = { link = "Operator" }, awkRegExp = { link = "SpecialChar" }, awkSearch = { link = "Keyword" }, awkSemicolon = { link = "Delimiter" }, awkSpecialCharacter = { link = "SpecialChar" }, awkSpecialPrintf = { link = "SpecialChar" }, awkVariables = { link = "Identifier" }, cIncluded = { fg = c.nord7 }, cOperator = { link = "Operator" }, cPreCondit = { link = "PreCondit" }, cmakeGeneratorExpression = { fg = c.nord10 }, csPreCondit = { link = "PreCondit" }, csType = { link = "Type" }, csXmlTag = { link = "SpecialComment" }, cssAttributeSelector = { fg = c.nord7 }, cssDefinition = { fg = c.nord7 }, cssIdentifier = { fg = c.nord7 }, cssStringQ = { fg = c.nord7 }, cssAttr = { link = "Keyword" }, cssBraces = { link = "Delimiter" }, cssClassName = { link = "cssDefinition" }, cssColor = { link = "Number" }, cssProp = { link = "cssDefinition" }, cssPseudoClass = { link = "cssDefinition" }, cssPseudoClassId = { link = "cssPseudoClass" }, cssVendor = { link = "Keyword" }, dosinHeader = { fg = c.nord8 }, dosiniLabel = { link = "Type" }, dtBooleanKey = { fg = c.nord7 }, dtExecKey = { fg = c.nord7 }, dtLocaleKey = { fg = c.nord7 }, dtNumericKey = { fg = c.nord7 }, dtTypeKey = { fg = c.nord7 }, dtDelim = { link = "Delimiter" }, dtLocaleValue = { link = "Keyword" }, dtTypeValue = { link = "Keyword" }, diffAdded = { fg = c.add }, diffChanged = { fg = c.change }, diffRemoved = { fg = c.remove }, gitconfigVariable = { fg = c.nord7 }, goBuiltins = { fg = c.nord7 }, goConstants = { link = "Keyword" }, helpBar = { fg = c.nord3 }, helpHyperTextJump = { fg = c.nord8, style = underline }, htmlArg = { fg = c.nord7 }, htmlLink = { fg = c.nord4, style = c.none, ps = c.none }, htmlBold = { link = "Bold" }, htmlEndTag = { link = "htmlTag" }, htmlItalic = { link = "Italic" }, htmlH1 = { link = "markdownH1" }, htmlH2 = { link = "markdownH2" }, htmlH3 = { link = "markdownH3" }, htmlH4 = { link = "markdownH4" }, htmlH5 = { link = "markdownH5" }, htmlH6 = { link = "markdownH6" }, htmlSpecialChar = { link = "SpecialChar" }, htmlTag = { link = "Keyword" }, htmlTagN = { link = "htmlTag" }, javaDocTags = { fg = c.nord7 }, javaCommentTitle = { link = "Comment" }, javaScriptBraces = { link = "Delimiter" }, javaScriptIdentifier = { link = "Keyword" }, javaScriptNumber = { link = "Number" }, jsonKeyword = { fg = c.nord7 }, lessClass = { fg = c.nord7 }, lessAmpersand = { link = "Keyword" }, lessCssAttribute = { link = "Delimiter" }, lessFunction = { link = "Function" }, cssSelectorOp = { link = "Keyword" }, lispAtomBarSymbol = { link = "SpecialChar" }, lispAtomList = { link = "SpecialChar" }, lispAtomMark = { link = "Keyword" }, lispBarSymbol = { link = "SpecialChar" }, lispFunc = { link = "Function" }, luaFunc = { link = "Function" }, markdownBlockquote = { fg = c.nord7 }, markdownCode = { fg = c.nord7 }, markdownCodeDelimiter = { fg = c.nord7 }, markdownFootnote = { fg = c.nord7 }, markdownId = { fg = c.nord7 }, markdownDeclaration = { fg = c.nord7 }, markdownLinkText = { fg = c.nord7 }, markdownUrl = { fg = c.nord7 }, markdownBold = { link = "Bold" }, markdownBoldDelimiter = { link = "Keyword" }, markdownFootnoteDefinition = { link = "markdownFootnote" }, markdownH1 = { fg = c.nord11 }, markdownH2 = { fg = c.nord12 }, markdownH3 = { fg = c.nord13 }, markdownH4 = { fg = c.nord14 }, markdownH5 = { fg = c.nord7 }, markdownH6 = { fg = c.nord9 }, markdownIdDelimiter = { link = "Keyword" }, markdownItalic = { link = "Italic" }, markdownItalicDelimiter = { link = "Keyword" }, markdownLinkDelimiter = { link = "Keyword" }, markdownLinkTextDelimiter = { link = "Keyword" }, markdownListMarker = { link = "Keyword" }, markdownRule = { link = "Keyword" }, markdownHeadingDelimiter = { link = "Keyword" }, perlPackageDecl = { fg = c.nord7 }, phpClasses = { fg = c.nord7 }, phpDocTags = { fg = c.nord7 }, phpDocCustomTags = { link = "phpDocTags" }, phpMemberSelector = { link = "Keyword" }, padCmdText = { fg = c.nord7 }, padVerbatimLine = { fg = c.nord4 }, podFormat = { link = "Keyword" }, pythonBuiltin = { link = "Type" }, pythonEscape = { link = "SpecialChar" }, rubyConstant = { fg = c.nord7 }, rubySymbol = { fg = c.nord6 }, rubyAttribute = { link = "Identifier" }, rubyBlockParameterList = { link = "Operator" }, rubyInterpolationDelimiter = { link = "Keyword" }, rubyKeywordAsMethod = { link = "Function" }, rubyLocalVariableOrMethod = { link = "Function" }, rubyPseudoVariable = { link = "Keyword" }, rubyRegexp = { link = "SpecialChar" }, rustAttribute = { fg = c.nord10 }, rustEnum = { fg = c.nord7 }, rustMacro = { fg = c.nord8 }, rustModPath = { fg = c.nord7 }, rustPanic = { fg = c.nord9 }, rustModTrait = { fg = c.nord7 }, rustCommentLineDoc = { link = "Comment" }, rustDerive = { link = "rustAttribute" }, rustEnumVariant = { link = "rustEnum" }, rustEscape = { link = "SpecialChar" }, rustQuestionMark = { link = "Keyword" }, sassClass = { fg = c.nord7 }, sassId = { fg = c.nord7 }, sassAmpersand = { link = "Keyword" }, sassClassChar = { link = "Delimiter" }, sassControl = { link = "Keyword" }, sassControlLine = { link = "Keyword" }, sassExtend = { link = "Keyword" }, sassFor = { link = "Keyword" }, sassFunctionDecl = { link = "Keyword" }, sassFunctionName = { link = "Function" }, sassidChar = { link = "sassId" }, sassInclude = { link = "SpecialChar" }, sassMixinName = { link = "Function" }, sassMixing = { link = "SpecialChar" }, sassReturn = { link = "Keyword" }, shCmdParenRegion = { link = "Delimiter" }, shCmdSubRegion = { link = "Delimiter" }, shDerefSimple = { link = "Identifier" }, shDerefVar = { link = "Identifier" }, sqlKeyword = { link = "Keyword" }, sqlSpecial = { link = "Keyword" }, vimAugroup = { fg = c.nord7 }, vimMapRhs = { fg = c.nord7 }, vimNotation = { fg = c.nord7 }, vimFunc = { link = "Function" }, vimFunction = { link = "Function" }, vimUserFunc = { link = "Function" }, xmlAttrib = { fg = c.nord7 }, xmlCdataStart = { fg = c.nord3 }, xmlNamespace = { fg = c.nord7 }, xmlAttribPunct = { link = "Delimiter" }, xmlCdata = { link = "Comment" }, xmlCdataCdata = { link = "xmlCdataStart" }, xmlCdataEnd = { link = "xmlCdataStart" }, xmlEndTag = { link = "xmlTagName" }, xmlProcessingDelim = { link = "Keyword" }, xmlTagName = { link = "Keyword" }, yamlBlockMappingKey = { fg = c.nord7 }, yamlBool = { link = "Keyword" }, yamlDocumentStart = { link = "Keyword" }, } theme.plugins = { -- Bufferline TabLineSelector = { fg = c.nord9 }, TabLineDuplicate = { fg = c.nord15 }, -- Dashboard DashboardShortCut = { fg = c.nord7 }, DashboardHeader = { fg = c.nord9 }, DashboardCenter = { fg = c.nord15 }, DashboardFooter = { fg = c.nord3_bright, style = italic }, -- Diff diffAdded = { link = "DiffAdd" }, diffChanged = { link = "DiffChange" }, diffRemoved = { link = "DiffRemove" }, diffOldFile = { fg = c.nord13 }, diffNewFile = { fg = c.nord12 }, diffFile = { fg = c.nord7 }, diffLine = { fg = c.nord3 }, diffIndexLine = { fg = c.nord9 }, -- GitSigns GitSignsAdd = { fg = c.add }, GitSignsAddNr = { fg = c.add }, GitSignsAddLn = { fg = c.add }, GitSignsChange = { fg = c.change }, GitSignsChangeNr = { fg = c.change }, GitSignsChangeLn = { fg = c.change }, GitSignsDelete = { fg = c.remove }, GitSignsDeleteNr = { fg = c.remove }, GitSignsDeleteLn = { fg = c.remove }, -- Indent Blankline IndentBlanklineChar = { fg = c.nord3 }, IndentBlanklineContextChar = { fg = c.nord10 }, -- Lightspeed LightspeedLabel = { fg = c.nord8, style = bold }, -- The character needed to be pressed to jump to the match position, after the whole search pattern has been given. It appears top of the second character of the pair, after the first input has been given. LightspeedLabelOverlapped = { fg = c.nord8, style = bold .. underline, }, -- When matches overlap, labels get next to each other - in that case they get different highlights, to be more easily distinguishable (slightly lighter or darker, depending on the global background). LightspeedLabelDistant = { fg = c.nord15, style = bold }, LightspeedLabelDistantOverlapped = { fg = c.nord15, style = bold .. underline, }, -- If the number of matches exceeds the available target labels, the next group of labeled targets are shown with a different color. Those can be reached by pressing `cycle_group_fwd_key` before the label character. LightspeedShortcut = { fg = c.nord10, style = bold }, LightspeedShortcutOverlapped = { fg = c.nord10, style = bold .. underline, }, -- Labels for positions that can be jumped to right after the first input (see |lightspeed-shortcuts|). These are highlighted as "inverted" labels by default (background/foreground switched). LightspeedMaskedChar = { fg = c.nord4, bg = c.nord2, style = bold, }, -- The second character of the match, that is shown on top of the first one, as a reminder. LightspeedGreyWash = { fg = c.nord3_bright }, -- Foreground color of the "washed out" area for 2-character search. Depending on the colorscheme, it might be appropriate to link this to the Comment highlight group. LightspeedUnlabeledMatch = { fg = c.nord4, bg = c.nord1 }, -- Matches that can be jumped to automatically, i.e. do not get a label - the only ones, and the first ones if `jump_to_first_match` is on. (Bold black or white by default, depending on the global background.) LightspeedOneCharMatch = { fg = c.nord8, style = bold .. inverse }, -- Matching characters of f/t search. (Default: |LightspeedShortcut| without underline. Setting some background color is recommended, as there is no "grey wash" for one-character search mode.) LightspeedUniqueChar = { style = bold .. underline }, -- Unique characters in the search direction, shown if `highlight_unique_chars` is on. Uses the same settings as |LightspeedUnlabeledMatch| by default. -- LightSpeedPeindigOpArea = {} -- When jumping based on partial input in -- operator-pending mode, we do not see the operation executed right away, -- because of the "safety" timeout (see |lightspeed-jump-on-partial-input|), -- therefore we set a temporary highlight on the operated area. -- LightspeedCursor = {} -- Linked to |hl-Cursor| by default. -- Neogit NeogitBranch = { fg = c.nord15 }, NeogitRemote = { fg = c.nord13 }, NeogitNotificationInfo = { fg = c.success }, NeogitNotificationWarning = { fg = c.warning }, NeogitNotificationError = { fg = c.error }, NeogitDiffAddHighlight = { fg = c.add, bg = c.nord1 }, NeogitDiffDeleteHighlight = { fg = c.remove, bg = c.nord1 }, NeogitDiffContextHighlight = { bg = c.nord1, fg = c.nord4, }, NeogitHunkHeader = { fg = c.nord4 }, NeogitHunkHeaderHighlight = { fg = c.nord7, bg = c.nord1 }, -- Neovim healthError = { fg = c.error }, healthSuccess = { fg = c.success }, healthWarning = { fg = c.warning }, -- nvim-cmp CmpItemAbbr = { fg = c.nord4 }, CmpItemAbbrDeprecated = { fg = c.nord3_bright }, CmpItemAbbrMatch = { fg = c.nord8, style = bold .. inverse }, CmpItemAbbrMatchFuzzy = { fg = c.nord8, bg = c.nord0, style = bold .. inverse, }, CmpItemKind = { fg = c.nord9 }, CmpItemMenu = { fg = c.nord3_bright }, CmpGhostText = { fg = c.nord3 }, CmpDocumentation = { bg = c.nord3 }, -- nvim-dap DapBreakpoint = { fg = c.nord11 }, DapStopped = { fg = c.nord15 }, -- octo.nvim OctoEditable = { bg = c.nord1 }, -- nvim-ts-rainbow rainbowcol1 = { fg = c.nord10 }, rainbowcol2 = { fg = c.nord15 }, rainbowcol3 = { fg = c.nord14 }, rainbowcol4 = { fg = c.nord13 }, rainbowcol5 = { fg = c.nord12 }, rainbowcol6 = { fg = c.nord12 }, rainbowcol7 = { fg = c.nord9 }, -- Telescope TelescopePromptBorder = { fg = c.nord15 }, TelescopeResultsBorder = { fg = c.nord9 }, TelescopePreviewBorder = { fg = c.nord10 }, TelescopeSelectionCaret = { fg = c.nord9 }, TelescopeSelection = { fg = c.nord9 }, TelescopeMatching = { fg = c.nord8 }, -- TelescopeNormal = {}, -- Tree-sitter TSAttribute = { fg = c.nord10 }, -- Annotations that can be attached to the code to denote some kind of meta information. e.g. C++/Dart attributes. TSBoolean = { link = "Boolean" }, -- Boolean literals: `True` and `False` in Python. TSCharacter = { link = "Character" }, -- Character literals: `'a'` in C. TSComment = { link = "Comment" }, -- Line comments and block comments. TSConditional = { link = "Conditional" }, -- Keywords related to conditionals: `if`, `when`, `cond`, etc. TSConstant = { link = "Constant" }, -- Constants identifiers. These might not be semantically constant. E.g. uppercase variables in Python. TSConstBuiltin = { link = "Constant" }, -- Built-in constant values: `nil` in Lua. TSConstMacro = { link = "Function" }, -- Constants defined by macros: `NULL` in C. TSConstructor = { link = "Function" }, -- Constructor calls and definitions: `{}` in Lua, and Java constructors. TSError = { link = "Error" }, -- Syntax/parser errors. This might highlight large sections of code while the user is typing still incomplete code, use a sensible highlight. TSException = { link = "Exception" }, -- Exception related keywords: `try`, `except`, `finally` in Python. TSField = { link = "Identifier" }, -- Object and struct fields. TSFloat = { link = "Float" }, -- Floating-point number literals. TSFunction = { link = "Function" }, -- Function calls and definitions. TSFuncBuiltin = { link = "Function" }, -- Built-in functions: `print` in Lua. TSFuncMacro = { fg = c.nord8 }, -- Macro defined functions (calls and definitions): each `macro_rules` in Rust. TSInclude = { link = "Include" }, -- File or module inclusion keywords: `#include` in C, `use` or `extern crate` in Rust. TSKeyword = { link = "Keyword" }, -- Keywords that don't fit into other categories. TSKeywordFunction = { link = "Keyword" }, -- Keywords used to define a function: `function` in Lua, `def` and `lambda` in Python. TSKeywordOperator = { link = "Keyword" }, -- Unary and binary operators that are English words: `and`, `or` in Python; `sizeof` in C. TSKeywordReturn = { link = "Keyword" }, -- Keywords like `return` and `yield`. TSLabel = { link = "Label" }, -- GOTO labels: `label:` in C, and `::label::` in Lua. TSMethod = { link = "Function" }, -- Method calls and definitions. TSNamespace = { fg = c.nord7 }, -- Identifiers referring to modules and namespaces. -- TSNone = {}, -- No highlighting (sets all highlight arguments to `NONE`). this group is used to clear certain ranges, for example, string interpolations. Don't change the values of this highlight group. TSNumber = { link = "Number" }, -- Numeric literals that don't fit into other categories. TSOperator = { link = "Operator" }, -- Binary or unary operators: `+`, and also `->` and `*` in C. TSParameter = { fg = c.nord10 }, -- Parameters of a function. TSParameterReference = { link = "TSParameter" }, -- References to parameters of a function. -- TSProperty = { }, -- Same as `TSField`. TSPunctDelimiter = { link = "Delimiter" }, -- Punctuation delimiters: Periods, commas, semicolons, etc. TSPunctBracket = { link = "Delimiter" }, -- Brackets, braces, parentheses, etc. TSPunctSpecial = { link = "Delimiter" }, -- Special punctuation that doesn't fit into the previous categories. TSRepeat = { link = "Repeat" }, -- Keywords related to loops: `for`, `while`, etc. TSString = { link = "String" }, -- String literals. TSStringRegex = { link = "String" }, -- Regular expression literals. TSStringEscape = { fg = c.nord15 }, -- Escape characters within a string: `\n`, `\t`, etc. TSStringSpecial = { link = "TSStringEscape" }, -- Strings with special meaning that don't fit into the previous categories. TSSymbol = { link = "Identifier" }, -- Identifiers referring to symbols or atoms. TSTag = { link = "Tag" }, -- Tags like HTML tag names. TSTagAttribute = { link = "TSAttribute" }, -- HTML tag attributes. TSTagDelimiter = { link = "Delimiter" }, -- Tag delimiters like `<` `>` `/`. TSText = { link = "Text" }, -- Non-structured text. Like text in a markup language. TSStrong = { link = "Bold" }, -- Text to be represented in bold. TSEmphasis = { link = "Italic" }, -- Text to be represented with emphasis. TSUnderline = { link = "Underline" }, -- Text to be represented with an underline. TSStrike = { style = strikethrough }, -- Strikethrough text. TSTitle = { fg = c.nord8, style = bold }, -- Text that is part of a title. TSLiteral = { fg = c.nord7 }, -- Literal or verbatim text. TSURI = { fg = c.nord8, style = underline }, -- URIs like hyperlinks or email addresses. TSMath = { fg = c.nord7 }, -- Math environments like LaTeX's `$ ... $` TSTextReference = { link = "String" }, -- Footnotes, text references, citations, etc. TSEnvironment = { bg = c.nord1 }, -- Text environments of markup languages. TSEnvironmentName = { link = "Tag" }, -- Text/string indicating the type of text environment. Like the name of `\begin` block in LaTeX. TSNote = { fg = c.info }, -- Text representation of an informational note. TSWarning = { fg = c.warning }, -- Text representation of a warning note. TSDanger = { fg = c.error }, -- Text representation of a danger note. TSType = { link = "Type" }, -- Type (and class) definitions and annotations. TSTypeBuiltin = { link = "TypeBuiltin" }, -- Built-in types: `i32` in Rust. TSVariable = { link = "Identifier" }, -- Variable names that don't fit into other categories. TSVariableBuiltin = { link = "Keyword" }, -- Variable names defined by the language: `this` or `self` in Javascript. -- Which-key.nvim WhichKey = { link = "Function" }, -- the key WhichKeyGroup = { link = "Keyword" }, -- a group WhichKeySeparator = { link = "Keyword" }, -- the separator between the key and its label WhichKeyDesc = { link = "Identifier" }, -- the label of the key WhichKeyFloat = { fg = c.nord4, bg = c.nord1 }, -- Normal in the popup window WhichKeyValue = { link = "Comment" }, -- used by plugins that provide values } return theme end return M
local math2d = require('math2d') local magnetRamps = {} magnetRamps.setRange = function (ramp, range, player) ramp.range = range + 6 if ramp.rangeID then rendering.destroy(ramp.rangeID) end for each, tile in pairs(ramp.tiles) do tile.destroy() end ramp.tiles = {} ramp.rangeID = rendering.draw_sprite{ sprite = "RTMagnetTrainRampRange", surface = ramp.entity.surface, orientation = ramp.entity.orientation+0.25, target = ramp.entity, target_offset = { global.OrientationUnitComponents[ramp.entity.orientation+0.25].x-(range+1)/2*global.OrientationUnitComponents[ramp.entity.orientation].x, global.OrientationUnitComponents[ramp.entity.orientation+0.25].y-(range+1)/2*global.OrientationUnitComponents[ramp.entity.orientation].y }, only_in_alt_mode = true, x_scale = range / 2, y_scale = 0.5, tint = {r = 0.5, g = 0.5, b = 0, a = 0.5} } local orientationComponent = global.OrientationUnitComponents[ramp.entity.orientation] for i = 1, range do local offset = math2d.position.multiply_scalar(orientationComponent, -i) local centerPosition = math2d.position.add(ramp.entity.position, offset) local a, b = makeMagRampSection(centerPosition, ramp.entity.surface, ramp.entity.orientation) table.insert(ramp.tiles, a) table.insert(ramp.tiles, b) end ramp.power.electric_buffer_size = 200000 * range if player then player.print("Set Range: " .. range .. " tiles. Required power: " .. util.format_number(ramp.power.electric_buffer_size, true) .. "J") end end function makeMagRampSection(centerPosition, surface, orientation) local offsets = { a = math2d.position.rotate_vector({ 0.5, 0 }, 360 * orientation), b = math2d.position.rotate_vector({ 1.5, 0 }, 360 * orientation), } local a = surface.create_entity({ name = "RTMagnetRail", position = math2d.position.add(centerPosition, offsets.a), create_build_effect_smoke = true }) rendering.draw_sprite{ sprite = "RTMagnetRailSprite", x_scale = 0.5, y_scale = 0.5, surface = surface, target = a, render_layer = "80" } a.destructible = false local b = surface.create_entity({ name = "RTMagnetRail", position = math2d.position.add(centerPosition, offsets.b), create_build_effect_smoke = true }) rendering.draw_sprite{ sprite = "RTMagnetRailSprite", x_scale = 0.5, y_scale = 0.5, surface = surface, target = b, render_layer = "80" } b.destructible = false return a, b end return magnetRamps
function Spawn( entityKeyValues ) thisEntity:SetModel("models/development/invisiblebox.vmdl") thisEntity:SetOriginalModel("models/development/invisiblebox.vmdl") local greevils = { "npc_black_greevil", "npc_white_greevil", "npc_orange_greevil", "npc_yellow_greevil", "npc_green_greevil", "npc_purple_greevil", "npc_fire_greevil", "npc_ice_greevil" } local greevil_name = GetRandomElement(greevils) Timers:CreateTimer(function () local time = math.ceil(GameRules:GetDOTATime(false, false)) if time % 60.0 == 0 and time > 0 then if not IsValidEntity(greevil) or not greevil:IsAlive() then greevil = CreateUnitByName(greevil_name, thisEntity:GetAbsOrigin(), true, nil, nil, DOTA_TEAM_NEUTRALS) local angles = thisEntity:GetAngles() greevil:SetAngles(angles.x, angles.y, angles.z) end end return 1.0 end) end
local luvi = require('luvi'); _G.loadModule = function (idf,path) idf = idf:match("%.?([^%.]+)$"); luvi.bundle.register(idf,path); return require(idf); end; local fs = require("fs"); io.write("\n[ 그래프로 그림 그리기 ]\n\27[33m그릴 수 있는 그래프들은 다음과 같습니다\27[0m\n──────────────────────────────────────\n"); local items = fs.readdirSync("./graphs"); for i,str in ipairs(items) do io.write(("\27[32m%d 번\27[0m : %s\n"):format(i,str)); end io.write("──────────────────────────────────────\n\27[33m출력할 그래프의 번호를 입력하세요 : \27[0m"); local input = io.read(); local this = items[tonumber(input)]; if not this then io.write("해당 그래프는 존재하지 않습니다!"); os.exit(1); end local draw = loadModule("draw","./draw.lua")--require("draw"); local file = io.open("./graphs/" .. this); local str = file:read("*a"); file:close(); io.write( draw:draw( draw:funcFromStr(str), -- xSize,ySize,mut,title 88,38,10,this ), draw:footer(str) );
local assert = assert local type = type module( "environment", package.seeall ) local environments = {} local functions = { ["null"] = function() end } --[[------------------------------------------------------------------------- Working on Functions ---------------------------------------------------------------------------]] function saveFunc( name, func, override ) assert( type( name ) == "string", "bad argument #1 (string expected)" ) assert( name ~= "null", "You can't just go ahead and overwrite a 'null' function." ) assert( type( func ) == "function", "bad argument #2 (function expected)" ) if (functions[ name ] == nil) or (override == true) then functions[ name ] = func end return functions[ name ] end function loadFunc( name ) return functions[ name ] or functions["null"] end function removeFunc( name ) assert( type( name ) == "string", "bad argument #1 (string expected)" ) assert( name ~= "null", "You can't just go ahead and remove a 'null' function." ) functions[ name ] = nil end --[[------------------------------------------------------------------------- Working on Environments ---------------------------------------------------------------------------]] function global() return _G end do local ENV = {} ENV["__index"] = ENV debug.getregistry().Environment = ENV do function ENV:getID() return self["__env"]["id"] end function ENV:getName() return self["__env"]["identifier"] end function ENV:__tostring() return "GLua Environment - " .. self:getName() .. " [" .. self:getID() .. "]" end function ENV:replace( name, func ) assert( type( name ) == "string", "bad argument #1 (string expected)" ) self[ name ] = func or functions["null"] end end do local getmetatable = getmetatable function isEnvironment( any ) return getmetatable( any ) == ENV end end do local emptyTable = {} do local table_Count = table.Count local setmetatable = setmetatable function new( any, builder, override ) assert( type( any ) == "string", "bad argument #1 (string expected)" ) if (environments[ any ] == nil) or (override == true) then local env = {} if type( builder ) == "function" then env = builder( any ) or env elseif type( builder ) == "table" then env = builder end if ( type( env ) == "table" ) then env["__env"] = { ["identifier"] = any, ["id"] = table_Count( environments ) + 1 } environments[ any ] = setmetatable( env, ENV ) end end return environments[ any ] or emptyTable end end function get( any ) return environments[ any ] or emptyTable end function remove( any ) environments[ any ] = nil end end end function getName( env ) if isEnvironment( env ) then return env:getName() end return "GLua Environment" end do local table_Copy = table.Copy function getAll() return table_Copy( environments ) end end do local runExtensions = { ["lua"] = true, ["dat"] = true, ["txt"] = true } function isIncludeExtension( ext ) return runExtensions[ ext ] or false end end do local CompileFile = CompileFile local file_Exists = file.Exists local debug_setfenv = debug.setfenv function include( path, environment, gamePath ) if file_Exists( path, gamePath or "GAME" ) and isIncludeExtension( path:GetExtensionFromFilename() ) then local func = nil local luaCode = file.Read( path, gamePath or "GAME" ) if (luaCode == nil) or (luaCode == "") then func = CompileFile( path ) else func = CompileString( luaCode, getName( environment ) .. ": " .. path ) end assert( type( func ) == "function", "Lua code compilation failed! <nil>" ) if isEnvironment( environment ) then debug_setfenv( func, environment ) end local ok, data = pcall( func ) return (ok == true) and data end end end
local K, C = unpack(select(2, ...)) if C.Misc.PvPEmote ~= true then return end local Module = K:NewModule("PvPEmote", "AceEvent-3.0") local _G = _G local bit_band = bit.band local math_random = math.random local select = select local DoEmote = _G.DoEmote local GetAchievementInfo = _G.GetAchievementInfo local unitFilter = _G.COMBATLOG_OBJECT_CONTROL_PLAYER local PVPEmotes = { "BARK", "BECKON", "BITE", "BONK", "BYE", "CACKLE", "CALM", "CHUCKLE", "COMFORT", "CUDDLE", "CURTSEY", "FLEX", "GIGGLE", "GLOAT", "GRIN", "GROWL", "GUFFAW", "INSULT", "LAUGH", "LICK", "MOCK", "MOO", "MOON", "MOURN", "NO", "PITY", "RASP", "ROAR", "ROFL", "RUDE", "SCRATCH", "SHOO", "SIGH", "SLAP", "SMIRK", "SNARL", "SNICKER", "SNIFF", "SNUB", "SOOTHE", "TAP", "TAUNT", "TEASE", "THANK", "TICKLE", "VETO", "VIOLIN", "YAWN" } function Module:COMBAT_LOG_EVENT_UNFILTERED() local _, subEvent, _, sourceGUID, _, _, _, _, destName, destFlags = CombatLogGetCurrentEventInfo() local alreadyHugged if (subEvent == "PARTY_KILL") and (sourceGUID == K.GUID) and (bit_band(destFlags, unitFilter) > 0) then if alreadyHugged or select(4, GetAchievementInfo(247)) then -- Fire off a random emote, to keep it interesting. DoEmote(PVPEmotes[math_random(1, #PVPEmotes)], destName) else DoEmote("HUG", destName) -- Set a flag indicating we have tried it once, -- in case we're dealing with a bugged achievement. -- No point spamming hug forever when the issue requires -- a server restart or client relog to be fixed anyway. alreadyHugged = true end end end function Module:OnEnable() self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end
-- ======= Copyright (c) 2003-2014, Unknown Worlds Entertainment, Inc. All rights reserved. ======= -- -- lua\NS2Utility.lua -- -- Created by: Charlie Cleveland (charlie@unknownworlds.com) -- -- NS2-specific utility functions. -- -- ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/Table.lua") Script.Load("lua/Utility.lua") local kInfestationDecalSimpleMaterial = PrecacheAsset("materials/infestation/infestation_decal_simple.material") function FormatDateTimeString(dateTime) local tmpDate = os.date("*t", dateTime) local ordinal = "th" local lastDig = tmpDate.day % 10 if (tmpDate.day < 11 or tmpDate.day > 13) and lastDig > 0 and lastDig < 4 then if lastDig == 1 then ordinal = "st" elseif lastDig == 2 then ordinal = "nd" else ordinal = "rd" end end return string.format("%s%s, %d @ %d:%02d", os.date("%A, %B %d", dateTime), ordinal, tmpDate.year, tmpDate.hour, tmpDate.min) end function PlayerUI_GetGameTimeString() local gameTime, state = PlayerUI_GetGameLengthTime() if state < kGameState.PreGame then gameTime = 0 end local minutes = math.floor(gameTime / 60) local seconds = math.floor(gameTime % 60) return (string.format("%d:%.2d", minutes, seconds)) end function GetWeaponReserveAmmoFraction(weapon) local fraction = -1 if weapon and weapon:isa("Weapon") then if weapon:isa("ClipWeapon") then fraction = weapon:GetAmmo()/weapon:GetMaxAmmo() end end return fraction end function GetWeaponAmmoFraction(weapon) local fraction = -1 if weapon and weapon:isa("Weapon") then if weapon:isa("ClipWeapon") then fraction = weapon:GetClip()/weapon:GetClipSize() elseif weapon:isa("GrenadeThrower") then fraction = weapon.grenadesLeft/kMaxHandGrenades elseif weapon:isa("LayMines") then fraction = weapon:GetMinesLeft()/kNumMines elseif weapon:isa("ExoWeaponHolder") then local leftWeapon = Shared.GetEntity(weapon.leftWeaponId) local rightWeapon = Shared.GetEntity(weapon.rightWeaponId) if rightWeapon:isa("Railgun") then fraction = rightWeapon:GetChargeAmount() if leftWeapon:isa("Railgun") then fraction = (fraction + leftWeapon:GetChargeAmount()) / 2.0 end elseif rightWeapon:isa("Minigun") then fraction = rightWeapon.heatAmount if leftWeapon:isa("Minigun") then fraction = (fraction + leftWeapon.heatAmount) / 2.0 end fraction = 1 - fraction end elseif weapon:isa("Builder") or weapon:isa("Welder") then fraction = PlayerUI_GetUnitStatusPercentage()/100 end end return fraction end function GetWeaponReserveAmmoString(weapon) local ammo = "" if weapon and weapon:isa("Weapon") then if weapon:isa("ClipWeapon") then ammo = string.format("%d", weapon:GetAmmo() or 0) end end return ammo end function GetWeaponAmmoString(weapon) local ammo = "" if weapon and weapon:isa("Weapon") then if weapon:isa("ClipWeapon") then ammo = string.format("%d", weapon:GetClip() or 0) elseif weapon:isa("GrenadeThrower") then ammo = string.format("%d", weapon.grenadesLeft or 0) elseif weapon:isa("LayMines") then ammo = string.format("%d", weapon:GetMinesLeft() or 0) elseif weapon:isa("ExoWeaponHolder") then local leftWeapon = Shared.GetEntity(weapon.leftWeaponId) local rightWeapon = Shared.GetEntity(weapon.rightWeaponId) local leftAmmo = -1 local rightAmmo = -1 if rightWeapon:isa("Railgun") then rightAmmo = rightWeapon:GetChargeAmount() * 100 if leftWeapon:isa("Railgun") then leftAmmo = leftWeapon:GetChargeAmount() * 100 end elseif rightWeapon:isa("Minigun") then rightAmmo = rightWeapon.heatAmount * 100 if leftWeapon:isa("Minigun") then leftAmmo = leftWeapon.heatAmount * 100 end end if leftAmmo > -1 and rightAmmo > -1 then ammo = string.format("%d%% / %d%%", leftAmmo, rightAmmo) elseif rightAmmo > -1 then ammo = string.format("%d%%", rightAmmo) end elseif weapon:isa("Builder") or weapon:isa("Welder") and PlayerUI_GetUnitStatusPercentage() > 0 then ammo = string.format("%d%%", PlayerUI_GetUnitStatusPercentage()) end end return ammo end function GetIsPointInsideClogs(point) local clogs = GetEntitiesWithinRange("Clog", point, Clog.kRadius) for i=1, #clogs do if clogs[i] then return true end end return false end function GetHallucinationLifeTimeFraction(self) local fraction = 1 if self.isHallucination or self:isa("Hallucination") then fraction = 1 - Clamp((Shared.GetTime() - self.creationTime) / kHallucinationLifeTime, 0, 1) end return fraction end function GetTargetOrigin(target) if target.GetEngagementPoint then return target:GetEngagementPoint() end if target.GetModelOrigin then return target:GetModelOrigin() end return target:GetOrigin() end function SelectAllHallucinations(player) DeselectAllUnits(player:GetTeamNumber()) for _, hallucination in ipairs(GetEntitiesForTeam("Hallucination", player:GetTeamNumber())) do if hallucination:GetIsAlive() then hallucination:SetSelected(player:GetTeamNumber(), true, true, true) end end for _, hallucination in ipairs(GetEntitiesForTeam("Alien", player:GetTeamNumber())) do if hallucination:GetIsAlive() and hallucination.isHallucination then hallucination:SetSelected(player:GetTeamNumber(), true, true, true) end end end function GetDirectedExtentsForDiameter(direction, diameter) -- normalize and scale the vector, then extract the extents from it local v = GetNormalizedVector(direction) v:Scale(diameter) local x = math.sqrt(v.y * v.y + v.z * v.z) local y = math.sqrt(v.x * v.x + v.z * v.z) local z = math.sqrt(v.y * v.y + v.x * v.x) local result = Vector(x,y,z) -- Log("extents for %s/%s -> %s", direction, v, result) return result end function GetSupplyUsedByTeam(teamNumber) assert(teamNumber) local supplyUsed = 0 if Server then local team = GetGamerules():GetTeam(teamNumber) if team and team.GetSupplyUsed then supplyUsed = team:GetSupplyUsed() end else local teamInfoEnt = GetTeamInfoEntity(teamNumber) if teamInfoEnt and teamInfoEnt.GetSupplyUsed then supplyUsed = teamInfoEnt:GetSupplyUsed() end end return supplyUsed end function GetMaxSupplyForTeam(teamNumber) return kMaxSupply --[[ local maxSupply = 0 if Server then local team = GetGamerules():GetTeam(teamNumber) if team and team.GetNumCapturedTechPoints then maxSupply = team:GetNumCapturedTechPoints() * kSupplyPerTechpoint end else local teamInfoEnt = GetTeamInfoEntity(teamNumber) if teamInfoEnt and teamInfoEnt.GetNumCapturedTechPoints then maxSupply = teamInfoEnt:GetNumCapturedTechPoints() * kSupplyPerTechpoint end end return maxSupply ]] end if Client then function CreateSimpleInfestationDecal(size, coords) if not size then size = 1.5 end local decal = Client.CreateRenderDecal() local infestationMaterial = Client.CreateRenderMaterial() infestationMaterial:SetMaterial(kInfestationDecalSimpleMaterial) infestationMaterial:SetParameter("scale", size) decal:SetMaterial(infestationMaterial) decal:SetExtents(Vector(size, size, size)) if coords then decal:SetCoords(coords) end return decal end end function GetIsTechUseable(techId, teamNum) local useAble = false local techTree = GetTechTree(teamNum) if techTree then local techNode = techTree:GetTechNode(techId) if techNode then useAble = techNode:GetAvailable() if techNode:GetIsResearch() then useAble = techNode:GetResearched() and techNode:GetHasTech() end end end return useAble == true end if Server then Script.Load("lua/NS2Utility_Server.lua") end if Client then PrecacheAsset("ui/buildmenu.dds") end local function HandleImpactDecal(position, doer, surface, target, showtracer, altMode, damage, direction, decalParams) -- when we hit a target project some blood on the geometry behind --DebugLine(position, position + direction * kBloodDistance, 3, 1, 0, 0, 1) if direction then local trace = Shared.TraceRay(position, position + direction * kBloodDistance, CollisionRep.Damage, PhysicsMask.Bullets, EntityFilterOne(target)) if trace.fraction ~= 1 then decalParams[kEffectHostCoords] = Coords.GetTranslation(trace.endPoint) decalParams[kEffectHostCoords].yAxis = trace.normal decalParams[kEffectHostCoords].zAxis = direction decalParams[kEffectHostCoords].xAxis = decalParams[kEffectHostCoords].yAxis:CrossProduct(decalParams[kEffectHostCoords].zAxis) decalParams[kEffectHostCoords].zAxis = decalParams[kEffectHostCoords].xAxis:CrossProduct(decalParams[kEffectHostCoords].yAxis) decalParams[kEffectHostCoords].zAxis:Normalize() decalParams[kEffectHostCoords].xAxis:Normalize() --DrawCoords(decalParams[kEffectHostCoords]) if not target then decalParams[kEffectSurface] = trace.surface end GetEffectManager():TriggerEffects("damage_decal", decalParams) end end end function HandleHitEffect(position, doer, surface, target, showtracer, altMode, damage, direction) local tableParams = { } tableParams[kEffectHostCoords] = Coords.GetTranslation(position) if doer then tableParams[kEffectFilterDoerName] = doer:GetClassName() end tableParams[kEffectSurface] = surface tableParams[kEffectFilterInAltMode] = altMode if target then tableParams[kEffectFilterClassName] = target:GetClassName() if target.GetTeamType then tableParams[kEffectFilterIsMarine] = target:GetTeamType() == kMarineTeamType tableParams[kEffectFilterIsAlien] = target:GetTeamType() == kAlienTeamType end else tableParams[kEffectFilterIsMarine] = false tableParams[kEffectFilterIsAlien] = false end -- Don't play the hit cinematic, those are made for third person. if target ~= Client.GetLocalPlayer() then GetEffectManager():TriggerEffects("damage", tableParams) end -- Always play sound effect. GetEffectManager():TriggerEffects("damage_sound", tableParams) if showtracer == true and doer then local tracerStart = (doer.GetBarrelPoint and doer:GetBarrelPoint()) or (doer.GetEyePos and doer:GetEyePos()) or doer:GetOrigin() local tracerVelocity = GetNormalizedVector(position - tracerStart) * kTracerSpeed CreateTracer(tracerStart, position, tracerVelocity, doer) end if damage > 0 and target and target.OnTakeDamageClient then target:OnTakeDamageClient(damage, doer, position) end HandleImpactDecal(position, doer, surface, target, showtracer, altMode, damage, direction, tableParams) end function GetCommanderForTeam(teamNumber) local commanders = GetEntitiesForTeam("Commander", teamNumber) if #commanders > 0 then return commanders[1] end end function UpdateMenuTechId(teamNumber, selected) local commander = GetCommanderForTeam(teamNumber) local menuTechId = commander:GetMenuTechId() if selected then menuTechId = kTechId.RootMenu elseif menuTechId ~= kTechId.BuildMenu and menuTechId ~= kTechId.AdvancedMenu and menuTechId ~= kTechId.AssistMenu then menuTechId = kTechId.BuildMenu end if Client then commander:SetCurrentTech(menuTechId) elseif Server then commander.menuTechId = menuTechId end return menuTechId end -- passing true for resetClientMask will cause the client to discard the predict selection and wait for a server update function DeselectAllUnits(teamNumber, resetClientMask, sendMessage) if sendMessage == nil then sendMessage = true end for _, unit in ipairs(GetEntitiesWithMixin("Selectable")) do unit:SetSelected(teamNumber, false, false, false) if resetClientMask then unit:ClearClientSelectionMask() end end -- inform server to reset the selection if Client and sendMessage then local selectUnitMessage = BuildSelectUnitMessage(teamNumber, nil, false, false) Client.SendNetworkMessage("SelectUnit", selectUnitMessage, true) end end function GetIsRecycledUnit(unit) return unit ~= nil and HasMixin(unit, "Recycle") and unit:GetIsRecycled() end function GetGameInfoEntity() local entityList = Shared.GetEntitiesWithClassname("GameInfo") if entityList:GetSize() > 0 then return entityList:GetEntityAtIndex(0) end end function GetTeamInfoEntity(teamNumber) local teamInfo = GetEntitiesForTeam("TeamInfo", teamNumber) if table.icount(teamInfo) > 0 then return teamInfo[1] end end function GetIsTargetDetected(target) return HasMixin(target, "Detectable") and target:GetIsDetected() end function GetIsParasited(target) return target ~= nil and HasMixin(target, "ParasiteAble") and target:GetIsParasited() end function GetTeamHasCommander(teamNumber) local teamInfoEntity = GetTeamInfoEntity(teamNumber) if teamInfoEntity and teamInfoEntity:GetLastCommIsBot() then return false end if Client then local commName = ScoreboardUI_GetCommanderName(teamNumber) return commName ~= nil elseif Server then return #GetEntitiesForTeam("Commander", teamNumber) ~= 0 end end function GetIsCloseToMenuStructure(player) local ptlabs = GetEntitiesForTeamWithinRange("PrototypeLab", player:GetTeamNumber(), player:GetOrigin(), PrototypeLab.kResupplyUseRange) local armories = GetEntitiesForTeamWithinRange("Armory", player:GetTeamNumber(), player:GetOrigin(), Armory.kResupplyUseRange) return (ptlabs and #ptlabs > 0) or (armories and #armories > 0) end function GetPlayerCanUseEntity(player, target) local useSuccessTable = { useSuccess = false } if target.GetCanBeUsed then useSuccessTable.useSuccess = true target:GetCanBeUsed(player, useSuccessTable) end --Print("GetPlayerCanUseEntity(%s, %s) returns %s", ToString(player), ToString(target), ToString(useSuccessTable.useSuccess)) -- really need to move this functionality into two mixin (when for user, one for useable) return useSuccessTable.useSuccess or (target.GetCanAlwaysBeUsed and target:GetCanAlwaysBeUsed()) end function GetIsClassHasEnergyFor(className, entity, techId, techNode, commander) local hasEnergy = false if entity:isa(className) and HasMixin(entity, "Energy") and entity:GetTechAllowed(techId, techNode, commander) then local cost = LookupTechData(techId, kTechDataCostKey, 0) hasEnergy = entity:GetEnergy() >= cost end return hasEnergy end function GetIsUnitActive(unit, debug) local powered = not HasMixin(unit, "PowerConsumer") or not unit:GetRequiresPower() or unit:GetIsPowered() local alive = not HasMixin(unit, "Live") or unit:GetIsAlive() local isBuilt = not HasMixin(unit, "Construct") or unit:GetIsBuilt() local isRecycled = HasMixin(unit, "Recycle") and (unit:GetIsRecycled() or unit:GetIsRecycling()) local isConsumed = HasMixin(unit, "Consume") and (unit:GetIsConsumed() or unit:GetIsConsuming()) if debug then Print("------------ GetIsUnitActive(%s) -----------------", ToString(unit)) Print("powered: %s", ToString(powered)) Print("alive: %s", ToString(alive)) Print("isBuilt: %s", ToString(isBuilt)) Print("isRecycled: %s", ToString(isRecycled)) Print("isConsumed: %s", ToString(isConsumed)) Print("-----------------------------") end return powered and alive and isBuilt and not isRecycled and not isConsumed end function GetIsUnderResourceTowerLimit(self) local techPoints = 0 local harvesters = 0 local teamInfo = GetEntitiesForTeam("TeamInfo", self:GetTeamNumber()) if table.icount(teamInfo) > 0 then techPoints = teamInfo[1]:GetNumCapturedTechPoints() harvesters = teamInfo[1]:GetNumCapturedResPoints() end local towerLimit = kMinSupportedRTs + techPoints * kRTsPerTechpoint return harvesters < towerLimit end function GetAnyNearbyUnitsInCombat(origin, radius, teamNumber) local nearbyUnits = GetEntitiesWithMixinForTeamWithinRange("Combat", teamNumber, origin, radius) for e = 1, #nearbyUnits do if nearbyUnits[e]:GetIsInCombat() then return true end end return false end function GetCircleSizeForEntity(entity) local size = ConditionalValue(entity:isa("Player"),2.0, 2) size = ConditionalValue(entity:isa("Drifter"), 2.5, size) size = ConditionalValue(entity:isa("PowerPoint"), 2.6, size) size = ConditionalValue(entity:isa("Hive"), 6.5, size) size = ConditionalValue(entity:isa("MAC"), 2.0, size) size = ConditionalValue(entity:isa("Door"), 4.0, size) size = ConditionalValue(entity:isa("InfantryPortal"), 3.5, size) size = ConditionalValue(entity:isa("Extractor"), 3.0, size) size = ConditionalValue(entity:isa("CommandStation"), 6.5, size) size = ConditionalValue(entity:isa("Egg"), 2.5, size) size = ConditionalValue(entity:isa("Armory"), 4.0, size) size = ConditionalValue(entity:isa("Harvester"), 3.7, size) size = ConditionalValue(entity:isa("Crag"), 3, size) size = ConditionalValue(entity:isa("RoboticsFactory"), 6, size) size = ConditionalValue(entity:isa("ARC"), 3.5, size) size = ConditionalValue(entity:isa("ArmsLab"), 4.3, size) size = ConditionalValue(entity:isa("BoneWall"), 5.5, size) return size end gMaxHeightOffGround = 0.0 function GetAttachEntity(techId, position, snapRadius) local attachClass = LookupTechData(techId, kStructureAttachClass) if attachClass then for _, currentEnt in ipairs( GetEntitiesWithinRange(attachClass, position, ConditionalValue(snapRadius, snapRadius, .5)) ) do if not currentEnt:GetAttached() then return currentEnt end end end return nil end local function FindPoweredAttachEntities(className, teamNumber, origin, range) ASSERT(type(className) == "string") ASSERT(type(teamNumber) == "number") ASSERT(origin ~= nil) ASSERT(type(range) == "number") local function teamAndPoweredFilterFunction(entity) return entity:GetTeamNumber() == teamNumber and entity:GetIsBuilt() and entity:GetIsPowered() end return Shared.GetEntitiesWithTagInRange("class:" .. className, origin, range, teamAndPoweredFilterFunction) end function CheckForFlatSurface(origin, boxExtents) local valid = true -- Perform trace at center, then at each of the extent corners if boxExtents then local tracePoints = { origin + Vector(-boxExtents, 0.5, -boxExtents), origin + Vector(-boxExtents, 0.5, boxExtents), origin + Vector( boxExtents, 0.5, -boxExtents), origin + Vector( boxExtents, 0.5, boxExtents) } for index, point in ipairs(tracePoints) do local trace = Shared.TraceRay(tracePoints[index], tracePoints[index] - Vector(0, 0.7, 0), CollisionRep.Move, PhysicsMask.AllButPCs, EntityFilterOne(nil)) if (trace.fraction == 1) then valid = false break end end end return valid end --[[ * Returns the spawn point on success, nil on failure. ]] function ValidateSpawnPoint(spawnPoint, capsuleHeight, capsuleRadius, filter, origin) local center = Vector(0, capsuleHeight * 0.5 + capsuleRadius, 0) local spawnPointCenter = spawnPoint + center -- Make sure capsule isn't interpenetrating something. local spawnPointBlocked = Shared.CollideCapsule(spawnPointCenter, capsuleRadius, capsuleHeight, CollisionRep.Default, PhysicsMask.AllButPCs, nil) if not spawnPointBlocked then -- Trace capsule to ground, making sure we're not on something like a player or structure local trace = Shared.TraceCapsule(spawnPointCenter, spawnPoint - Vector(0, 10, 0), capsuleRadius, capsuleHeight, CollisionRep.Move, PhysicsMask.AllButPCs) if trace.fraction < 1 and (trace.entity == nil or not trace.entity:isa("ScriptActor")) then VectorCopy(trace.endPoint, spawnPoint) local endPoint = trace.endPoint + Vector(0, capsuleHeight / 2, 0) -- Trace in both directions to make sure no walls are being ignored. trace = Shared.TraceRay(endPoint, origin, CollisionRep.Move, PhysicsMask.AllButPCs, filter) local traceOriginToEnd = Shared.TraceRay(origin, endPoint, CollisionRep.Move, PhysicsMask.AllButPCs, filter) if trace.fraction == 1 and traceOriginToEnd.fraction == 1 then return spawnPoint - Vector(0, capsuleHeight / 2, 0) end end end return nil end -- Find place for player to spawn, within range of origin. Makes sure that a line can be traced between the two points -- without hitting anything, to make sure you don't spawn on the other side of a wall. Returns nil if it can't find a -- spawn point after a few tries. function GetRandomSpawnForCapsule(capsuleHeight, capsuleRadius, origin, minRange, maxRange, filter, validationFunc) ASSERT(capsuleHeight > 0) ASSERT(capsuleRadius > 0) ASSERT(origin ~= nil) ASSERT(type(minRange) == "number") ASSERT(type(maxRange) == "number") ASSERT(maxRange > minRange) ASSERT(minRange > 0) ASSERT(maxRange > 0) local maxHeight = 10 for i = 0, 10 do local spawnPoint local points = GetRandomPointsWithinRadius(origin, minRange, maxRange, maxHeight, 1, 1, nil, validationFunc) if #points == 1 then spawnPoint = points[1] elseif Server then --DebugPrint("GetRandomPointsWithinRadius() failed inside of GetRandomSpawnForCapsule()") end if spawnPoint then -- The spawn point returned by GetRandomPointsWithinRadius() may be too close to the ground. -- Move it up a bit so there is some "wiggle" room. ValidateSpawnPoint() traces down anyway. spawnPoint = spawnPoint + Vector(0, 0.5, 0) local validSpawnPoint = ValidateSpawnPoint(spawnPoint, capsuleHeight, capsuleRadius, filter, origin) if validSpawnPoint then return validSpawnPoint end end end return nil end function GetInfestationRequirementsMet(techId, position) local requirementsMet = true -- Check infestation requirements if LookupTechData(techId, kTechDataRequiresInfestation) then if not GetIsPointOnInfestation(position) then requirementsMet = false end -- SA: Note that we don't check kTechDataNotOnInfestation anymore. -- This function should only be used for stuff that REQUIRES infestation. end return requirementsMet end function GetExtents(techId) local extents = LookupTechData(techId, kTechDataMaxExtents) if not extents then extents = Vector(.5, .5, .5) end return extents end function CreateFilter(entity1, entity2) local filter if entity1 and entity2 then filter = EntityFilterTwo(entity1, entity2) elseif entity1 then filter = EntityFilterOne(entity1) elseif entity2 then filter = EntityFilterOne(entity2) end return filter end -- Make sure point isn't blocking attachment entities function GetPointBlocksAttachEntities(origin) local nozzles = GetEntitiesWithinRange("ResourcePoint", origin, 1.5) if table.icount(nozzles) == 0 then local techPoints = GetEntitiesWithinRange("TechPoint", origin, 3.2) if table.icount(techPoints) == 0 then return false end end return true end function GetGroundAtPointWithCapsule(position, extents, physicsGroupMask, filter) local kCapsuleSize = 0.1 local topOffset = extents.y + kCapsuleSize local startPosition = position + Vector(0, topOffset, 0) local endPosition = position - Vector(0, 1000, 0) local trace if filter == nil then trace = Shared.TraceCapsule(startPosition, endPosition, kCapsuleSize, 0, CollisionRep.Move, physicsGroupMask) else trace = Shared.TraceCapsule(startPosition, endPosition, kCapsuleSize, 0, CollisionRep.Move, physicsGroupMask, filter) end -- If we didn't hit anything, then use our existing position. This -- prevents objects from constantly moving downward if they get outside -- of the bounds of the map. if trace.fraction ~= 1 then return trace.endPoint - Vector(0, 2 * kCapsuleSize, 0) else return position end end --[[ * Return the passed in position casted down to the ground. --]] function GetGroundAt(entity, position, physicsGroupMask, filter) if filter then return GetGroundAtPointWithCapsule(position, entity:GetExtents(), physicsGroupMask, filter) end return GetGroundAtPointWithCapsule(position, entity:GetExtents(), physicsGroupMask, EntityFilterOne(entity)) end --[[ * Return the ground below position, using a TraceBox with the given extents, mask and filter. * Returns position if nothing hit. * * filter defaults to nil * extents defaults to a 0.1x0.1x0.1 box (ie, extents 0.05x...) * physicGroupsMask defaults to PhysicsMask.Movement --]] function GetGroundAtPosition(position, filter, physicsGroupMask, extents) physicsGroupMask = physicsGroupMask or PhysicsMask.Movement extents = extents or Vector(0.05, 0.05, 0.05) local topOffset = extents.y + 0.1 local startPosition = position + Vector(0, topOffset, 0) local endPosition = position - Vector(0, 1000, 0) local trace = Shared.TraceBox(extents, startPosition, endPosition, CollisionRep.Move, physicsGroupMask, filter) -- If we didn't hit anything, then use our existing position. This -- prevents objects from constantly moving downward if they get outside -- of the bounds of the map. if trace.fraction ~= 1 then return trace.endPoint - Vector(0, extents.y, 0) else return position end end function GetHoverAt(entity, position, filter) local ground = GetGroundAt(entity, position, PhysicsMask.Movement, filter) local resultY = position.y -- if we have a hover height, use it to find our minimum height above ground, otherwise use zero local minHeightAboveGround = 0 if entity.GetHoverHeight then minHeightAboveGround = entity:GetHoverHeight() end local heightAboveGround = resultY - ground.y -- always snap "up", snap "down" only if not flying if heightAboveGround <= minHeightAboveGround or not entity:GetIsFlying() then resultY = resultY + minHeightAboveGround - heightAboveGround end if resultY ~= position.y then return Vector(position.x, resultY, position.z) end return position end function GetWaypointGroupName(entity) return ConditionalValue(entity:GetIsFlying(), kAirWaypointsGroup, kDefaultWaypointGroup) end function GetTriggerEntity(position, teamNumber) local triggerEntity local minDist local ents = GetEntitiesWithMixinForTeamWithinRange("Live", teamNumber, position, .5) for _, ent in ipairs(ents) do local dist = (ent:GetOrigin() - position):GetLength() if not minDist or (dist < minDist) then triggerEntity = ent minDist = dist end end return triggerEntity end function GetBlockedByUmbra(entity) return entity ~= nil and HasMixin(entity, "Umbra") and entity:GetHasUmbra() end -- TODO: use what is defined in the material file function GetSurfaceFromEntity(entity) if GetIsAlienUnit(entity) then return "organic" elseif GetIsMarineUnit(entity) then return "thin_metal" end return "thin_metal" end function GetSurfaceAndNormalUnderEntity(entity, axis) if not axis then axis = entity:GetCoords().yAxis end local trace = Shared.TraceRay(entity:GetOrigin() + axis * 0.2, entity:GetOrigin() - axis * 10, CollisionRep.Default, PhysicsMask.Bullets, EntityFilterAll() ) if trace.fraction ~= 1 then return trace.surface, trace.normal end return "thin_metal", Vector(0, 1, 0) end -- Trace line to each target to make sure it's not blocked by a wall. -- Returns true/false, along with distance traced function GetWallBetween(startPoint, endPoint, targetEntity) -- Filter out all entities except the targetEntity on this trace. local trace = Shared.TraceRay(startPoint, endPoint, CollisionRep.Move, PhysicsMask.Bullets, EntityFilterOnly(targetEntity)) local dist = (startPoint - endPoint):GetLength() local hitWorld = false -- Hit nothing? if trace.fraction == 1 then hitWorld = false -- Hit the world? elseif not trace.entity then dist = (startPoint - trace.endPoint):GetLength() hitWorld = true elseif trace.entity == targetEntity then -- Hit target entity, return traced distance to it. dist = (startPoint - trace.endPoint):GetLength() hitWorld = false end return hitWorld, dist end -- Get damage type description text for tooltips function DamageTypeDesc(damageType) if table.icount(kDamageTypeDesc) >= damageType then if kDamageTypeDesc[damageType] ~= "" then return string.format("(%s)", kDamageTypeDesc[damageType]) end end return "" end function GetHealthColor(scalar) local kHurtThreshold = .7 local kNearDeadThreshold = .4 local minComponent = 191 local spreadComponent = 255 - minComponent scalar = Clamp(scalar, 0, 1) if scalar <= kNearDeadThreshold then -- Faded red to bright red local r = minComponent + (scalar / kNearDeadThreshold) * spreadComponent return {r, 0, 0} elseif scalar <= kHurtThreshold then local redGreen = minComponent + ( (scalar - kNearDeadThreshold) / (kHurtThreshold - kNearDeadThreshold) ) * spreadComponent return {redGreen, redGreen, 0} else local g = minComponent + ( (scalar - kHurtThreshold) / (1 - kHurtThreshold) ) * spreadComponent return {0, g, 0} end end function GetEntsWithTechId(techIdTable, attachRange, position) local ents = {} local entities if attachRange and position then entities = GetEntitiesWithMixinWithinRange("Tech", position, attachRange) else entities = GetEntitiesWithMixin("Tech") end for _, entity in ipairs(entities) do if table.find(techIdTable, entity:GetTechId()) then table.insert(ents, entity) end end return ents end function GetEntsWithTechIdIsActive(techIdTable, attachRange, position) local ents = {} local entities if attachRange and position then entities = GetEntitiesWithMixinWithinRange("Tech", position, attachRange) else entities = GetEntitiesWithMixin("Tech") end for _, entity in ipairs(entities) do if table.find(techIdTable, entity:GetTechId()) and GetIsUnitActive(entity) then table.insert(ents, entity) end end return ents end function GetFreeAttachEntsForTechId(techId) local freeEnts = {} local attachClass = LookupTechData(techId, kStructureAttachClass) if attachClass ~= nil then for _, ent in ientitylist(Shared.GetEntitiesWithClassname(attachClass)) do if ent ~= nil and ent:GetAttached() == nil then table.insert(freeEnts, ent) end end end return freeEnts end function GetNearestFreeAttachEntity(techId, origin, range) local nearest, nearestDist for _, ent in ipairs(GetFreeAttachEntsForTechId(techId)) do local dist = (ent:GetOrigin() - origin):GetLengthXZ() if (nearest == nil or dist < nearestDist) and (range == nil or dist <= range) then nearest = ent nearestDist = dist end end return nearest end -- Trace until we hit the "inside" of the level or hit nothing. Returns nil if we hit nothing, -- returns the world point of the surface we hit otherwise. Only hit surfaces that are facing -- towards us. -- Input pickVec is either a normalized direction away from the commander that represents where -- the mouse was clicked, or if worldCoordsSpecified is true, it's the XZ position of the order -- given to the minimap. In that case, trace from above it straight down to find the target. -- The last parameter is false if target is for selection, true if it's for building function GetCommanderPickTarget(player, pickVec, worldCoordsSpecified, forBuild, filter, traceThickness, traceType ) traceType = traceType or 'ray' local ogPickVec = Vector() VectorCopy(pickVec, ogPickVec) local startPoint = player:GetOrigin() if worldCoordsSpecified then startPoint = Vector(pickVec.x, startPoint.y + 20, pickVec.z) pickVec = Vector(0, -1, 0) end local trace local mask = ConditionalValue(forBuild, PhysicsMask.CommanderBuild, PhysicsMask.CommanderSelect) local extents = traceType == 'box' and traceThickness and GetDirectedExtentsForDiameter(pickVec, traceThickness) -- keep this method compatible with old api where you couldn't directly pass a filter but only specified if all entities or only the player are to be filtered filter = filter == true and EntityFilterAll() or type(filter) == "function" and filter or EntityFilterOne(player) while true do local endPoint = startPoint + pickVec * 1000 if traceType == 'ray' then trace = Shared.TraceRay(startPoint, endPoint, CollisionRep.Select, mask, filter) else trace = Shared.TraceBox(extents, startPoint, endPoint, CollisionRep.Select, mask, filter) end local hitDistance = (startPoint - trace.endPoint):GetLength() -- Try again if we're inside the surface if(trace.fraction == 0 or hitDistance < .1) then startPoint = startPoint + pickVec elseif(trace.fraction == 1) then -- Nothing found break -- Only hit a target that's facing us (skip surfaces facing away from us) elseif trace.normal.y < 0 then -- Trace again from what we hit startPoint = trace.endPoint + pickVec * 0.01 else -- Hit something (might be the floor) break end end if traceType == 'ray' and traceThickness and not trace.entity then local trace2 = GetCommanderPickTarget(player, ogPickVec, worldCoordsSpecified, forBuild, filter, traceThickness, 'box' ) if trace2.entity then return trace2 end end return trace end function GetAreEnemies(entityOne, entityTwo) return entityOne and entityTwo and HasMixin(entityOne, "Team") and HasMixin(entityTwo, "Team") and ( (entityOne:GetTeamNumber() == kMarineTeamType and entityTwo:GetTeamNumber() == kAlienTeamType) or (entityOne:GetTeamNumber() == kAlienTeamType and entityTwo:GetTeamNumber() == kMarineTeamType) ) end function GetAreFriends(entityOne, entityTwo) return entityOne and entityTwo and HasMixin(entityOne, "Team") and HasMixin(entityTwo, "Team") and entityOne:GetTeamNumber() == entityTwo:GetTeamNumber() end function GetIsMarineUnit(entity) return entity and HasMixin(entity, "Team") and entity:GetTeamType() == kMarineTeamType end function GetIsAlienUnit(entity) return entity and HasMixin(entity, "Team") and entity:GetTeamType() == kAlienTeamType end function GetEnemyTeamNumber(entityTeamNumber) if(entityTeamNumber == kTeam1Index) then return kTeam2Index elseif(entityTeamNumber == kTeam2Index) then return kTeam1Index else return kTeamInvalid end end function SpawnPlayerAtPoint(player, origin, angles) player:SetOrigin(origin) if angles then -- For some reason only the "pitch" adjusts the in game angle, -- so take the yaw (the rotation of the entity) and convert it -- to "roll". Also SetViewAngles does not work here. --From McG: no clue what above note is about. SetViewAngles works without issue --Best guess, at some point this it was broken due to another issue, so this was --never actually broken. player:SetViewAngles(angles) end end --[[ * Returns the passed in point traced down to the ground. Ignores all entities. --]] function DropToFloor(point) local trace = Shared.TraceRay(point, Vector(point.x, point.y - 1000, point.z), CollisionRep.Move, PhysicsMask.All) if trace.fraction < 1 then return trace.endPoint end return point end function GetNearestTechPoint(origin, availableOnly) -- Look for nearest empty tech point to use instead local nearestTechPoint local nearestTechPointDistance = 0 for _, techPoint in ientitylist(Shared.GetEntitiesWithClassname("TechPoint")) do -- Only use unoccupied tech points that are neutral or marked for use with our team local techPointTeamNumber = techPoint:GetTeamNumberAllowed() if not availableOnly or techPoint:GetAttached() == nil then local distance = (techPoint:GetOrigin() - origin):GetLength() if nearestTechPoint == nil or distance < nearestTechPointDistance then nearestTechPoint = techPoint nearestTechPointDistance = distance end end end return nearestTechPoint end function GetNearest(origin, className, teamNumber, filterFunc) assert(type(className) == "string") local nearest local nearestDistance = 0 for _, ent in ientitylist(Shared.GetEntitiesWithClassname(className)) do -- Filter is optional, pass through if there is no filter function defined. if not filterFunc or filterFunc(ent) then if teamNumber == nil or (teamNumber == ent:GetTeamNumber()) then local distance = (ent:GetOrigin() - origin):GetLengthSquared() if nearest == nil or distance < nearestDistance then nearest = ent nearestDistance = distance end end end end return nearest end function GetCanAttackEntity(seeingEntity, targetEntity) return GetCanSeeEntity(seeingEntity, targetEntity, true) end -- Computes line of sight to entity, set considerObstacles to true to check if any other entity is blocking LOS local toEntity = Vector() function GetCanSeeEntity(seeingEntity, targetEntity, considerObstacles, obstaclesFilter) PROFILE("NS2Utility:GetCanSeeEntity") local seen = false -- See if line is in our view cone if targetEntity:GetIsVisible() then local targetOrigin = HasMixin(targetEntity, "Target") and targetEntity:GetEngagementPoint() or targetEntity:GetOrigin() local eyePos = GetEntityEyePos(seeingEntity) -- Not all seeing entity types have a FOV. -- So default to within FOV. local withinFOV = true -- Anything that has the GetFov method supports FOV checking. if seeingEntity.GetFov ~= nil then -- Reuse vector toEntity.x = targetOrigin.x - eyePos.x toEntity.y = targetOrigin.y - eyePos.y toEntity.z = targetOrigin.z - eyePos.z -- Normalize vector local toEntityLength = math.sqrt(toEntity.x * toEntity.x + toEntity.y * toEntity.y + toEntity.z * toEntity.z) if toEntityLength > kEpsilon then toEntity.x = toEntity.x / toEntityLength toEntity.y = toEntity.y / toEntityLength toEntity.z = toEntity.z / toEntityLength end local seeingEntityAngles = GetEntityViewAngles(seeingEntity) local normViewVec = seeingEntityAngles:GetCoords().zAxis local dotProduct = Math.DotProduct(toEntity, normViewVec) local fov = seeingEntity:GetFov() -- players have separate fov for marking enemies as sighted if seeingEntity.GetMinimapFov then fov = seeingEntity:GetMinimapFov(targetEntity) end local halfFov = math.rad(fov / 2) local s = math.acos(dotProduct) withinFOV = s < halfFov end if withinFOV then local filter = EntityFilterAllButIsa("Door")-- EntityFilterAll() if considerObstacles then -- Weapons don't block FOV filter = obstaclesFilter or EntityFilterTwoAndIsa(seeingEntity, targetEntity, "Weapon") end -- See if there's something blocking our view of the entity. local trace = Shared.TraceRay(eyePos, targetOrigin, CollisionRep.LOS, PhysicsMask.All, filter) if trace.fraction == 1 then seen = true end end end return seen end function GetLocations() return EntityListToTable(Shared.GetEntitiesWithClassname("Location")) end function GetLocationForPoint(point, ignoredLocation) local ents = GetLocations() for _, location in ipairs(ents) do if location ~= ignoredLocation and location:GetIsPointInside(point) then return location end end return nil end function GetLocationEntitiesNamed(name) PROFILE("GetLocationEntitiesNamed") local locationEntities = {} if name ~= nil and name ~= "" then local ents = GetLocations() for _, location in ipairs(ents) do if location:GetName() == name then table.insert(locationEntities, location) end end end return locationEntities end function GetPowerPointForLocation(locationName) if locationName == nil or locationName == "" then return nil end local locationId = Shared.GetStringIndex(locationName) local powerPoints = Shared.GetEntitiesWithClassname("PowerPoint") for _, powerPoint in ientitylist(powerPoints) do if powerPoint:GetLocationId() == locationId then return powerPoint end end return nil end -- for performance, cache the lights for each locationName local lightLocationCache = {} function GetLightsForLocation(locationName) PROFILE("GetLightsForLocation") if locationName == nil or locationName == "" then return {} end if lightLocationCache[locationName] then return lightLocationCache[locationName] end local lightList = {} local locationTransforms = Client.locationList[locationName] for _, locationTransform in ipairs(locationTransforms) do for _, renderLight in ipairs(Client.lightList) do if renderLight then local lightOrigin = renderLight:GetCoords().origin local transformedPt = locationTransform:TransformPoint(lightOrigin) if transformedPt.x >= -1 and transformedPt.x < 1.0 and transformedPt.y >= -1 and transformedPt.y < 1.0 and transformedPt.z >= -1 and transformedPt.z < 1.0 then table.insert(lightList, renderLight) end end end end --Log("Total lights %s, lights in %s = %s", #Client.lightList, locationName, #lightList) lightLocationCache[locationName] = lightList return lightList end -- for performance, cache the probes for each locationName local probeLocationCache = {} function GetReflectionProbesForLocation(locationName) PROFILE("GetReflectionProbesForLocation") if locationName == nil or locationName == "" then return {} end if probeLocationCache[locationName] then return probeLocationCache[locationName] end local probeList = {} local locationTransforms = Client.locationList[locationName] for _, locationTransform in ipairs(locationTransforms) do if Client.reflectionProbeList then for _, probe in ipairs(Client.reflectionProbeList) do if probe then local probeOrigin = probe:GetOrigin() local transformedPt = locationTransform:TransformPoint(probeOrigin) if transformedPt.x >= -1 and transformedPt.x < 1.0 and transformedPt.y >= -1 and transformedPt.y < 1.0 and transformedPt.z >= -1 and transformedPt.z < 1.0 then table.insert(probeList, probe) end end end end end probeLocationCache[locationName] = probeList return probeList end local glowPropLocationCache = {} function GetGlowingPropsForLocation(locationName) PROFILE("GetGlowingPropsForLocation") if locationName == nil or locationName == "" then return {} end if glowPropLocationCache[locationName] then return glowPropLocationCache[locationName] end local propList = {} local locationTransforms = Client.locationList[locationName] for _, locationTransform in ipairs(locationTransforms) do for _, propLight in ipairs(Client.glowingProps) do if propLight then local lightOrigin = propLight:GetCoords().origin local transformedPt = locationTransform:TransformPoint(lightOrigin) if transformedPt.x >= -1 and transformedPt.x < 1.0 and transformedPt.y >= -1 and transformedPt.y < 1.0 and transformedPt.z >= -1 and transformedPt.z < 1.0 then table.insert(propList, propLight) end end end end --Log("Total glowing props %s, glow props in %s = %s", #Client.glowingProps, locationName, #propList) glowPropLocationCache[locationName] = propList return propList end -- Iterate over all location name strings, caching the light, reflection probe, and emissive prop -- locations so it's available during the game. (Gets the hitch and GC bump out of the way early.) function PrecacheLightsAndProps() PROFILE("PrecacheLightsAndProps") assert(Client) local idx = 2 -- location names start at 2 for some reason... the string at index 1 is "". while true do local str = Shared.GetString(idx) if str == "" then -- indexing out of bounds yields "". return end GetLightsForLocation(str) GetReflectionProbesForLocation(str) GetGlowingPropsForLocation(str) idx = idx + 1 end end function ClearLights() if Client.lightList ~= nil then for _, light in ipairs(Client.lightList) do Client.DestroyRenderLight(light) end Client.lightList = { } end end local function SetLight(renderLight, intensity, color) if intensity then renderLight:SetIntensity(intensity) end if color then renderLight:SetColor(color) if renderLight:GetType() == RenderLight.Type_AmbientVolume then renderLight:SetDirectionalColor(RenderLight.Direction_Right, color) renderLight:SetDirectionalColor(RenderLight.Direction_Left, color) renderLight:SetDirectionalColor(RenderLight.Direction_Up, color) renderLight:SetDirectionalColor(RenderLight.Direction_Down, color) renderLight:SetDirectionalColor(RenderLight.Direction_Forward, color) renderLight:SetDirectionalColor(RenderLight.Direction_Backward, color) end end end local kMinCommanderLightIntensityScalar = 0.3 local function UpdateRedLightsforPowerPointWorker(self) for renderLight,_ in pairs(self.activeLights) do --Max redness already. local angleRad = 1 * math.pi / 2 -- and scalar goes 0->1 local scalar = math.sin(angleRad) local showCommanderLight = false local player = Client.GetLocalPlayer() if player and player:isa("Commander") then showCommanderLight = true end if showCommanderLight then scalar = math.max(kMinCommanderLightIntensityScalar, scalar) end local intensity = scalar * renderLight.originalIntensity intensity = intensity * self:CheckFlicker(renderLight,PowerPoint.kAuxFlickerChance, scalar) local color if showCommanderLight then color = PowerPoint.kDisabledCommanderColor else color = PowerPoint.kDisabledColor end SetLight(renderLight, intensity, color) end end function NotifyEntitiesWithFilteredCinematics() for _, entity in ipairs(GetEntitiesWithMixin("FilteredCinematicUser")) do entity:OnFilteredCinematicOptionChanged() end end function MinimalParticlesOption_Update() Client.kMinimalParticles = GetAdvancedOption("particles") NotifyEntitiesWithFilteredCinematics() end function ViewModelOption_Update() local player = Client.GetLocalPlayer() if player then local drawviewmodel = GetAdvancedOption("drawviewmodel") local drawviewmodel_a = GetAdvancedOption("drawviewmodel_a") Client.kHideViewModel = drawviewmodel == 1 or drawviewmodel == 2 and ( player:isa("Marine") and not GetAdvancedOption("drawviewmodel_m") or player:isa("Exo") and not GetAdvancedOption("drawviewmodel_exo") or player:isa("Alien") and drawviewmodel_a ~= 0 and ( drawviewmodel_a == 1 or player:isa("Skulk") and not GetAdvancedOption("drawviewmodel_skulk") or player:isa("Gorge") and not GetAdvancedOption("drawviewmodel_gorge") or player:isa("Lerk") and not GetAdvancedOption("drawviewmodel_lerk") or player:isa("Fade") and not GetAdvancedOption("drawviewmodel_fade") or player:isa("Onos") and not GetAdvancedOption("drawviewmodel_onos") ) ) if ClientUI then ClientUI.RestartScripts { "Hud/Marine/GUIMarineHUD", "GUIExoEject" } end NotifyEntitiesWithFilteredCinematics() end end local gLightQuality function Lights_UpdateLightMode() -- Don't attempt to load lowlights for main menu 'map' if Client.fullyLoaded then local LoadData -- Check the light quality options. Check low and minimal options and notify the client if the map doesn't support -- the chosen option. The light lists are initialized in early world (as long as the map has 1 light), so these should be fine to use. local lightQuality = Client.GetOptionInteger("graphics/lightQuality", 2) local hasLowLights = Client.lowLightList and #Client.lowLightList > 0 local hasMinimalLights = Client.minimalLightList and #Client.minimalLightList > 0 --[[ Light quality options 0: Minimal 1: Low 2: High --]] if lightQuality == 0 then if not hasMinimalLights then -- Now try "Low" if not hasLowLights then Shared.Message("Map doesn't support the minimal or low lights option, defaulting to regular lights.") Shared.ConsoleCommand("output " .. "Map doesn't support the minimal or low lights option, defaulting to regular lights.") LoadData = Client.originalLights else Shared.Message("Map doesn't support the minimal lights option, defaulting to low lights.") Shared.ConsoleCommand("output " .. "Map doesn't support the minimal lights option, defaulting to low lights.") LoadData = Client.lowLightList end else LoadData = Client.minimalLightList end elseif lightQuality == 1 then if not hasLowLights then Shared.Message("Map doesn't support the low lights option, defaulting to regular lights.") Shared.ConsoleCommand("output " .. "Map doesn't support the low lights option, defaulting to regular lights.") LoadData = Client.originalLights else LoadData = Client.lowLightList end else LoadData = Client.originalLights end -- Now we finally load/re-load the lights. if LoadData and lightQuality ~= gLightQuality then ClearLights() gLightQuality = lightQuality for _, object in ipairs(LoadData) do LoadMapEntity(object.className, object.groupName, object.values) end lightLocationCache = { } local powerPoints = Shared.GetEntitiesWithClassname("PowerPoint") for _, powerPoint in ientitylist(powerPoints) do if powerPoint.lightHandler then powerPoint.lightHandler:Reset() end end end end end if Client then function ResetLights() for _, renderLight in ipairs(Client.lightList) do renderLight:SetColor(renderLight.originalColor) renderLight:SetIntensity(renderLight.originalIntensity) end end end local kUpVector = Vector(0, 1, 0) function SetPlayerPoseParameters(player, viewModel, headAngles) local coords = player:GetCoords() local pitch = -Math.Wrap(Math.Degrees(headAngles.pitch), -180, 180) local landIntensity = player.landIntensity or 0 local bodyYaw = 0 if player.bodyYaw then bodyYaw = Math.Wrap(Math.Degrees(player.bodyYaw), -180, 180) end local bodyYawRun = 0 if player.bodyYawRun then bodyYawRun = Math.Wrap(Math.Degrees(player.bodyYawRun), -180, 180) end local headCoords = headAngles:GetCoords() local velocity = player:GetVelocityFromPolar() -- Not all players will contrain their movement to the X/Z plane only. if player.GetMoveSpeedIs2D and player:GetMoveSpeedIs2D() then velocity.y = 0 end local x = Math.DotProduct(headCoords.xAxis, velocity) local z = Math.DotProduct(headCoords.zAxis, velocity) local moveYaw = Math.Wrap(Math.Degrees( math.atan2(z,x) ), -180, 180) local moveSpeed = velocity:GetLength() / player:GetMaxSpeed(true) local crouchAmount = HasMixin(player, "CrouchMove") and player:GetCrouchAmount() or 0 if player.ModifyCrouchAnimation then crouchAmount = player:ModifyCrouchAnimation(crouchAmount) end player:SetPoseParam("move_yaw", moveYaw) player:SetPoseParam("move_speed", moveSpeed) player:SetPoseParam("body_pitch", pitch) player:SetPoseParam("body_yaw", bodyYaw) player:SetPoseParam("body_yaw_run", bodyYawRun) player:SetPoseParam("crouch", crouchAmount) player:SetPoseParam("land_intensity", landIntensity) if viewModel then viewModel:SetPoseParam("move_yaw", moveYaw) viewModel:SetPoseParam("move_speed", moveSpeed) viewModel:SetPoseParam("body_pitch", pitch) viewModel:SetPoseParam("body_yaw", bodyYaw) viewModel:SetPoseParam("body_yaw_run", bodyYawRun) viewModel:SetPoseParam("crouch", crouchAmount) viewModel:SetPoseParam("land_intensity", landIntensity) end end -- Pass in position on ground function GetHasRoomForCapsule(extents, position, collisionRep, physicsMask, ignoreEntity, filter) if extents ~= nil then local filter = filter or ConditionalValue(ignoreEntity, EntityFilterOne(ignoreEntity), nil) return not Shared.CollideBox(extents, position, collisionRep, physicsMask, filter) else Print("GetHasRoomForCapsule(): Extents not valid.") end return false end function GetEngagementDistance(entIdOrTechId, trueTechId) local distance = 2 local success = true local techId = entIdOrTechId if not trueTechId then local ent = Shared.GetEntity(entIdOrTechId) if ent and ent.GetTechId then techId = ent:GetTechId() else success = false end end -- local desc if success then distance = LookupTechData(techId, kTechDataEngagementDistance, nil) if distance then -- desc = EnumToString(kTechId, techId) else distance = 1 success = false end end --Print("GetEngagementDistance(%s, %s) => %s => %s, %s", ToString(entIdOrTechId), ToString(trueTechId), ToString(desc), ToString(distance), ToString(success)) return distance, success end function MinimapToWorld(commander, x, y) local heightmap = GetHeightmap() -- Translate minimap coords to world position return Vector(heightmap:GetWorldX(y), 0, heightmap:GetWorldZ(x)) end function GetMinimapPlayableWidth(map) local mapX = map:GetMapX(map:GetOffset().z + map:GetExtents().z) return (mapX - .5) * 2 end function GetMinimapPlayableHeight(map) local mapY = map:GetMapY(map:GetOffset().x - map:GetExtents().x) return (mapY - .5) * 2 end function GetMinimapHorizontalScale(map) local width = GetMinimapPlayableWidth(map) local height = GetMinimapPlayableHeight(map) return ConditionalValue(height > width, width/height, 1) end function GetMinimapVerticalScale(map) local width = GetMinimapPlayableWidth(map) local height = GetMinimapPlayableHeight(map) return ConditionalValue(width > height, height/width, 1) end function GetMinimapNormCoordsFromPlayable(map, playableX, playableY) local playableWidth = GetMinimapPlayableWidth(map) local playableHeight = GetMinimapPlayableHeight(map) return playableX * (1 / playableWidth), playableY * (1 / playableHeight) end -- If we hit something, create an effect (sparks, blood, etc) --[[function TriggerHitEffects(doer, target, origin, surface, melee, extraEffectParams) local tableParams = {} if target and target.GetClassName and target.GetTeamType then tableParams[kEffectFilterClassName] = target:GetClassName() tableParams[kEffectFilterIsMarine] = target:GetTeamType() == kMarineTeamType tableParams[kEffectFilterIsAlien] = target:GetTeamType() == kAlienTeamType end if GetIsPointOnInfestation(origin) then surface = "organic" end if not surface or surface == "" then surface = "metal" end tableParams[kEffectSurface] = surface if origin then tableParams[kEffectHostCoords] = Coords.GetTranslation(origin) else tableParams[kEffectHostCoords] = Coords.GetIdentity() end if doer then tableParams[kEffectFilterDoerName] = doer:GetClassName() end tableParams[kEffectFilterInAltMode] = (melee == true) -- Add in extraEffectParams if specified if extraEffectParams then for key, element in pairs(extraEffectParams) do tableParams[key] = element end end GetEffectManager():TriggerEffects("damage", tableParams, doer) end]]-- local kInfestationSearchRange = 25 function GetIsPointOnInfestation(point) local onInfestation = false -- See if entity is on infestation local infestationEntities = GetEntitiesWithMixinWithinRange("Infestation", point, kInfestationSearchRange) for infestationIndex = 1, #infestationEntities do local infestation = infestationEntities[infestationIndex] if infestation:GetIsPointOnInfestation(point) then onInfestation = true break end end -- count being inside of a gorge tunnel as on infestation if not onInfestation then local tunnelEntities = GetEntitiesWithinRange("Tunnel", point, 40) onInfestation = #tunnelEntities > 0 end return onInfestation end function GetIsPointInGorgeTunnel(point) local tunnelEntities = GetEntitiesWithinRange("Tunnel", point, 40) return #tunnelEntities > 0 and tunnelEntities[1] end function GetIsPointOffInfestation(point) return not GetIsPointOnInfestation(point) end -- Get nearest valid target for commander ability activation, of specified team number nearest specified position. -- Returns nil if none exists in range. function GetActivationTarget(teamNumber, position) local nearestTarget, nearestDist local targets = GetEntitiesWithMixinForTeamWithinRange("Live", teamNumber, position, 2) for _, target in ipairs(targets) do if target:GetIsVisible() and not target:isa("Infestation") then local dist = (target:GetOrigin() - position):GetLength() if nearestTarget == nil or dist < nearestDist then nearestTarget = target nearestDist = dist end end end return nearestTarget end function GetSelectionText(entity, teamNumber) local text = "" local cloakedText = "" if entity.GetIsCamouflaged and entity:GetIsCamouflaged() then cloakedText = " (" .. Locale.ResolveString("CAMOUFLAGED") .. ")" elseif HasMixin(entity, "Cloakable") and entity:GetIsCloaked() then cloakedText = " (" .. Locale.ResolveString("CLOAKED") .. ")" end local maturity = "" if HasMixin(entity, "Maturity") then if entity:GetMaturityLevel() == kMaturityLevel.Grown then maturity = Locale.ResolveString("GROWN") .. " " end end if entity:isa("Player") and entity:GetIsAlive() then local playerName = Scoreboard_GetPlayerData(entity:GetClientIndex(), "Name") if playerName ~= nil then text = string.format("%s%s", playerName, cloakedText) end else -- Don't show built % for enemies, show health instead local enemyTeam = HasMixin(entity, "Team") and GetEnemyTeamNumber(entity:GetTeamNumber()) == teamNumber local techId = entity:GetTechId() local secondaryText = "" if HasMixin(entity, "Construct") and not entity:GetIsBuilt() then secondaryText = Locale.ResolveString("CONSTRUCT_UNBUILT") elseif HasMixin(entity, "PowerConsumer") and entity:GetRequiresPower() and not entity:GetIsPowered() then secondaryText = Locale.ResolveString("CONSTRUCT_UNPOWERED") elseif entity:isa("Whip") then if not entity:GetIsRooted() then secondaryText = Locale.ResolveString("CONSTRUCT_UNROOTED") end end local primaryText = GetDisplayNameForTechId(techId) if entity.GetDescription then primaryText = entity:GetDescription() end text = string.format("%s%s%s%s", maturity, secondaryText, primaryText, cloakedText) end return text end function GetCostForTech(techId) return LookupTechData(techId, kTechDataCostKey, 0) end --[[ * Adds additional points to the path to ensure that no two points are more than * maxDistance apart. --]] function SubdividePathPoints(points, maxDistance) PROFILE("NS2Utility:SubdividePathPoints") local numPoints = #points local i = 1 while i < numPoints do local point1 = points[i] local point2 = points[i + 1] -- If the distance between two points is large, add intermediate points local delta = point2 - point1 local distance = delta:GetLength() local numNewPoints = math.floor(distance / maxDistance) local p = 0 for j=1,numNewPoints do local f = j / numNewPoints local newPoint = point1 + delta * f if (table.find(points, newPoint) == nil) then i = i + 1 table.insert( points, i, newPoint ) p = p + 1 end end i = i + 1 numPoints = numPoints + p end end local function GetTraceEndPoint(src, dst, trace, skinWidth) local delta = dst - src local distance = delta:GetLength() local fraction = trace.fraction fraction = Clamp( fraction + (fraction - 1.0) * skinWidth / distance, 0.0, 1.0 ) return src + delta * fraction end function GetFriendlyFire() return false end local allowedWarmUpStrcutures = { "Hydra", "Clog", "TunnelEntrance" } function GetValidTargetInWarmUp(target) for _, classname in ipairs(allowedWarmUpStrcutures) do if target:isa(classname) then return true end end return not HasMixin(target, "Construct") end -- All damage is routed through here. function CanEntityDoDamageTo(attacker, target, cheats, devMode, friendlyFire, damageType) if not GetGameInfoEntity():GetGameStarted() and not GetWarmupActive() then return false end if target:isa("Clog") then return true end if not HasMixin(target, "Live") then return false end if GetWarmupActive() and not GetValidTargetInWarmUp(target) then return false end if target:isa("ARC") and damageType == kDamageType.Splash then return true end if not target:GetCanTakeDamage() then return false end if target == nil or (target.GetDarwinMode and target:GetDarwinMode()) then return false elseif cheats or devMode then return true elseif attacker == nil then return true end -- You can always do damage to yourself. if attacker == target then return true end -- Command stations can kill even friendlies trapped inside. if attacker ~= nil and attacker:isa("CommandStation") then return true end -- Your own grenades can hurt you. if attacker:isa("Grenade") then local owner = attacker:GetOwner() if owner and owner:GetId() == target:GetId() then return true end end -- Same teams not allowed to hurt each other unless friendly fire enabled. local teamsOK = true if attacker ~= nil then teamsOK = GetAreEnemies(attacker, target) or friendlyFire end -- Allow damage of own stuff when testing. return teamsOK end function TraceMeleeBox(weapon, eyePoint, axis, extents, range, mask, filter) -- We make sure that the given range is actually the start/end of the melee volume by moving forward the -- starting point with the extents (and some extra to make sure we don't hit anything behind us), -- as well as moving the endPoint back with the extents as well (making sure we dont trace backwards) -- Make sure we don't hit anything behind us. local startPoint = eyePoint + axis * weapon:GetMeleeOffset() local endPoint = eyePoint + axis * math.max(0, range) local trace = Shared.TraceBox(extents, startPoint, endPoint, CollisionRep.Damage, mask, filter) return trace, startPoint, endPoint end local function IsPossibleMeleeTarget(player, target, teamNumber) if target and HasMixin(target, "Live") and target:GetCanTakeDamage() and target:GetIsAlive() then if HasMixin(target, "Team") and teamNumber == target:GetTeamNumber() then return true end end return false end --[[ * Priority function for melee target. * * Returns newTarget it it is a better target, otherwise target. * * Default priority: closest enemy player, otherwise closest enemy melee target --]] local function IsBetterMeleeTarget(weapon, player, newTarget, target) local teamNumber = GetEnemyTeamNumber(player:GetTeamNumber()) if IsPossibleMeleeTarget(player, newTarget, teamNumber) then if not target or (not target:isa("Player") and newTarget:isa("Player")) then return true end end return false end -- melee targets must be in front of the player local function IsNotBehind(fromPoint, hitPoint, forwardDirection) local startPoint = fromPoint + forwardDirection * 0.1 local toHitPoint = hitPoint - startPoint toHitPoint:Normalize() return forwardDirection:DotProduct(toHitPoint) > 0 end -- The order in which we do the traces - middle first, the corners last. local kTraceOrder = { 4, 1, 3, 5, 7, 0, 2, 6, 8 } --[[ * Checks if a melee capsule would hit anything. Does not actually carry * out any attack or inflict any damage. * * Target prio algorithm: * First, a small box (the size of a rifle but or a skulks head) is moved along the view-axis, colliding * with everything. The endpoint of this trace is the attackEndPoind * * Second, a new trace to the attackEndPoint using the full size of the melee box is done. This trace * is done WITHOUT REGARD FOR GEOMETRY, and uses an entity-filter that tracks targets as they come, * and prioritizes them. * * Basically, inside the range to the attackEndPoint, the attacker chooses the "best" target freely. --]] --[[ * Bullets are small and will hit exactly where you looked. * Melee, however, is different. We select targets from a volume, and we expect the melee'er to be able * to basically select the "best" target from that volume. * Right now, the Trace methods available is limited (spheres or world-axis aligned boxes), so we have to * compensate by doing multiple traces. * We specify the size of the width and base height and its range. * Then we split the space into 9 parts and trace/select all of them, choose the "best" target. If no good target is found, * we use the middle trace for effects. --]] function CheckMeleeCapsule(weapon, player, damage, range, optionalCoords, traceRealAttack, scale, priorityFunc, filter, mask) scale = scale or 1 local eyePoint = player:GetEyePos() -- if not teamNumber then -- teamNumber = GetEnemyTeamNumber( player:GetTeamNumber() ) -- end mask = mask or PhysicsMask.Melee local coords = optionalCoords or player:GetViewAngles():GetCoords() local axis = coords.zAxis local forwardDirection = Vector(coords.zAxis) forwardDirection.y = 0 if forwardDirection:GetLength() ~= 0 then forwardDirection:Normalize() end local width, height = weapon:GetMeleeBase() width = scale * width height = scale * height --[[ if Client then Client.DebugCapsule(eyePoint, eyePoint + axis * range, width, 0, 3) end --]] -- extents defines a world-axis aligned box, so x and z must be the same. local extents = Vector(width / 6, height / 6, width / 6) if not filter then filter = EntityFilterOne(player) end local middleTrace,middleStart local target,endPoint,surface,startPoint if not priorityFunc then priorityFunc = IsBetterMeleeTarget end local selectedTrace for _, pointIndex in ipairs(kTraceOrder) do local dx = pointIndex % 3 - 1 local dy = math.floor(pointIndex / 3) - 1 local point = eyePoint + coords.xAxis * (dx * width / 3) + coords.yAxis * (dy * height / 3) local trace, sp, ep = TraceMeleeBox(weapon, point, axis, extents, range, mask, filter) if dx == 0 and dy == 0 then middleTrace, middleStart = trace, sp selectedTrace = trace end if trace.entity and priorityFunc(weapon, player, trace.entity, target) and IsNotBehind(eyePoint, trace.endPoint, forwardDirection) then selectedTrace = trace target = trace.entity startPoint = sp endPoint = trace.endPoint surface = trace.surface surface = GetIsAlienUnit(target) and "organic" or "metal" if GetAreEnemies(player, target) then if target:isa("Alien") then surface = "organic" elseif target:isa("Marine") then surface = "flesh" else if HasMixin(target, "Team") then if target:GetTeamType() == kAlienTeamType then surface = "organic" else surface = "metal" end end end end end end -- if we have not found a target, we use the middleTrace to possibly bite a wall (or when cheats are on, teammates) target = target or middleTrace.entity endPoint = endPoint or middleTrace.endPoint surface = surface or middleTrace.surface startPoint = startPoint or middleStart local direction = target and (endPoint - startPoint):GetUnit() or coords.zAxis return target ~= nil or middleTrace.fraction < 1, target, endPoint, direction, surface, startPoint, selectedTrace end local kNumMeleeZones = 3 local kRangeMult = 0-- 0.15 function PerformGradualMeleeAttack(weapon, player, damage, range, optionalCoords, altMode, filter) local didHit, target, endPoint, direction, surface local didHitNow local damageMult = 1 local stepSize = 1 / kNumMeleeZones local trace for i = 1, kNumMeleeZones do local attackRange = range * (1 - (i-1) * kRangeMult) didHitNow, target, endPoint, direction, surface = CheckMeleeCapsule(weapon, player, damage, range, optionalCoords, true, i * stepSize, nil, filter) didHit = didHit or didHitNow if target and didHitNow then if target:isa("Player") then damageMult = 1 - (i - 1) * stepSize end break end end if didHit then weapon:DoDamage(damage * damageMult, target, endPoint, direction, surface, altMode) end return didHit, target, endPoint, direction, surface, trace end --[[ * Does an attack with a melee capsule. --]] function AttackMeleeCapsule(weapon, player, damage, range, optionalCoords, altMode, filter) local targets = {} local didHit, target, endPoint, direction, surface, startPoint, trace if not filter then filter = EntityFilterTwo(player, weapon) end -- loop upto 20 times just to go through any soft targets. -- Stops as soon as nothing is hit or a non-soft target is hit for i = 1, 20 do local traceFilter = function(test) return EntityFilterList(targets)(test) or filter(test) end -- Enable tracing on this capsule check, last argument. didHit, target, endPoint, direction, surface, startPoint, trace = CheckMeleeCapsule(weapon, player, damage, range, optionalCoords, true, 1, nil, traceFilter) local alreadyHitTarget = target ~= nil and table.icontains(targets, target) if didHit and not alreadyHitTarget then weapon:DoDamage(damage, target, endPoint, direction, surface, altMode) end if target and not alreadyHitTarget then table.insert(targets, target) end if not target or not HasMixin(target, "SoftTarget") then break end end HandleHitregAnalysis(player, startPoint, endPoint, trace) local lastTarget = targets[#targets] -- Handle Stats if Server then local parent = weapon and weapon.GetParent and weapon:GetParent() if parent and weapon.GetTechId then -- Drifters, buildings and teammates don't count towards accuracy as hits or misses if (lastTarget and lastTarget:isa("Player") and GetAreEnemies(parent, lastTarget)) or lastTarget == nil then local steamId = parent:GetSteamId() if steamId then StatsUI_AddAccuracyStat(steamId, weapon:GetTechId(), lastTarget ~= nil, lastTarget and lastTarget:isa("Onos"), weapon:GetParent():GetTeamNumber()) end end end end return didHit, lastTarget, endPoint, surface end local kExplosionDirections = { Vector(0, 1, 0), Vector(0, -1, 0), Vector(1, 0, 0), Vector(-1, 0, 0), Vector(1, 0, 0), Vector(0, 0, 1), Vector(0, 0, -1), } function CreateExplosionDecals(triggeringEntity, effectName) effectName = effectName or "explosion_decal" local startPoint = triggeringEntity:GetOrigin() + Vector(0, 0.2, 0) for i = 1, #kExplosionDirections do local direction = kExplosionDirections[i] local trace = Shared.TraceRay(startPoint, startPoint + direction * 2, CollisionRep.Damage, PhysicsMask.Bullets, EntityFilterAll()) if trace.fraction ~= 1 then local coords = Coords.GetTranslation(trace.endPoint) coords.yAxis = trace.normal coords.zAxis = trace.normal:GetPerpendicular() coords.xAxis = coords.zAxis:CrossProduct(coords.yAxis) triggeringEntity:TriggerEffects(effectName, {effecthostcoords = coords}) end end end function BuildClassToGrid() local ClassToGrid = { } ClassToGrid["Undefined"] = { 5, 8 } ClassToGrid["TechPoint"] = { 1, 1 } ClassToGrid["ResourcePoint"] = { 2, 1 } ClassToGrid["Door"] = { 3, 1 } ClassToGrid["DoorLocked"] = { 4, 1 } ClassToGrid["DoorWelded"] = { 5, 1 } ClassToGrid["Grenade"] = { 6, 1 } ClassToGrid["PowerPoint"] = { 7, 1 } ClassToGrid["UnsocketedPowerPoint"] = { 8, 8 } ClassToGrid["Scan"] = { 6, 8 } ClassToGrid["HighlightWorld"] = { 4, 6 } ClassToGrid["ReadyRoomPlayer"] = { 1, 2 } ClassToGrid["Marine"] = { 1, 2 } ClassToGrid["Exo"] = { 2, 2 } ClassToGrid["JetpackMarine"] = { 3, 2 } ClassToGrid["Exo"] = { 2, 2 } ClassToGrid["MAC"] = { 4, 2 } ClassToGrid["CommandStationOccupied"] = { 5, 2 } ClassToGrid["CommandStationL2Occupied"] = { 6, 2 } ClassToGrid["CommandStationL3Occupied"] = { 7, 2 } ClassToGrid["Death"] = { 8, 2 } ClassToGrid["Skulk"] = { 1, 3 } ClassToGrid["Gorge"] = { 2, 3 } ClassToGrid["Lerk"] = { 3, 3 } ClassToGrid["Fade"] = { 4, 3 } ClassToGrid["Onos"] = { 5, 3 } ClassToGrid["Drifter"] = { 6, 3 } ClassToGrid["HiveOccupied"] = { 7, 3 } ClassToGrid["BoneWall"] = { 8, 3 } ClassToGrid["CommandStation"] = { 1, 4 } ClassToGrid["Extractor"] = { 4, 4 } ClassToGrid["Sentry"] = { 5, 4 } ClassToGrid["ARC"] = { 6, 4 } ClassToGrid["ARCDeployed"] = { 7, 4 } ClassToGrid["SentryBattery"] = { 8, 4 } ClassToGrid["InfantryPortal"] = { 1, 5 } ClassToGrid["Armory"] = { 2, 5 } ClassToGrid["AdvancedArmory"] = { 3, 5 } ClassToGrid["AdvancedArmoryModule"] = { 4, 5 } ClassToGrid["PhaseGate"] = { 5, 5 } ClassToGrid["Observatory"] = { 6, 5 } ClassToGrid["RoboticsFactory"] = { 7, 5 } ClassToGrid["ArmsLab"] = { 8, 5 } ClassToGrid["PrototypeLab"] = { 4, 5 } ClassToGrid["HiveBuilding"] = { 1, 6 } ClassToGrid["Hive"] = { 2, 6 } ClassToGrid["Infestation"] = { 4, 6 } ClassToGrid["Harvester"] = { 5, 6 } ClassToGrid["Hydra"] = { 6, 6 } ClassToGrid["Egg"] = { 7, 6 } ClassToGrid["Embryo"] = { 7, 6 } ClassToGrid["Shell"] = { 8, 6 } ClassToGrid["Spur"] = { 7, 7 } ClassToGrid["Veil"] = { 8, 7 } ClassToGrid["Crag"] = { 1, 7 } ClassToGrid["Whip"] = { 3, 7 } ClassToGrid["Shade"] = { 5, 7 } ClassToGrid["Shift"] = { 6, 7 } ClassToGrid["WaypointMove"] = { 1, 8 } ClassToGrid["WaypointDefend"] = { 2, 8 } ClassToGrid["TunnelEntrance"] = { 3, 8 } ClassToGrid["PlayerFOV"] = { 4, 8 } ClassToGrid["MoveOrder"] = { 1, 8 } ClassToGrid["BuildOrder"] = { 2, 8 } ClassToGrid["AttackOrder"] = { 2, 8 } ClassToGrid["SensorBlip"] = { 5, 8 } ClassToGrid["EtherealGate"] = { 8, 1 } ClassToGrid["Player"] = { 7, 8 } return ClassToGrid end --[[ * Returns Column and Row to find the minimap icon for the passed in class. --]] function GetSpriteGridByClass(class, classToGrid) -- This really shouldn't happen but lets return something just in case. if not classToGrid[class] then Print("No sprite defined for minimap icon %s", class) Print(debug.traceback()) return 4, 8 end return classToGrid[class][1], classToGrid[class][2] end --[[ * Non-linear egg spawning. Eggs spawn slower the more of them you have, but speed up with more players. * Pass in the number of players currently on your team, and the number of egg that this will be (ie, with * no eggs, pass in 1 to find out how long it will take for the first egg to spawn in). --]] function CalcEggSpawnTime(numPlayers, eggNumber, numDeadPlayers) local clampedEggNumber = Clamp(eggNumber, 1, kAlienEggsPerHive) local clampedNumPlayers = Clamp(numPlayers, 1, kMaxPlayers/2) local calcEggScalar = math.sin(((clampedEggNumber - 1)/kAlienEggsPerHive) * (math.pi / 2)) * kAlienEggSinScalar local calcSpawnTime = kAlienEggMinSpawnTime + (calcEggScalar / clampedNumPlayers) * kAlienEggPlayerScalar return Clamp(calcSpawnTime, kAlienEggMinSpawnTime, kAlienEggMaxSpawnTime) end gEventTiming = {} function LogEventTiming() if Shared then table.insert(gEventTiming, Shared.GetTime()) end end function GetEventTimingString(seconds) local logTime = Shared.GetTime() - seconds local count = 0 for _, time in ipairs(gEventTiming) do if time >= logTime then count = count + 1 end end return string.format("%d events in past %d seconds (%.3f avg delay).", count, seconds, seconds/count) end function GetIsVortexed(entity) return entity and HasMixin(entity, "VortexAble") and entity:GetIsVortexed() end function GetIsNanoShielded(entity) return entity and HasMixin(entity, "NanoShieldAble") and entity:GetIsNanoShielded() end if Client then local kMaxPitch = Math.Radians(89.9) function ClampInputPitch(input) input.pitch = Clamp(input.pitch, -kMaxPitch, kMaxPitch) end -- &ol& = order location -- &ot& = order target entity name function TranslateHintText(text) local translatedText = text local player = Client.GetLocalPlayer() if player and HasMixin(player, "Orders") then local order = player:GetCurrentOrder() if order then local orderDestination = order:GetLocation() local location = GetLocationForPoint(orderDestination) local orderLocationName = location and location:GetName() or "" translatedText = string.gsub(translatedText, "&ol&", orderLocationName) local orderTargetEntityName = LookupTechData(order:GetParam(), kTechDataDisplayName, "<entity name>") translatedText = string.gsub(translatedText, "&ot&", orderTargetEntityName) end end return translatedText end end gSpeedDebug = nil function SetSpeedDebugText(text, ...) if gSpeedDebug then local result = string.format(text, ...) gSpeedDebug:SetDebugText(result) end end -- returns pairs of impact point, entity function TraceBullet(player, weapon, startPoint, direction, throughHallucinations, throughUnits) local hitInfo = {} local lastHitEntity = player local endPoint = startPoint + direction * 1000 local maxTraces = 3 for i = 1, maxTraces do local trace = Shared.TraceRay(startPoint, endPoint, CollisionRep.Damage, PhysicsMask.Bullets, EntityFilterTwo(lastHitEntity, weapon)) if trace.fraction ~= 1 then table.insert(hitInfo, { EndPoint = trace.endPoint, Entity = trace.entity } ) if trace.entity and (trace.entity:isa("Hallucination") and throughHallucinations == true) or throughUnits == true then startPoint = Vector(trace.endPoint) lastHitEntity = trace.entity else break end else break end end return hitInfo end -- add comma to separate thousands function CommaValue(amount) local formatted = "" if amount ~= nil then formatted = amount while true do local k formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2') if (k==0) then break end end end return formatted end --[[ * Trim off unnecessary path and extension. --]] function GetTrimmedMapName(mapName) if mapName == nil then return "" end for trimmedName in string.gmatch(mapName, [[\/(.+)\.level]]) do return trimmedName end return mapName end -- Look for "BIND_" in the string and substitute with key to press -- ie, "Press the BIND_Buy key to evolve to a new lifeform or to gain new upgrades." => "Press the B key to evolve to a new lifeform or to gain new upgrades." function SubstituteBindStrings(tipString) local substitutions = { } for word in string.gmatch(tipString, "BIND_(%a+)") do local bind = GetPrettyInputName(word) if type(bind) == "string" then tipString = string.gsub(tipString, "BIND_" .. word, bind) -- If the input name is not found, replace the BIND_InputName with just InputName as a fallback. else tipString = string.gsub(tipString, "BIND_" .. word, word) end end return tipString end -- Look up texture coordinates in kInventoryIconsTexture -- Used for death messages, inventory icons, and abilities drawn in the alien "energy ball" gTechIdPosition = nil function GetTexCoordsForTechId(techId) local x1 = 0 local y1 = 0 local x2 = kInventoryIconTextureWidth local y2 = kInventoryIconTextureHeight if not gTechIdPosition then gTechIdPosition = {} -- marine weapons gTechIdPosition[kTechId.Rifle] = kDeathMessageIcon.Rifle gTechIdPosition[kTechId.HeavyMachineGun] = kDeathMessageIcon.HeavyMachineGun gTechIdPosition[kTechId.Pistol] = kDeathMessageIcon.Pistol gTechIdPosition[kTechId.Axe] = kDeathMessageIcon.Axe gTechIdPosition[kTechId.Shotgun] = kDeathMessageIcon.Shotgun gTechIdPosition[kTechId.Flamethrower] = kDeathMessageIcon.Flamethrower gTechIdPosition[kTechId.GrenadeLauncher] = kDeathMessageIcon.GL gTechIdPosition[kTechId.Welder] = kDeathMessageIcon.Welder gTechIdPosition[kTechId.LayMines] = kDeathMessageIcon.Mine gTechIdPosition[kTechId.ClusterGrenade] = kDeathMessageIcon.ClusterGrenade gTechIdPosition[kTechId.GasGrenade] = kDeathMessageIcon.GasGrenade gTechIdPosition[kTechId.PulseGrenade] = kDeathMessageIcon.PulseGrenade gTechIdPosition[kTechId.Exo] = kDeathMessageIcon.Crush gTechIdPosition[kTechId.PowerSurge] = kDeathMessageIcon.EMPBlast -- alien abilities gTechIdPosition[kTechId.Bite] = kDeathMessageIcon.Bite gTechIdPosition[kTechId.Leap] = kDeathMessageIcon.Leap gTechIdPosition[kTechId.Parasite] = kDeathMessageIcon.Parasite gTechIdPosition[kTechId.Xenocide] = kDeathMessageIcon.Xenocide gTechIdPosition[kTechId.Spit] = kDeathMessageIcon.Spit gTechIdPosition[kTechId.BuildAbility] = kDeathMessageIcon.BuildAbility gTechIdPosition[kTechId.Spray] = kDeathMessageIcon.Spray gTechIdPosition[kTechId.BileBomb] = kDeathMessageIcon.BileBomb gTechIdPosition[kTechId.WhipBomb] = kDeathMessageIcon.WhipBomb gTechIdPosition[kTechId.BabblerAbility] = kDeathMessageIcon.BabblerAbility gTechIdPosition[kTechId.LerkBite] = kDeathMessageIcon.LerkBite gTechIdPosition[kTechId.Spikes] = kDeathMessageIcon.Spikes gTechIdPosition[kTechId.Spores] = kDeathMessageIcon.SporeCloud gTechIdPosition[kTechId.Umbra] = kDeathMessageIcon.Umbra gTechIdPosition[kTechId.Swipe] = kDeathMessageIcon.Swipe gTechIdPosition[kTechId.Stab] = kDeathMessageIcon.Stab gTechIdPosition[kTechId.Blink] = kDeathMessageIcon.Blink gTechIdPosition[kTechId.Vortex] = kDeathMessageIcon.Vortex gTechIdPosition[kTechId.MetabolizeEnergy] = kDeathMessageIcon.Metabolize gTechIdPosition[kTechId.MetabolizeHealth] = kDeathMessageIcon.Metabolize gTechIdPosition[kTechId.Gore] = kDeathMessageIcon.Gore gTechIdPosition[kTechId.Stomp] = kDeathMessageIcon.Stomp gTechIdPosition[kTechId.BoneShield] = kDeathMessageIcon.BoneShield gTechIdPosition[kTechId.GorgeTunnelTech] = kDeathMessageIcon.GorgeTunnel end local position = gTechIdPosition[techId] if position then y1 = (position - 1) * kInventoryIconTextureHeight y2 = y1 + kInventoryIconTextureHeight end return x1, y1, x2, y2 end -- Ex: input.commands = RemoveMoveCommand( input.commands, Move.PrimaryAttack ) function RemoveMoveCommand( commands, moveMask ) local negMask = bit.bxor(0xFFFFFFFF, moveMask) return bit.band(commands, negMask) end function HasMoveCommand( commands, moveMask ) return bit.band( commands, moveMask ) ~= 0 end function AddMoveCommand( commands, moveMask ) return bit.bor(commands, moveMask) end function GetShellLevel(teamNumber) if teamNumber then local teamInfo = GetTeamInfoEntity(teamNumber) if teamInfo then return teamInfo.shellLevel or 0 end end return 0 end function GetSpurLevel(teamNumber) if teamNumber then local teamInfo = GetTeamInfoEntity(teamNumber) if teamInfo then return teamInfo.spurLevel or 0 end end return 0 end function GetVeilLevel(teamNumber) if teamNumber then local teamInfo = GetTeamInfoEntity(teamNumber) if teamInfo then return teamInfo.veilLevel or 0 end end return 0 end function GetSelectablesOnScreen(commander, className, minPos, maxPos) assert(Client) if not className then className = "Entity" end local selectables = {} if not minPos then minPos = Vector(0,0,0) end if not maxPos then maxPos = Vector(Client.GetScreenWidth(), Client.GetScreenHeight(), 0) end -- Check own team first, if no entities are found, then let the marquee select enemies local team = { commander:GetTeamNumber(), ConditionalValue(commander:GetTeamNumber() == kTeam1Index, kTeam2Index, kTeam1Index) } for _, teamNumber in ipairs(team) do for _, selectable in ipairs(GetEntitiesWithMixinForTeam("Selectable", teamNumber)) do if selectable:isa(className) then local screenPos = Client.WorldToScreen(selectable:GetOrigin()) if screenPos.x >= minPos.x and screenPos.x <= maxPos.x and screenPos.y >= minPos.y and screenPos.y <= maxPos.y then table.insert(selectables, selectable) end end end if #selectables > 0 then break end end return selectables end function GetInstalledMapList() local matchingFiles = { } Shared.GetMatchingFileNames("maps/*.level", false, matchingFiles) local mapNames = { } local mapFiles = { } for _, mapFile in ipairs(matchingFiles) do local _, _, filename = string.find(mapFile, "maps/(.*).level") local mapname = string.gsub(filename, 'ns2_', '', 1):gsub("^%l", string.upper) local tagged,_ = string.match(filename, "ns2_", 1) if tagged ~= nil then table.insert(mapNames, mapname) table.insert(mapFiles, {["name"] = mapname, ["fileName"] = filename}) end end return mapNames, mapFiles end -- TODO: move to Utility.lua function EntityFilterList(list) return function(test) return table.icontains(list, test) end end -- avoid problem with client generating a hit while server fails by shrinking client-side bullets a bit local kClientSideCaliberAdjustment = 0.00 function GetBulletTargets(startPoint, endPoint, spreadDirection, bulletSize, filter) local targets = {} local hitPoints = {} local trace if Client then if bulletSize < 2*kClientSideCaliberAdjustment then bulletSize = bulletSize / 2 else bulletSize = bulletSize - kClientSideCaliberAdjustment end end for i = 1, 20 do local traceFilter if filter then traceFilter = function(test) return EntityFilterList(targets)(test) or filter(test) end else traceFilter = EntityFilterList(targets) end trace = Shared.TraceRay(startPoint, endPoint, CollisionRep.Damage, PhysicsMask.Bullets, traceFilter) if not trace.entity then -- Limit the box trace to the point where the ray hit as an optimization. local boxTraceEndPoint = trace.fraction ~= 1 and trace.endPoint or endPoint local extents = GetDirectedExtentsForDiameter(spreadDirection, bulletSize) trace = Shared.TraceBox(extents, startPoint, boxTraceEndPoint, CollisionRep.Damage, PhysicsMask.Bullets, traceFilter) end if trace.entity and not table.icontains(targets, trace.entity) then table.insert(targets, trace.entity) table.insert(hitPoints, trace.endPoint) end local deadTarget = trace.entity and HasMixin(trace.entity, "Live") and not trace.entity:GetIsAlive() local softTarget = trace.entity and HasMixin(trace.entity, "SoftTarget") local ragdollTarget = trace.entity and trace.entity:isa("Ragdoll") if (not trace.entity or not (deadTarget or softTarget or ragdollTarget)) or trace.fraction == 1 then break end -- if (deadTarget) then Log("Dead %s target, bullet is going forward", EntityToString(trace.entity)) end -- if (soft) then Log("Soft %s target, bullet is going forward", EntityToString(trace.entity)) end -- if (ragdollTarget) then Log("Ragdoll %s target, bullet is going forward", EntityToString(trace.entity)) end end return targets, trace, hitPoints end local kAlienStructureMoveSound = PrecacheAsset("sound/NS2.fev/alien/infestation/build") function UpdateAlienStructureMove(self, deltaTime) if Server then local currentOrder = self:GetCurrentOrder() if GetIsUnitActive(self) and currentOrder and currentOrder:GetType() == kTechId.Move and (not HasMixin(self, "TeleportAble") or not self:GetIsTeleporting()) then local speed = self:GetMaxSpeed() if self.shiftBoost then speed = speed * kShiftStructurespeedScalar end self:MoveToTarget(PhysicsMask.AIMovement, currentOrder:GetLocation(), speed, deltaTime) if not self.distanceMoved then self.distanceMoved = 0 end self.distanceMoved = self.distanceMoved + speed * deltaTime if self.distanceMoved > 1 then if HasMixin(self, "StaticTarget") then self:StaticTargetMoved() end self.distanceMoved = 0 end if self:IsTargetReached(currentOrder:GetLocation(), kAIMoveOrderCompleteDistance) then self:CompletedCurrentOrder() self.moving = false self.distanceMoved = 0 else self.moving = true end else self.moving = false self.distanceMoved = 0 end if HasMixin(self, "Obstacle") then if currentOrder and currentOrder:GetType() == kTechId.Move then self:RemoveFromMesh() if not self.removedMesh then self.removedMesh = true self:OnObstacleChanged() end elseif self.removedMesh then self:AddToMesh() self.removedMesh = false end end elseif Client then if self.clientMoving ~= self.moving then if self.moving then Shared.PlaySound(self, kAlienStructureMoveSound, 1) else Shared.StopSound(self, kAlienStructureMoveSound) end self.clientMoving = self.moving end if self.moving and (not self.timeLastDecalCreated or self.timeLastDecalCreated + 1.1 < Shared.GetTime() ) then self:TriggerEffects("structure_move") self.timeLastDecalCreated = Shared.GetTime() end end end function GetCommanderLogoutAllowed() return true --[[ local gameState = kGameState.PreGame local gameStateDuration = 0 if Server then local gamerules = GetGamerules() if gamerules then gameState = gamerules:GetGameState() gameStateDuration = gamerules:GetGameTimeChanged() end else local gameInfo = GetGameInfoEntity() if gameInfo then gameState = gameInfo:GetState() gameStateDuration = math.max(0, Shared.GetTime() - gameInfo:GetStartTime()) end end return ( gameState ~= kGameState.Countdown and gameState ~= kGameState.Started ) or gameStateDuration >= kCommanderMinTime --]] end function ValidateShoulderPad( variants ) local idx = Client.GetOptionInteger("shoulderPad", 1) if not kShoulderPad2ItemId[idx] then Client.SetOptionInteger("shoulderPad", 1) idx = 1 elseif not GetHasShoulderPad(idx) then idx = 1 end variants.shoulderPadIndex = idx end function ValidateVariant( variants, variantType, enum, enumData ) local idx = Client.GetOptionInteger(variantType, 1) local pvIdx = idx --cache incase not owned, for logging if not rawget( enum, idx ) then -- if it's an invalid id Client.SetOptionInteger(variantType, 1) -- fix it idx = 1 HPrint( "Invalid ID on " .. variantType ) elseif not GetHasVariant( enumData, idx ) then -- if they don't have access to this idx = 1 -- don't let them use it HPrint( "No access to " .. variantType .. " " .. pvIdx ) end variants[variantType] = idx end function GetAndSetVariantOptions() local variants = {} variants.sexType = Client.GetOptionString("sexType", "Male") ValidateShoulderPad(variants) ValidateVariant(variants, "marineVariant", kMarineVariants, kMarineVariantsData) ValidateVariant(variants, "skulkVariant", kSkulkVariants, kSkulkVariantsData) ValidateVariant(variants, "gorgeVariant", kGorgeVariants, kGorgeVariantsData) ValidateVariant(variants, "lerkVariant", kLerkVariants, kLerkVariantsData) ValidateVariant(variants, "fadeVariant", kFadeVariants, kFadeVariantsData) ValidateVariant(variants, "onosVariant", kOnosVariants, kOnosVariantsData) ValidateVariant(variants, "exoVariant", kExoVariants, kExoVariantsData) ValidateVariant(variants, "rifleVariant", kRifleVariants, kRifleVariantsData) ValidateVariant(variants, "pistolVariant", kPistolVariants, kPistolVariantsData) ValidateVariant(variants, "axeVariant", kAxeVariants, kAxeVariantsData) ValidateVariant(variants, "shotgunVariant", kShotgunVariants, kShotgunVariantsData) ValidateVariant(variants, "flamethrowerVariant", kFlamethrowerVariants, kFlamethrowerVariantsData) ValidateVariant(variants, "grenadeLauncherVariant", kGrenadeLauncherVariants, kGrenadeLauncherVariantsData) ValidateVariant(variants, "welderVariant", kWelderVariants, kWelderVariantsData) ValidateVariant(variants, "hmgVariant", kHMGVariants, kHMGVariantsData) ValidateVariant(variants, "marineStructuresVariant", kMarineStructureVariants, kMarineStructureVariantsData) ValidateVariant(variants, "alienStructuresVariant", kAlienStructureVariants, kAlienStructureVariantsData) ValidateVariant(variants, "alienTunnelsVariant", kAlienTunnelVariants, kAlienTunnelVariantsData) return variants end function SendPlayerVariantUpdate() if Client.GetIsConnected() then local options = GetAndSetVariantOptions() Client.SendNetworkMessage("SetPlayerVariant", { marineVariant = options.marineVariant, skulkVariant = options.skulkVariant, gorgeVariant = options.gorgeVariant, lerkVariant = options.lerkVariant, fadeVariant = options.fadeVariant, onosVariant = options.onosVariant, isMale = string.lower(options.sexType) == "male", shoulderPadIndex = options.shoulderPadIndex, exoVariant = options.exoVariant, rifleVariant = options.rifleVariant, pistolVariant = options.pistolVariant, axeVariant = options.axeVariant, shotgunVariant = options.shotgunVariant, flamethrowerVariant = options.flamethrowerVariant, grenadeLauncherVariant = options.grenadeLauncherVariant, welderVariant = options.welderVariant, hmgVariant = options.hmgVariant, marineStructuresVariant = options.marineStructuresVariant, alienStructuresVariant = options.alienStructuresVariant, alienTunnelsVariant = options.alienTunnelsVariant, }, true) end end function CheckCollectableAchievement() if Client.IsInventoryLoaded() then for _, itemId in ipairs(kCollectableItemIds) do if not GetOwnsItem( itemId ) then return end end Client.SetAchievement('Economy_0_1') end end ------------------------------------------ -- This will return nil if the asset DNE ------------------------------------------ function PrecacheAssetIfExists( path ) if GetFileExists(path) then return PrecacheAsset(path) else --DebugPrint("attempted to precache asset that does not exist: "..path) return nil end end ------------------------------------------ -- If the first path DNE, it will use the fallback ------------------------------------------ function PrecacheAssetSafe( path, fallback ) if GetFileExists(path) then return PrecacheAsset(path) else --DebugPrint("Could not find "..path.."\n Loading "..fallback.." instead" ) assert( GetFileExists(fallback) ) return PrecacheAsset(fallback) end end function GetPlayerSkillTier(skill, isRookie, adagradSum, isBot) --TODO-HIVE Update for Team-context if isBot then return -1, "SKILLTIER_BOT" end if isRookie then return 0, "SKILLTIER_ROOKIE", 0 end if not skill or skill == -1 then return -2, "SKILLTIER_UNKNOWN" end if adagradSum then -- capping the skill values using sum of squared adagrad gradients -- This should stop the skill tier from changing too often for some players due to short term trends -- The used factor may need some further adjustments if adagradSum <= 0 then skill = 0 else skill = math.max(skill - 25 / math.sqrt(adagradSum), 0) end end if skill <= 300 then return 1, "SKILLTIER_RECRUIT", skill end if skill <= 750 then return 2, "SKILLTIER_FRONTIERSMAN", skill end if skill <= 1400 then return 3, "SKILLTIER_SQUADLEADER", skill end if skill <= 2100 then return 4, "SKILLTIER_VETERAN", skill end if skill <= 2900 then return 5, "SKILLTIER_COMMANDANT", skill end if skill <= 4100 then return 6, "SKILLTIER_SPECIALOPS", skill end return 7, "SKILLTIER_SANJISURVIVOR", skill end local kSkillTierToDescMap = { [-1] = "SKILLTIER_BOT", [ 0] = "SKILLTIER_ROOKIE", [ 1] = "SKILLTIER_RECRUIT", [ 2] = "SKILLTIER_FRONTIERSMAN", [ 3] = "SKILLTIER_SQUADLEADER", [ 4] = "SKILLTIER_VETERAN", [ 5] = "SKILLTIER_COMMANDANT", [ 6] = "SKILLTIER_SPECIALOPS", [ 7] = "SKILLTIER_SANJISURVIVOR", unknown = "SKILLTIER_UNKNOWN", } function GetSkillTierDescription(tier) assert(type(tier) == "number") return kSkillTierToDescMap[tier] or kSkillTierToDescMap.unknown end local warmupActive = false function SetWarmupActive(active) warmupActive = active end function GetWarmupActive() return warmupActive end
local ZkyTargetBar = LibStub("AceAddon-3.0"):GetAddon("ZkyTargetBar") local defaults = { profile = { position = nil, scale = 1.5, layout = 3, textPosition = { x = 0, y = -2 }, hideText = false, showInRaid = true, showInParty = false, showSolo = false, locked = false, playErrorSound = true, } } local options = nil local function getOptions() if options then return options end options = { type = "group", name = "Return Target Icon Bar", args = { general = { type = "group", name = "", inline = true, args = { descriptionImage = { name = "", type = "description", image = "Interface\\AddOns\\ZkyTargetBar\\media\\return", imageWidth = 64, imageHeight = 64, width = "half", order = 1 }, descriptiontext = { name = "Return Target Icon Bar by Irpa\nDiscord: https://discord.gg/SZYAKFy\nGithub: https://github.com/zorkqz/ZkyTargetBar\n", type = "description", width = "full", order = 1.1 }, headerGlobalSettings = { name = "Settings", type = "header", width = "double", order = 2 }, showInRaid = { name = "Show in raids", desc = "", type = "toggle", order = 2.1, get = function(self) return ZkyTargetBar.db.profile.showInRaid end, set = function(self, value) ZkyTargetBar.db.profile.showInRaid = value ZkyTargetBar:CheckHide() end }, showInParty = { name = "Show in party", desc = "", type = "toggle", order = 2.2, get = function(self) return ZkyTargetBar.db.profile.showInParty end, set = function(self, value) ZkyTargetBar.db.profile.showInParty = value ZkyTargetBar:CheckHide() end }, showSolo = { name = "Show when solo", desc = "Doesn't make much sense.", type = "toggle", order = 2.3, get = function(self) return ZkyTargetBar.db.profile.showSolo end, set = function(self, value) ZkyTargetBar.db.profile.showSolo = value ZkyTargetBar:CheckHide() end }, locked = { name = "Lock position", desc = "Lock icons in place.", type = "toggle", order = 2.4, get = function(self) return ZkyTargetBar.db.profile.locked end, set = function(self, value) ZkyTargetBar.db.profile.locked = value end }, playErrorSound = { name = "Play error sound", desc = "Play an error sound if no target could be found.", type = "toggle", order = 2.4, get = function(self) return ZkyTargetBar.db.profile.playErrorSound end, set = function(self, value) ZkyTargetBar.db.profile.playErrorSound = value end }, hideText = { name = "Hide Text", desc = "", type = "toggle", order = 2.5, get = function(self) return ZkyTargetBar.db.profile.hideText end, set = function(self, value) ZkyTargetBar.db.profile.hideText = value ZkyTargetBar:UpdateTextPosition() end }, headerLayout = { name = "Layout", type = "header", width = "double", order = 3 }, scale = { name = "Scale", desc = "", type = "range", order = 3.1, min = 0.1, max = 5, softMin = 0.5, softMax = 2, step = 0.1, bigStep = 0.1, get = function(self) return ZkyTargetBar.db.profile.scale end, set = function(self, value) ZkyTargetBar.db.profile.scale = value ZkyTargetBar:DoLayout() end }, layout = { name = "Layout", desc = "", type = "range", order = 3.2, min = 0, max = 3, softMin = 0, softMax = 3, step = 1, bigStep = 1, get = function(self) return ZkyTargetBar.db.profile.layout end, set = function(self, value) ZkyTargetBar.db.profile.layout = value ZkyTargetBar:DoLayout() end }, emptyDescription1 = { name = "", type = "description", order = 3.3 }, textPositionX = { name = "Text X", desc = "", type = "range", order = 3.4, min = -100, max = 100, softMin = -100, softMax = 100, step = 0.1, bigStep = 1, get = function(self) return ZkyTargetBar.db.profile.textPosition.x end, set = function(self, value) ZkyTargetBar.db.profile.textPosition.x = value ZkyTargetBar:UpdateTextPosition() end }, textPositionY = { name = "Text Y", desc = "", type = "range", order = 3.5, min = -100, max = 100, softMin = -100, softMax = 100, step = 0.1, bigStep = 1, get = function(self) return ZkyTargetBar.db.profile.textPosition.y end, set = function(self, value) ZkyTargetBar.db.profile.textPosition.y = value ZkyTargetBar:UpdateTextPosition() end }, } } } } return options end function ZkyTargetBar:ChatCommand(input) InterfaceOptionsFrame_OpenToCategory(ZkyTargetBar.Options.Menus.Profiles) InterfaceOptionsFrame_OpenToCategory(ZkyTargetBar.Options.Menus.Profiles) InterfaceOptionsFrame_OpenToCategory(ZkyTargetBar.Options.Menus.ZkyTargetBar) end function ZkyTargetBar:SetupOptions() ZkyTargetBar.db = LibStub("AceDB-3.0"):New("ZkyTargetBarDB", defaults, true) ZkyTargetBar.Options = {} ZkyTargetBar.Options.Menus = {} ZkyTargetBar.Options.Profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(ZkyTargetBar.db) LibStub("AceConfig-3.0"):RegisterOptionsTable("ZkyTargetBar", getOptions) LibStub("AceConfigRegistry-3.0"):RegisterOptionsTable("ZkyTargetBar Profiles", ZkyTargetBar.Options.Profiles) ZkyTargetBar.Options.Menus.ZkyTargetBar = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("ZkyTargetBar", "ZkyTargetBar", nil) ZkyTargetBar.Options.Menus.Profiles = LibStub("AceConfigDialog-3.0"):AddToBlizOptions("ZkyTargetBar Profiles", "Profiles", "ZkyTargetBar") ZkyTargetBar:RegisterChatCommand("ZkyTargetBar", "ChatCommand") ZkyTargetBar:RegisterChatCommand("ztb", "ChatCommand") end -- Binding Variables BINDING_HEADER_RETURNTARGETBAR = "Return Target Icon Bar" _G["BINDING_NAME_CLICK ZkyTargetBarButton8:LeftButton"] = "Target Skull"; _G["BINDING_NAME_CLICK ZkyTargetBarButton7:LeftButton"] = "Target Cross"; _G["BINDING_NAME_CLICK ZkyTargetBarButton6:LeftButton"] = "Target Square"; _G["BINDING_NAME_CLICK ZkyTargetBarButton5:LeftButton"] = "Target Moon"; _G["BINDING_NAME_CLICK ZkyTargetBarButton4:LeftButton"] = "Target Triangle"; _G["BINDING_NAME_CLICK ZkyTargetBarButton3:LeftButton"] = "Target Diamond"; _G["BINDING_NAME_CLICK ZkyTargetBarButton2:LeftButton"] = "Target Circle"; _G["BINDING_NAME_CLICK ZkyTargetBarButton1:LeftButton"] = "Target Star";
--- An empty module that can be used with require() print('empty_mod.lua called') return { foo = function() print('foo') end }
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --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 wibox = require("wibox") local TagList = require("widget.tag-list") local clickable_container = require("widget.material.clickable-container") return function(screen, action_bar_width) -- Create an imagebox widget which will contains an icon indicating which layout we're using. -- We need one layoutbox per screen. local LayoutBox = function(s) local layoutBox = clickable_container(awful.widget.layoutbox(s)) layoutBox:buttons( awful.util.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 ) ) ) return layoutBox end local folders = nil if general["weak_hardware"] == "0" or general["weak_hardware"] == nil then folders = require("widget.xdg-folders")("bottom") end return wibox.widget { id = "action_bar", layout = wibox.layout.align.horizontal, forced_height = action_bar_width, -- left widget expand = "none", nil, { -- middle widgets layout = wibox.layout.align.horizontal, -- Create a taglist widget TagList("bottom")(screen), folders --[[wibox.widget { orientation = 'horizontal', forced_height = 10, opacity = 0.50, widget = wibox.widget.separator }, ]] -- }, --s.mytasklist, -- Middle widget --nil, { -- Right widgets layout = wibox.layout.fixed.horizontal, LayoutBox() } } end
-- Density's values start from 0.0 to 1.0. DenistyMultiplier = 0.3 Citizen.CreateThread(function() while true do Citizen.Wait(0) SetVehicleDensityMultiplierThisFrame(DenistyMultiplier) SetPedDensityMultiplierThisFrame(DenistyMultiplier) SetRandomVehicleDensityMultiplierThisFrame(DenistyMultiplier) SetParkedVehicleDensityMultiplierThisFrame(DenistyMultiplier, DenistyMultiplier) end end)
--[[-------------------------------------------------------------------- Copyright (C) 2012 Sidoine De Wispelaere. Copyright (C) 2012, 2013, 2014 Johnny C. Lam. See the file LICENSE.txt for copying permission. --]]-------------------------------------------------------------------- -- Gather information about ennemies local OVALE, Ovale = ... local OvaleEnemies = Ovale:NewModule("OvaleEnemies", "AceEvent-3.0", "AceTimer-3.0") Ovale.OvaleEnemies = OvaleEnemies --<private-static-properties> local L = Ovale.L local OvaleDebug = Ovale.OvaleDebug local OvaleProfiler = Ovale.OvaleProfiler -- Forward declarations for module dependencies. local OvaleGUID = nil local OvaleState = nil local bit_band = bit.band local bit_bor = bit.bor local ipairs = ipairs local pairs = pairs local strfind = string.find local tostring = tostring local wipe = wipe local API_GetTime = GetTime local COMBATLOG_OBJECT_AFFILIATION_MINE = COMBATLOG_OBJECT_AFFILIATION_MINE local COMBATLOG_OBJECT_AFFILIATION_PARTY = COMBATLOG_OBJECT_AFFILIATION_PARTY local COMBATLOG_OBJECT_AFFILIATION_RAID = COMBATLOG_OBJECT_AFFILIATION_RAID local COMBATLOG_OBJECT_REACTION_FRIENDLY = COMBATLOG_OBJECT_REACTION_FRIENDLY -- Bitmask for player, party or raid unit controller affiliation. local GROUP_MEMBER = bit_bor(COMBATLOG_OBJECT_AFFILIATION_MINE, COMBATLOG_OBJECT_AFFILIATION_PARTY, COMBATLOG_OBJECT_AFFILIATION_RAID) -- Register for debugging messages. OvaleDebug:RegisterDebugging(OvaleEnemies) -- Register for profiling. OvaleProfiler:RegisterProfiling(OvaleEnemies) --[[ List of CLEU event suffixes that can correspond to the player damaging or try to damage (tag) an enemy, or vice versa. --]] local CLEU_TAG_SUFFIXES = { "_DAMAGE", "_MISSED", "_AURA_APPLIED", "_AURA_APPLIED_DOSE", "_AURA_REFRESH", "_CAST_START", "_INTERRUPT", "_DISPEL", "_DISPEL_FAILED", "_STOLEN", "_DRAIN", "_LEECH", } -- Table of CLEU events for auto-attacks. local CLEU_AUTOATTACK = { RANGED_DAMAGE = true, RANGED_MISSED = true, SWING_DAMAGE = true, SWING_MISSED = true, } -- Table of CLEU events for when a unit is removed from combat. local CLEU_UNIT_REMOVED = { UNIT_DESTROYED = true, UNIT_DIED = true, UNIT_DISSIPATES = true, } -- Player's GUID. local self_playerGUID = nil -- enemyName[guid] = name local self_enemyName = {} -- enemyLastSeen[guid] = timestamp local self_enemyLastSeen = {} -- taggedEnemyLastSeen[guid] = timestamp -- GUIDs used as keys for this table are a subset of the GUIDs used for enemyLastSeen. local self_taggedEnemyLastSeen = {} -- Timer for reaper function to remove inactive enemies. local self_reaperTimer = nil local REAP_INTERVAL = 3 --</private-static-properties> --<public-static-properties> -- Total number of active enemies. OvaleEnemies.activeEnemies = 0 -- Total number of tagged enemies. OvaleEnemies.taggedEnemies = 0 --</public-static-properties> --<private-static-methods> local function IsTagEvent(cleuEvent) local isTagEvent = false if CLEU_AUTOATTACK[cleuEvent] then isTagEvent = true else for _, suffix in ipairs(CLEU_TAG_SUFFIXES) do if strfind(cleuEvent, suffix .. "$") then isTagEvent = true break end end end return isTagEvent end local function IsFriendly(unitFlags, isGroupMember) return bit_band(unitFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) > 0 and (not isGroupMember or bit_band(unitFlags, GROUP_MEMBER) > 0) end --</private-static-methods> --<public-static-methods> function OvaleEnemies:OnInitialize() -- Resolve module dependencies. OvaleGUID = Ovale.OvaleGUID OvaleState = Ovale.OvaleState end function OvaleEnemies:OnEnable() self_playerGUID = Ovale.playerGUID if not self_reaperTimer then self_reaperTimer = self:ScheduleRepeatingTimer("RemoveInactiveEnemies", REAP_INTERVAL) end self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterEvent("PLAYER_REGEN_DISABLED") OvaleState:RegisterState(self, self.statePrototype) end function OvaleEnemies:OnDisable() OvaleState:UnregisterState(self) if not self_reaperTimer then self:CancelTimer(self_reaperTimer) self_reaperTimer = nil end self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterEvent("PLAYER_REGEN_DISABLED") end function OvaleEnemies:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, ...) if CLEU_UNIT_REMOVED[cleuEvent] then local now = API_GetTime() self:RemoveEnemy(cleuEvent, destGUID, now, true) elseif sourceGUID and sourceGUID ~= "" and sourceName and sourceFlags and destGUID and destGUID ~= "" and destName and destFlags then if not IsFriendly(sourceFlags) and IsFriendly(destFlags, true) then --[[ Unfriendly enemy attacks friendly group member. Filter out periodic damage effects since they can occur after the caster's death and can cause false positives. --]] if not cleuEvent == "SPELL_PERIODIC_DAMAGE" and IsTagEvent(cleuEvent) then local now = API_GetTime() self:AddEnemy(cleuEvent, sourceGUID, sourceName, now) end elseif IsFriendly(sourceFlags, true) and not IsFriendly(destFlags) and IsTagEvent(cleuEvent) then -- Friendly group member attacks unfriendly enemy. local now = API_GetTime() -- Treat both player and pet attacks as a player tag. local isPlayerTag = (sourceGUID == self_playerGUID) or OvaleGUID:IsPlayerPet(sourceGUID) self:AddEnemy(cleuEvent, destGUID, destName, now, isPlayerTag) end end end function OvaleEnemies:PLAYER_REGEN_DISABLED() -- Reset enemy tracking when combat starts. wipe(self_enemyName) wipe(self_enemyLastSeen) wipe(self_taggedEnemyLastSeen) self.activeEnemies = 0 self.taggedEnemies = 0 end --[[ Remove enemies that have been inactive for at least REAP_INTERVAL seconds. These enemies are not in combat with your group, out of range, or incapacitated and shouldn't count toward the number of active enemies. --]] function OvaleEnemies:RemoveInactiveEnemies() self:StartProfiling("OvaleEnemies_RemoveInactiveEnemies") local now = API_GetTime() -- Remove inactive enemies first. for guid, timestamp in pairs(self_enemyLastSeen) do if now - timestamp > REAP_INTERVAL then self:RemoveEnemy("REAPED", guid, now) end end -- Remove inactive tagged enemies last. for guid, timestamp in pairs(self_taggedEnemyLastSeen) do if now - timestamp > REAP_INTERVAL then self:RemoveTaggedEnemy("REAPED", guid, now) end end self:StopProfiling("OvaleEnemies_RemoveInactiveEnemies") end function OvaleEnemies:AddEnemy(cleuEvent, guid, name, timestamp, isTagged) self:StartProfiling("OvaleEnemies_AddEnemy") if guid then self_enemyName[guid] = name local changed = false do -- Update last time this enemy was seen. if not self_enemyLastSeen[guid] then self.activeEnemies = self.activeEnemies + 1 changed = true end self_enemyLastSeen[guid] = timestamp end if isTagged then -- Update last time this enemy was tagged. if not self_taggedEnemyLastSeen[guid] then self.taggedEnemies = self.taggedEnemies + 1 changed = true end self_taggedEnemyLastSeen[guid] = timestamp end if changed then self:DebugTimestamp("%s: %d/%d enemy seen: %s (%s)", cleuEvent, self.taggedEnemies, self.activeEnemies, guid, name) Ovale.refreshNeeded[self_playerGUID] = true end end self:StopProfiling("OvaleEnemies_AddEnemy") end function OvaleEnemies:RemoveEnemy(cleuEvent, guid, timestamp, isDead) self:StartProfiling("OvaleEnemies_RemoveEnemy") if guid then local name = self_enemyName[guid] local changed = false -- Update seen enemy count. if self_enemyLastSeen[guid] then self_enemyLastSeen[guid] = nil if self.activeEnemies > 0 then self.activeEnemies = self.activeEnemies - 1 changed = true end end -- Update tagged enemy count. if self_taggedEnemyLastSeen[guid] then self_taggedEnemyLastSeen[guid] = nil if self.taggedEnemies > 0 then self.taggedEnemies = self.taggedEnemies - 1 changed = true end end if changed then self:DebugTimestamp("%s: %d/%d enemy %s: %s (%s)", cleuEvent, self.taggedEnemies, self.activeEnemies, isDead and "died" or "removed", guid, name) Ovale.refreshNeeded[self_playerGUID] = true self:SendMessage("Ovale_InactiveUnit", guid, isDead) end end self:StopProfiling("OvaleEnemies_RemoveEnemy") end function OvaleEnemies:RemoveTaggedEnemy(cleuEvent, guid, timestamp) self:StartProfiling("OvaleEnemies_RemoveTaggedEnemy") if guid then local name = self_enemyName[guid] local tagged = self_taggedEnemyLastSeen[guid] if tagged then self_taggedEnemyLastSeen[guid] = nil if self.taggedEnemies > 0 then self.taggedEnemies = self.taggedEnemies - 1 end self:DebugTimestamp("%s: %d/%d enemy removed: %s (%s), last tagged at %f", cleuEvent, self.taggedEnemies, self.activeEnemies, guid, name, tagged) Ovale.refreshNeeded[self_playerGUID] = true end end self:StopProfiling("OvaleEnemies_RemoveEnemy") end function OvaleEnemies:DebugEnemies() for guid, seen in pairs(self_enemyLastSeen) do local name = self_enemyName[guid] local tagged = self_taggedEnemyLastSeen[guid] if tagged then self:Print("Tagged enemy %s (%s) last seen at %f", guid, name, tagged) else self:Print("Enemy %s (%s) last seen at %f", guid, name, seen) end end self:Print("Total enemies: %d", self.activeEnemies) self:Print("Total tagged enemies: %d", self.taggedEnemies) end --</public-static-methods> --[[---------------------------------------------------------------------------- State machine for simulator. --]]---------------------------------------------------------------------------- --<public-static-properties> OvaleEnemies.statePrototype = {} --</public-static-properties> --<private-static-properties> local statePrototype = OvaleEnemies.statePrototype --</private-static-properties> --<state-properties> -- Total number of active enemies. statePrototype.activeEnemies = nil -- Total number of tagged enemies. statePrototype.taggedEnemies = nil -- Requested number of enemies. statePrototype.enemies = nil --</state-properties> --<public-static-methods> -- Initialize the state. function OvaleEnemies:InitializeState(state) state.enemies = nil end -- Reset the state to the current conditions. function OvaleEnemies:ResetState(state) self:StartProfiling("OvaleEnemies_ResetState") state.activeEnemies = self.activeEnemies state.taggedEnemies = self.taggedEnemies self:StopProfiling("OvaleEnemies_ResetState") end -- Release state resources prior to removing from the simulator. function OvaleEnemies:CleanState(state) state.activeEnemies = nil state.taggedEnemies = nil state.enemies = nil end --</public-static-methods>
return {id=5,name={key='key_name',text="aabbcc"},date={ _type_='DemoD5',x1=1,time={start_time=398966400,end_time=936806400,},},}
register_item({ name = "chips", texture = "chips.png", hunger = 6, }) register_item({ name = "water_bottle", texture = "water_bottle.png", thirst = 20, }) -- begin empty foods to mirror the regular foods register_item({ name = "empty_chips", texture = "empty_chips.png", }) register_item({ name = "empty_water_bottle", texture = "empty_water_bottle.png", })
--[[ Data storage note: this plugin requires state which you can get from the following url: https://github.com/TheLinx/lstate ]] Name = "Data Storage" Hidden = true -- comment to enable this plugin disable() local state = require("state") local cfg = CONFIG.data local function load() local saved = state.load(cfg.name) if saved then public = saved end end local function save() state.store(cfg.name, public) end function Load() load() end function Unload() save() end Hook "Think" { function() save() wait(cfg.saveInterval) end }
-- Copyright 2022 SmartThings -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local test = require "integration_test" local capabilities = require "st.capabilities" local zw = require "st.zwave" local zw_test_utils = require "integration_test.zwave_test_utils" local t_utils = require "integration_test.utils" local SwitchBinary = (require "st.zwave.CommandClass.SwitchBinary")({version=2}) local fortrezz_valve_endpoints = { { command_classes = { { value = zw.SWITCH_BINARY }, } } } local mock_device = test.mock_device.build_test_zwave_device({ profile = t_utils.get_profile_definition("valve-generic.yml"), zwave_endpoints = fortrezz_valve_endpoints, zwave_manufacturer_id = 0x0084, zwave_product_type = 0x0243, zwave_product_id = 0x0300 }) local function test_init() test.mock_device.add_test_device(mock_device) end test.set_test_init_function(test_init) test.register_message_test( "Binary valve on/off report should be handled: on", { { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( SwitchBinary:Report({target_value=SwitchBinary.value.ON_ENABLE}) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.valve.valve.closed()) } } ) test.register_message_test( "Binary valve on/off report should be handled: off", { { channel = "zwave", direction = "receive", message = { mock_device.id, zw_test_utils.zwave_test_build_receive_command( SwitchBinary:Report({target_value=SwitchBinary.value.OFF_DISABLE}) ) } }, { channel = "capability", direction = "send", message = mock_device:generate_test_message("main", capabilities.valve.valve.open()) } } ) test.register_coroutine_test( "Turning valve on should generate correct zwave messages", function() test.timer.__create_and_queue_test_time_advance_timer(1, "oneshot") test.socket.capability:__queue_receive( { mock_device.id, { capability = "valve", command = "open", args = {} } } ) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Set({ target_value=SwitchBinary.value.OFF_DISABLE, }) ) ) test.wait_for_events() test.mock_time.advance_time(1) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}) ) ) end ) test.register_coroutine_test( "Turning valve off should generate correct zwave messages", function() test.timer.__create_and_queue_test_time_advance_timer(1, "oneshot") test.socket.capability:__queue_receive( { mock_device.id, { capability = "valve", command = "close", args = {} } } ) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Set({ target_value=SwitchBinary.value.ON_ENABLE, }) ) ) test.wait_for_events() test.mock_time.advance_time(1) test.socket.zwave:__expect_send( zw_test_utils.zwave_test_build_send_command( mock_device, SwitchBinary:Get({}) ) ) end ) test.run_registered_tests()
object_draft_schematic_armor_component_new_armor_core_basic_test = object_draft_schematic_armor_component_shared_new_armor_core_basic_test:new { } ObjectTemplates:addTemplate(object_draft_schematic_armor_component_new_armor_core_basic_test, "object/draft_schematic/armor/component/new_armor_core_basic_test.iff")
ModelFlags = { [`flatbed`] = { "isTowTruck" }, [`trash2`] = { "isTrashTruck" }, [`benson`] = { "isDeliveryTruck" }, [`prop_vend_snak_01`] = { "isVendingMachine", "isVendingMachineFood" }, [`prop_vend_coffe_01`] = { "isVendingMachine", "isVendingMachineBeverage" }, [`prop_vend_soda_01`] = { "isVendingMachine", "isVendingMachineBeverage" }, [`prop_vend_soda_02`] = { "isVendingMachine", "isVendingMachineBeverage" }, [`prop_vend_fridge01`] = { "isVendingMachine", "isVendingMachineBeverage" }, [`prop_vend_water_01`] = { "isVendingMachine", "isVendingMachineBeverage" }, [`prop_atm_01`] = { "isATM" }, [`prop_atm_02`] = { "isATM" }, [`prop_atm_03`] = { "isATM" }, [`prop_fleeca_atm`] = { "isATM" }, [`v_5_b_atm1`] = { "isATM" }, [`v_5_b_atm2`] = { "isATM" }, [`prop_news_disp_01a`] = { "isNewsStand" }, [`prop_news_disp_02a`] = { "isNewsStand" }, [`prop_news_disp_02c`] = { "isNewsStand" }, [`prop_news_disp_03a`] = { "isNewsStand" }, [`prop_news_disp_05a`] = { "isNewsStand" }, [`npwheelchair`] = { "isWheelchair" }, [`v_res_fa_chair01`] = {"isChair"}, [-1278649385] = {"isChair"}, [`prop_picnictable_01`] = {"isChair"}, [`prop_picnictable_02`] = {"isChair"}, [`v_ilev_m_dinechair`] = {"isChair"}, [`v_club_stagechair`] = {"isChair"}, [`prop_bench_01a`] = {"isChair"}, [`prop_bench_01b`] = {"isChair"}, [`prop_bench_01c`] = {"isChair"}, [`prop_bench_02`] = {"isChair"}, [`prop_bench_03`] = {"isChair"}, [`prop_bench_04`] = {"isChair"}, [`prop_bench_05`] = {"isChair"}, [`prop_bench_06`] = {"isChair"}, [`prop_bench_08`] = {"isChair"}, [`prop_bench_09`] = {"isChair"}, [`prop_bench_10`] = {"isChair"}, [`prop_bench_11`] = {"isChair"}, [`prop_snow_bench_01`] = {"isChair"}, [`prop_fib_3b_bench`] = {"isChair"}, [`prop_ld_bench01`] = {"isChair"}, [`prop_wait_bench_01`] = {"isChair"}, [`v_serv_ct_chair02`] = {"isChair"}, [`hei_prop_heist_off_chair`] = {"isChair"}, [`hei_prop_hei_skid_chair`] = {"isChair"}, [`prop_chair_01a`] = {"isChair"}, [`prop_chair_01b`] = {"isChair"}, [`prop_chair_02`] = {"isChair"}, [`prop_chair_03`] = {"isChair"}, [`prop_chair_04a`] = {"isChair"}, [`prop_chair_04b`] = {"isChair"}, [`prop_chair_05`] = {"isChair"}, [`prop_chair_06`] = {"isChair"}, [`prop_chair_08`] = {"isChair"}, [`prop_chair_09`] = {"isChair"}, [`prop_chair_10`] = {"isChair"}, [`prop_chateau_chair_01`] = {"isChair"}, [`prop_clown_chair`] = {"isChair"}, [`prop_cs_office_chair`] = {"isChair"}, [`prop_direct_chair_01`] = {"isChair"}, [`prop_direct_chair_02`] = {"isChair"}, [`prop_gc_chair02`] = {"isChair"}, [`prop_off_chair_01`] = {"isChair"}, [`prop_off_chair_03`] = {"isChair"}, [`prop_off_chair_04`] = {"isChair"}, [`prop_off_chair_04b`] = {"isChair"}, [`prop_off_chair_04_s`] = {"isChair"}, [`prop_off_chair_05`] = {"isChair"}, [`prop_old_deck_chair`] = {"isChair"}, [`prop_old_wood_chair`] = {"isChair"}, [`prop_rock_chair_01`] = {"isChair"}, [`prop_skid_chair_01`] = {"isChair"}, [`prop_skid_chair_02`] = {"isChair"}, [`prop_skid_chair_03`] = {"isChair"}, [`prop_sol_chair`] = {"isChair"}, [`prop_wheelchair_01`] = {"isChair"}, [`prop_wheelchair_01_s`] = {"isChair"}, [`p_armchair_01_s`] = {"isChair"}, [`p_clb_officechair_s`] = {"isChair"}, [`p_dinechair_01_s`] = {"isChair"}, [`p_ilev_p_easychair_s`] = {"isChair"}, [`p_soloffchair_s`] = {"isChair"}, [`p_yacht_chair_01_s`] = {"isChair"}, [`v_club_officechair`] = {"isChair"}, [`v_corp_bk_chair3`] = {"isChair"}, [`v_corp_cd_chair`] = {"isChair"}, [`v_corp_offchair`] = {"isChair"}, [`v_ilev_chair02_ped`] = {"isChair"}, [`v_ilev_hd_chair`] = {"isChair"}, [`v_ilev_p_easychair`] = {"isChair"}, [`v_ret_gc_chair03`] = {"isChair"}, [`prop_ld_farm_chair01`] = {"isChair"}, [`prop_table_04_chr`] = {"isChair"}, [`prop_table_05_chr`] = {"isChair"}, [`prop_table_06_chr`] = {"isChair"}, [`v_ilev_leath_chr`] = {"isChair"}, [`prop_table_01_chr_a`] = {"isChair"}, [`prop_table_01_chr_b`] = {"isChair"}, [`prop_table_02_chr`] = {"isChair"}, [`prop_table_03b_chr`] = {"isChair"}, [`prop_table_03_chr`] = {"isChair"}, [`prop_torture_ch_01`] = {"isChair"}, [`v_ilev_fh_dineeamesa`] = {"isChair"}, [`v_ilev_fh_kitchenstool`] = {"isChair"}, [`v_ilev_tort_stool`] = {"isChair"}, [`hei_prop_yah_seat_01`] = {"isChair"}, [`hei_prop_yah_seat_02`] = {"isChair"}, [`hei_prop_yah_seat_03`] = {"isChair"}, [`prop_waiting_seat_01`] = {"isChair"}, [`prop_yacht_seat_01`] = {"isChair"}, [`prop_yacht_seat_02`] = {"isChair"}, [`prop_yacht_seat_03`] = {"isChair"}, [`prop_hobo_seat_01`] = {"isChair"}, [`prop_rub_couch01`] = {"isChair"}, [`miss_rub_couch_01`] = {"isChair"}, [`prop_ld_farm_couch01`] = {"isChair"}, [`prop_ld_farm_couch02`] = {"isChair"}, [`prop_rub_couch02`] = {"isChair"}, [`prop_rub_couch03`] = {"isChair"}, [`prop_rub_couch04`] = {"isChair"}, [`p_lev_sofa_s`] = {"isChair"}, [`p_res_sofa_l_s`] = {"isChair"}, [`p_v_med_p_sofa_s`] = {"isChair"}, [`p_yacht_sofa_01_s`] = {"isChair"}, [`v_ilev_m_sofa`] = {"isChair"}, [`v_res_tre_sofa_s`] = {"isChair"}, [`v_tre_sofa_mess_a_s`] = {"isChair"}, [`v_tre_sofa_mess_b_s`] = {"isChair"}, [`v_tre_sofa_mess_c_s`] = {"isChair"}, [`prop_roller_car_01`] = {"isChair"}, [`prop_roller_car_02`] = {"isChair"}, [`ex_prop_offchair_exec_04`] = {"isChair"}, [`ba_prop_battle_club_chair_01`] = {"isChair"}, [`np_mp_h_din_chair_09`] = {"isChair"}, [`prop_bar_stool_01`] = {"isChair"}, [`np_town_hall_judge_chair`] = {"isChair"}, [`ba_prop_int_glam_stool`] = {"isChair"}, [`vw_prop_vw_offchair_02`] = {"isChair"}, [`vw_prop_casino_chair_01a`] = {"isChair"}, [`V_Res_MBchair`] = {"isChair"}, [`V_Res_M_L_Chair1`] = {"isChair"}, [`V_Ret_Chair`] = {"isChair"}, [`V_Ret_GC_Chair01`] = {"isChair"}, [`V_ILev_M_DineChair`] = {"isChair"}, [`ba_Prop_Battle_Club_Chair_02`] = {"isChair"}, [`V_Res_M_ArmChair`] = {"isChair"}, [-105886377] = {"isChair"}, [757888276] = {"isChair"}, [-425962029] = {"isChair"}, [1630899471] = {"isChair"}, [-1786424499] = {"isChair"}, [-2065455377] = {"isChair"}, [-992735415] = {"isChair"}, [-1120527678] = {"isChair"}, [`v_serv_ct_chair01`] = {"isChair"}, [520143535] = {"isChair"}, [-1626066319] = {"isChair"}, [-470815620] = {"isChair"}, [`gr_prop_gr_chair02_ped`] = {"isChair"}, [`bkr_prop_clubhouse_chair_01`] = {"isChair"}, [`prop_dumpster_01a`] = { "isTrash" }, [`prop_dumpster_02a`] = { "isTrash" }, [`prop_dumpster_02b`] = { "isTrash" }, [`prop_dumpster_3a`] = { "isTrash" }, [`prop_dumpster_4a`] = { "isTrash" }, [`prop_dumpster_4b`] = { "isTrash" }, [`prop_bin_14b`] = { "isTrash" }, [`prop_bin_14a`] = { "isTrash" }, [`prop_bin_08a`] = { "isTrash" }, [`prop_bin_07c`] = { "isTrash" }, [`prop_rub_binbag_03`] = { "isTrash" }, [`prop_rub_binbag_01b`] = { "isTrash" }, [`prop_rub_binbag_06`] = { "isTrash" }, [`prop_beach_bars_02`] = { "isExercise" }, [`prop_weight_squat`] = { "isExercise" }, [`p_yoga_mat_01_s`] = { "isYogaMat" }, [`prop_yoga_mat_01`] = { "isYogaMat" }, [`prop_yoga_mat_02`] = { "isYogaMat" }, [`prop_yoga_mat_03`] = { "isYogaMat" }, [`ba_prop_battle_dj_mixer_01a`] = { "isSmokeMachineTrigger" }, [`p_phonebox_02_s`] = { "isPayPhone" }, [`prop_gas_pump_1d`] = { "isFuelPump" }, [`prop_gas_pump_1a`] = { "isFuelPump" }, [`prop_gas_pump_1b`] = { "isFuelPump" }, [`prop_gas_pump_1c`] = { "isFuelPump" }, [`prop_vintage_pump`] = { "isFuelPump" }, [`prop_gas_pump_old2`] = { "isFuelPump" }, [`prop_gas_pump_old3`] = { "isFuelPump" }, [`bkr_prop_weed_01_small_01c`] = { "isWeedPlant" }, [`bkr_prop_weed_01_small_01a`] = { "isWeedPlant" }, [`bkr_prop_weed_01_small_01b`] = { "isWeedPlant" }, [`bkr_prop_weed_med_01a`] = { "isWeedPlant" }, [`bkr_prop_weed_med_01b`] = { "isWeedPlant" }, [`bkr_prop_weed_lrg_01a`] = { "isWeedPlant" }, [`bkr_prop_weed_lrg_01b`] = { "isLrgWeedPlant", "isWeedPlant" }, [`prop_cementmixer_02a`] = { "isCementMixer" }, [`prop_tv_flat_01`] = { "isTelevision" }, [`prop_tv_flat_michael`] = { "isTelevision" }, [`prop_trev_tv_01`] = { "isTelevision" }, [`prop_tv_flat_03b`] = { "isTelevision" }, [`prop_tv_flat_03`] = { "isTelevision" }, [`prop_tv_flat_02b`] = { "isTelevision" }, [`prop_tv_flat_02`] = { "isTelevision" }, [`ex_prop_ex_tv_flat_01`] = { "isTelevision" }, }
local a = vim.api local highlights = {} local ns_telescope_selection = a.nvim_create_namespace('telescope_selection') local ns_telescope_multiselection = a.nvim_create_namespace('telescope_mulitselection') local ns_telescope_entry = a.nvim_create_namespace('telescope_entry') local Highlighter = {} Highlighter.__index = Highlighter function Highlighter:new(picker) return setmetatable({ picker = picker, }, self) end function Highlighter:hi_display(row, prefix, display_highlights) -- This is the bug that made my highlight fixes not work. -- We will leave the solutino commented, so the test fails. if not display_highlights or vim.tbl_isempty(display_highlights) then return end local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") a.nvim_buf_clear_namespace(results_bufnr, ns_telescope_entry, row, row + 1) local len_prefix = #prefix for _, hl_block in ipairs(display_highlights) do a.nvim_buf_add_highlight( results_bufnr, ns_telescope_entry, hl_block[2], row, len_prefix + hl_block[1][1], len_prefix + hl_block[1][2] ) end end function Highlighter:clear_display() a.nvim_buf_clear_namespace(self.picker.results_bufnr, ns_telescope_entry, 0, -1) end function Highlighter:hi_sorter(row, prompt, display) local picker = self.picker if not picker.sorter or not picker.sorter.highlighter then return end local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") picker:highlight_one_row(results_bufnr, prompt, display, row) end function Highlighter:hi_selection(row, caret) local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") a.nvim_buf_clear_namespace(results_bufnr, ns_telescope_selection, 0, -1) a.nvim_buf_add_highlight( results_bufnr, ns_telescope_selection, 'TelescopeSelectionCaret', row, 0, #caret ) a.nvim_buf_add_highlight( results_bufnr, ns_telescope_selection, 'TelescopeSelection', row, #caret, -1 ) end function Highlighter:hi_multiselect(row, entry) local results_bufnr = assert(self.picker.results_bufnr, "Must have a results bufnr") if self.picker.multi_select[entry] then vim.api.nvim_buf_add_highlight( results_bufnr, ns_telescope_multiselection, "TelescopeMultiSelection", row, 0, -1 ) else vim.api.nvim_buf_clear_namespace( results_bufnr, ns_telescope_multiselection, row, row + 1 ) end end highlights.new = function(...) return Highlighter:new(...) end return highlights
local mqtt = require('mqtt') local assert = require('assert') local TAG = "mqtt" -- 主要测试了 ping 这几个方法 -- 这个测试需要用到 MQTT 服务器 local url = 'mqtt://127.0.0.1:1883' local url = 'mqtt://iot.wotcloud.cn:1883' local options = { clientId = 'wotc_34dac1400002_test' } local client = mqtt.connect(url, options) client.options.debugEnabled = true client.options.keepalive = 4 local TOPIC = '/test-topic' local MESSAGE = 'Hello mqtt' -- connect client:on('connect', function() console.log('@event - connect') client:subscribe(TOPIC, function(err, ack) if (err) then console.log(err) return end console.log('subscribe.ack') end) end) -- message client:on('message', function (topic, message) console.log('@event - message', topic, message) assert.equal(topic, TOPIC) assert.equal(message, MESSAGE) client:close() print(TAG, "message is OK, auto exit...") end) client:on('reconnect', function() console.log('@event - reconnect') end) client:on('close', function() console.log('@event - close') end) client:on('offline', function() console.log('@event - offline') end) client:on('error', function(errInfo) console.log('@event - error', errInfo) end) -- 测试 ping 事件 setInterval(3000, function() --console.log('state = ', client.state) local now = process.now() local state = client.state local lastActivityPing = state.lastActivityPing or 0 local lastActivityIn = state.lastActivityIn or 0 if (client.connected) then local intervalIn = now - lastActivityIn local intervalPing = now - lastActivityPing console.log('intervalIn, intervalPing', intervalIn, intervalPing) end end)
local Widget = require "widgets/widget" local Text = require "widgets/text" local FollowText = Class(Widget, function(self, font, size, text) Widget._ctor(self, "followtext") self:SetScaleMode(SCALEMODE_PROPORTIONAL) self:SetMaxPropUpscale(1.25) self.text = self:AddChild(Text(font, size, text)) self.offset = Vector3(0,0,0) self.screen_offset = Vector3(0,0,0) self:StartUpdating() end) function FollowText:SetTarget(target) self.target = target self:OnUpdate() end function FollowText:SetOffset(offset) self.offset = offset self:OnUpdate() end function FollowText:SetScreenOffset(x,y) self.screen_offset.x = x self.screen_offset.y = y self:OnUpdate() end function FollowText:GetScreenOffset() return self.screen_offset.x, self.screen_offset.y end function FollowText:OnUpdate(dt) if self.target and self.target:IsValid() then local scale = TheFrontEnd:GetHUDScale() self.text:SetScale(scale) local world_pos = Vector3(self.target.AnimState:GetSymbolPosition(self.symbol or "",self.offset.x, self.offset.y, self.offset.z)) local screen_pos = Vector3(TheSim:GetScreenPos(world_pos:Get())) screen_pos.x = screen_pos.x + self.screen_offset.x screen_pos.y = screen_pos.y + self.screen_offset.y self:SetPosition(screen_pos) end end return FollowText
---@class cipherlib local cipher = {} ---@alias CipherType ---| '"AES-128-ECB"' # AES cipher with 128-bit ECB mode. ---| '"AES-192-ECB"' # AES cipher with 192-bit ECB mode. ---| '"AES-256-ECB"' # AES cipher with 256-bit ECB mode. ---| '"AES-128-CBC"' # AES cipher with 128-bit CBC mode. ---| '"AES-192-CBC"' # AES cipher with 192-bit CBC mode. ---| '"AES-256-CBC"' # AES cipher with 256-bit CBC mode. ---| '"AES-128-CFB128"' # AES cipher with 128-bit CFB128 mode. ---| '"AES-192-CFB128"' # AES cipher with 192-bit CFB128 mode. ---| '"AES-256-CFB128"' # AES cipher with 256-bit CFB128 mode. ---| '"AES-128-CTR"' # AES cipher with 128-bit CTR mode. ---| '"AES-192-CTR"' # AES cipher with 192-bit CTR mode. ---| '"AES-256-CTR"' # AES cipher with 256-bit CTR mode. ---| '"AES-128-GCM"' # AES cipher with 128-bit GCM mode. ---| '"AES-192-GCM"' # AES cipher with 192-bit GCM mode. ---| '"AES-256-GCM"' # AES cipher with 256-bit GCM mode. ---| '"CAMELLIA-128-ECB"' # Camellia cipher with 128-bit ECB mode. ---| '"CAMELLIA-192-ECB"' # Camellia cipher with 192-bit ECB mode. ---| '"CAMELLIA-256-ECB"' # Camellia cipher with 256-bit ECB mode. ---| '"CAMELLIA-128-CBC"' # Camellia cipher with 128-bit CBC mode. ---| '"CAMELLIA-192-CBC"' # Camellia cipher with 192-bit CBC mode. ---| '"CAMELLIA-256-CBC"' # Camellia cipher with 256-bit CBC mode. ---| '"CAMELLIA-128-CFB128"' # Camellia cipher with 128-bit CFB128 mode. ---| '"CAMELLIA-192-CFB128"' # Camellia cipher with 192-bit CFB128 mode. ---| '"CAMELLIA-256-CFB128"' # Camellia cipher with 256-bit CFB128 mode. ---| '"CAMELLIA-128-CTR"' # Camellia cipher with 128-bit CTR mode. ---| '"CAMELLIA-192-CTR"' # Camellia cipher with 192-bit CTR mode. ---| '"CAMELLIA-256-CTR"' # Camellia cipher with 256-bit CTR mode. ---| '"CAMELLIA-128-GCM"' # Camellia cipher with 128-bit GCM mode. ---| '"CAMELLIA-192-GCM"' # Camellia cipher with 192-bit GCM mode. ---| '"CAMELLIA-256-GCM"' # Camellia cipher with 256-bit GCM mode. ---| '"DES-ECB"' # DES cipher with ECB mode. ---| '"DES-CBC"' # DES cipher with CBC mode. ---| '"DES-EDE-ECB"' # DES cipher with EDE ECB mode. ---| '"DES-EDE-CBC"' # DES cipher with EDE CBC mode. ---| '"DES-EDE3-ECB"' # DES cipher with EDE3 ECB mode. ---| '"DES-EDE3-CBC"' # DES cipher with EDE3 CBC mode. ---| '"BLOWFISH-ECB"' # Blowfish cipher with ECB mode. ---| '"BLOWFISH-CBC"' # Blowfish cipher with CBC mode. ---| '"BLOWFISH-CFB64"' # Blowfish cipher with CFB64 mode. ---| '"BLOWFISH-CTR"' # Blowfish cipher with CTR mode. ---| '"ARC4-128"' # RC4 cipher with 128-bit mode. ---| '"AES-128-CCM"' # AES cipher with 128-bit CCM mode. ---| '"AES-192-CCM"' # AES cipher with 192-bit CCM mode. ---| '"AES-256-CCM"' # AES cipher with 256-bit CCM mode. ---| '"CAMELLIA-128-CCM"' # Camellia cipher with 128-bit CCM mode. ---| '"CAMELLIA-192-CCM"' # Camellia cipher with 192-bit CCM mode. ---| '"CAMELLIA-256-CCM"' # Camellia cipher with 256-bit CCM mode. ---| '"ARIA-128-ECB"' # Aria cipher with 128-bit key and ECB mode. ---| '"ARIA-192-ECB"' # Aria cipher with 192-bit key and ECB mode. ---| '"ARIA-256-ECB"' # Aria cipher with 256-bit key and ECB mode. ---| '"ARIA-128-CBC"' # Aria cipher with 128-bit key and CBC mode. ---| '"ARIA-192-CBC"' # Aria cipher with 192-bit key and CBC mode. ---| '"ARIA-256-CBC"' # Aria cipher with 256-bit key and CBC mode. ---| '"ARIA-128-CFB128"' # Aria cipher with 128-bit key and CFB-128 mode. ---| '"ARIA-192-CFB128"' # Aria cipher with 192-bit key and CFB-128 mode. ---| '"ARIA-256-CFB128"' # Aria cipher with 256-bit key and CFB-128 mode. ---| '"ARIA-128-CTR"' # Aria cipher with 128-bit key and CTR mode. ---| '"ARIA-192-CTR"' # Aria cipher with 192-bit key and CTR mode. ---| '"ARIA-256-CTR"' # Aria cipher with 256-bit key and CTR mode. ---| '"ARIA-128-GCM"' # Aria cipher with 128-bit key and GCM mode. ---| '"ARIA-192-GCM"' # Aria cipher with 192-bit key and GCM mode. ---| '"ARIA-256-GCM"' # Aria cipher with 256-bit key and GCM mode. ---| '"ARIA-128-CCM"' # Aria cipher with 128-bit key and CCM mode. ---| '"ARIA-192-CCM"' # Aria cipher with 192-bit key and CCM mode. ---| '"ARIA-256-CCM"' # Aria cipher with 256-bit key and CCM mode. ---| '"AES-128-OFB"' # AES 128-bit cipher in OFB mode. ---| '"AES-192-OFB"' # AES 192-bit cipher in OFB mode. ---| '"AES-256-OFB"' # AES 256-bit cipher in OFB mode. ---| '"AES-128-XTS"' # AES 128-bit cipher in XTS block mode. ---| '"AES-256-XTS"' # AES 256-bit cipher in XTS block mode. ---| '"CHACHA20"' # ChaCha20 stream cipher. ---| '"CHACHA20-POLY1305"' # ChaCha20-Poly1305 AEAD cipher. ---@alias CipherPadding ---|>'"NONE"' # Never pad (full blocks only). ---| '"PKCS7"' # PKCS7 padding (default). ---| '"ISO7816_4"' # ISO/IEC 7816-4 padding. ---| '"ANSI923"' # ANSI X.923 padding. ---| '"ZERO"' # Zero padding (not reversible). ---@class _cipher:userdata Cipher context. local _cipher = {} ---Create a cipher context. ---@param type CipherType Cipher type. ---@return _cipher context Cipher context. function cipher.create(type) end ---Return the length of the key in bytes. ---@return integer bytes The key length. function _cipher:getKeyLen() end ---Return the length of the initialization vector (IV) in bytes. ---@return integer bytes The IV length. function _cipher:getIVLen() end ---Set the padding mode, for cipher modes that use padding. ---@param padding CipherPadding The padding mode. ---@return boolean status true on success, false on failure. function _cipher:setPadding(padding) end ---Begin a encryption/decryption process. ---@param op '"encrypt"' |'"decrypt"' Operation. ---@param key string The key to use. ---@param iv? string The initialization vector (IV). ---@return boolean status true on success, false on failure. function _cipher:begin(op, key, iv) end ---The generic cipher update function. ---@param input string Input binary data. ---@return string|nil output Output binary data. function _cipher:update(input) end ---Finsh the encryption/decryption process. ---@return string|nil output Output binary data. function _cipher:finsh() end return cipher
local model = require "sailor.model" local helper = require "tests.helper" local access = require "sailor.access" local db = require "sailor.db" local fixtures = require "tests.fixtures.user" or {} describe("Testing #UserModel", function() --helper.blah() local User = model('user') local users = User:find_all() local u, count_before local db_spies = {} local db_spies_count = 0 local function assert_db_close(n) n = n or 1 db_spies_count = db_spies_count + n assert.spy(db_spies[1]).was_called(db_spies_count) assert.spy(db_spies[2]).was_called(db_spies_count) end setup(function() table.insert(db_spies, spy.on(db,'connect')) table.insert(db_spies, spy.on(db,'close')) end) it("should count objects", function() assert.is_equal(#users,User:count()) assert_db_close() end) it("should create different objects", function() u = User:new(fixtures[1]) u2 = User:new(fixtures[2]) assert.is_equal(u.name,fixtures[1].name) assert.is_equal(u2.name,fixtures[2].name) end) it("should save object", function() local s = spy.on(User,'validate') local s2 = spy.on(User,'insert') count_before = User:count() u = User:new(fixtures[1]) assert.is_true(u:save(false)) assert.is_equal(User:count(),count_before+1) assert.spy(s).was_not_called() assert.spy(s2).was_called() assert_db_close(3) end) it("should update object", function() local s = spy.on(User,'update') u.username = users[2].username or nil assert.is_true(u:save(false)) -- On update it is opening and closing db connection twice -- first for verifying if the entry exists -- maybe this should be revised assert_db_close(2) assert.spy(s).was_called() end) it("should delete object", function() u:delete() assert.is_equal(User:count(),count_before) assert_db_close(2) end) it("should find object by id", function() u = User:find_by_id(1) assert.are_same(u.id,users[1].id) assert_db_close() end) it("should find user relations", function() u = User:find_by_id(1) local post_fixtures = require "tests.fixtures.post" or {} local amount = 0 for k, v in ipairs(post_fixtures) do if v.author_id == 1 then amount = amount + 1 assert.is_equal(u.posts[amount].body,v.body) end end assert.is_equal(amount,#(u.posts)) assert_db_close(2) end) it("should not find object by id", function() local u = User:find_by_id(42) assert.is_false(u) assert_db_close() end) it("should find object by attributes", function() local u = User:find_by_attributes({username = users[1].username}) assert.are_same(u.id,users[1].id) assert_db_close() end) it("should not find object by attributes", function() local u = User:find_by_attributes({username = ''}) assert.is_false(u) assert_db_close() end) it("should validate object", function() assert.is_true(users[1]:validate()) end) it("should not validate object", function() assert.is_false(users[2]:validate()) end) it("should find all objects", function() assert.is_equal(User:count(),#(User:find_all())) assert_db_close(2) end) it("should find some objects", function() assert.is_equal(2,#(User:find_all("password LIKE '12345%'"))) assert_db_close() end) it("should find one object", function() u = User:find("password LIKE '12345%'") assert.is_equal(users[1].id,u.id) assert_db_close() end) it("should login", function() assert.is_true(User.authenticate(fixtures[1].username,fixtures[1].password,false)) assert_db_close() end) it("should know the user is logged in", function() assert.is_false(access.is_guest()) end) it("should logout", function() assert.is_true(User.logout()) end) it("should know the user is logged out", function() assert.is_true(access.is_guest()) end) it("should create objects but rollback", function() local Post = model('post') count_before = User:count() local count_post = Post:count() assert_db_close(2) db.begin_transaction() u = User:new(fixtures[1]) assert.is_true(u:save(false)) assert.is_equal(User:count(),count_before+1) local p = Post:new() p.author_id = u.id assert.is_true(p:save(false)) assert.is_equal(Post:count(),count_post+1) db.rollback() assert_db_close() assert.is_equal(User:count(),count_before) assert.is_equal(Post:count(),count_post) assert_db_close(2) end) it("should create objects and commit", function() local Post = model('post') count_before = User:count() local count_post = Post:count() assert_db_close(2) db.begin_transaction() u = User:new(fixtures[1]) assert.is_true(u:save(false)) assert.is_equal(User:count(),count_before+1) local p = Post:new() p.author_id = u.id assert.is_true(p:save(false)) assert.is_equal(Post:count(),count_post+1) db.commit() assert_db_close() assert.is_equal(User:count(),count_before+1) assert.is_equal(Post:count(),count_post+1) assert_db_close(2) end) end)
--[[ Copyright (C) 2018 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] -- A user-controlled system for pseudo-random number generation. -- Helper functions also use this as a source of randomness. local sys_random = require 'dmlab.system.random' local MAP_COUNT = 100000 local THEME_COUNT = 1000 local random = {} --[[ Set the seed of the underlying pseudo-random-bit generator. The argument may be a number or a string representation of a number. Beware of precision loss when using very large numeric values. It is probably useful to call this function with the per-episode seed in the "start" callback so that episodes play out reproducibly. ]] function random:seed(value) return self._rng:seed(value) end -- Returns an integer sampled uniformly at random from the closed range -- [1, MAP_COUNT]. function random:mapGenerationSeed() return self._rng:uniformInt(1, MAP_COUNT) end -- Returns an integer sampled uniformly at random from the closed range -- [1, THEME_COUNT]. function random:themeGenerationSeed() return self._rng:uniformInt(1, THEME_COUNT) end -- Returns an integer sampled uniformly at random from the closed range -- [lower, upper]. function random:uniformInt(lower, upper) return self._rng:uniformInt(lower, upper) end -- Returns a real number sampled uniformly at random from the half-open range -- [lower, upper). function random:uniformReal(lower, upper) return self._rng:uniformReal(lower, upper) end -- Returns an integer in the range [1, n] where the probability of each -- integer i is the ith weight divided by the sum of the n weights. function random:discreteDistribution(weights) return self._rng:discreteDistribution(weights) end -- Returns a real number sampled from the random distrubution centered around -- mean with standard distribution stddev. function random:normalDistribution(mean, stddev) return self._rng:normalDistribution(mean, stddev) end -- Returns an 8-bit triplet representing a random RGB color: -- {0~255, 0~255, 0~255}. function random:color() local function uniform255() return self._rng:uniformInt(0, 255) end return {uniform255(), uniform255(), uniform255()} end -- Returns an element sampled uniformly at random from a table. You can specify -- a consecutive part of the table to sample by specifying startIndex and -- endIndex. By default the entire table will be used. function random:choice(t, startIndex, endIndex) t = t or {} if not startIndex or startIndex < 1 then startIndex = 1 end if not endIndex or endIndex > #t then endIndex = #t end if startIndex > endIndex then return nil end return t[self._rng:uniformInt(startIndex, endIndex)] end -- Shuffles a Lua array in place. If n is given, the shuffle stops after the -- first n elements have been placed. 'n' is clamped to the size of the array. function random:shuffleInPlace(array, n) local c = (n and n < #array) and n or #array - 1 for i = 1, c do local j = self._rng:uniformInt(i, #array) array[j], array[i] = array[i], array[j] end return array end -- Returns a shuffled copy of a Lua array. function random:shuffle(array) local ret = {} for i, obj in ipairs(array) do ret[i] = obj end return self:shuffleInPlace(ret) end function random:generator() return self._rng end --[[ Returns a 'sampling without replacement' number generator with the integer range range [1, count]. Generator's memory grows linearly. Initialization and calling costs are both O(1). The generator returns nil when no new samples are available and resets to its initial state. --]] function random:shuffledIndexGenerator(count) -- The number of values that have been generated so far. local current = 0 -- A sparse array of shuffled values. local elements = {} --[[ All values <= current that are *not* in the completed shuffling. completed These values are at indices that *are* in shuffling the completed shuffling. elements [+++++++++++|--+---------+--++----------+----------+--] . . . . . . 1 current count Invariant A: All values <= current will be in `elements`. Invariant B: Every value in the completed shuffling has elements[value] ~= nil. The algorithm starts with current = 0 and elements empty, so the invariants start true. The algorithm increments as follows, 1. Increment current current = current + 1 2. Generate `random`, a random value in the range [current, count] random = randomNumberInRange(current, count) 3. Basic operation: (a) output `random` as the next completed shuffling value; that is, insert `random` at elements[current]. elements[random] is nil ==> elements[current] = random (b) insert `current` at elements[random]. elements[current] is nil ==> elements[random] = current Exception operations: - If elements[current] already has a value, then (by invariant B), current is already in the completed shuffling. In this case we should avoid (b) and instead push the existing elements[current] back into elements[random]. elements[current] has a value ==> elements[random] = elements[current] - If elements[random] already has a value, then (by invariant B), random is already in the completed shuffling. In this case we should avoid (a) and instead output the deferred value elements[random] in the completed shuffling. elements[random] has a value ==> elements[current] = elements[random] Note that both the basic and exception operations maintain the invariants, so by induction the invariants are always true. --]] return function() -- If we've shuffled all the elements, return nil for one call and reset -- to initial conditions. The caller can start again if a new shuffling is -- desired. if count == current then elements = {} current = 0 return nil end -- Step 1. current = current + 1 -- Step 2. local random = self._rng:uniformInt(current, count) -- Step 3. local currentStartValue = elements[current] elements[current] = elements[random] or random elements[random] = currentStartValue or current -- Return the tail of the completed shuffling that we just generated. return elements[current] end end local randomMT = {__index = random} function randomMT:__call(rng) return setmetatable({_rng = rng}, randomMT) end return setmetatable({_rng = sys_random}, randomMT)
return { STOP = 0, VOID = 1, BOOL = 2, BYTE = 3, I08 = 3, DOUBLE = 4, I16 = 6, I32 = 8, I64 = 10, STRING = 11, UTF7 = 11, STRUCT = 12, MAP = 13, SET = 14, LIST = 15, UTF8 = 16, UTF16 = 17 }
local awful = require("awful") do local cmds = { "lxpolkit", "xautolock -time 15 -locker 'dm-tool lock;gpg-connect-agent reloadagent /bye'", "clipmenud", "xfce4-power-manager", } for _, i in pairs(cmds) do awful.spawn.with_shell(i .. "&") end end
----------------------------------------- -- ID: 6565 -- Item: Persikos Snow Cone -- Food Effect: 5 minutes, all Races ----------------------------------------- -- MP +35% (Max. 50 @ 143 Base MP) -- INT +3 -- [Element: Air]+5 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(tpz.effect.FOOD) or target:hasStatusEffect(tpz.effect.FIELD_SUPPORT_FOOD) then result = tpz.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(tpz.effect.FOOD,0,0,300,6565) end function onEffectGain(target,effect) target:addMod(tpz.mod.FOOD_MPP, 35) target:addMod(tpz.mod.FOOD_MP_CAP, 50) target:addMod(tpz.mod.INT, 3) target:addMod(tpz.mod.WINDDEF, 5) end function onEffectLose(target, effect) target:delMod(tpz.mod.FOOD_MPP, 35) target:delMod(tpz.mod.FOOD_MP_CAP, 50) target:delMod(tpz.mod.INT, 3) target:delMod(tpz.mod.WINDDEF, 5) end
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). Clockwork was created by Conna Wiles (also known as kurozael.) http://cloudsixteen.com/license/clockwork.html --]] local COMMAND = Clockwork.command:New("DoorSetParent"); COMMAND.tip = "Set the active parent door to your target."; COMMAND.flags = CMD_DEFAULT; COMMAND.access = "a"; -- Called when the command has been run. function COMMAND:OnRun(player, arguments) local door = player:GetEyeTraceNoCursor().Entity; if (IsValid(door) and Clockwork.entity:IsDoor(door)) then cwDoorCmds.infoTable = cwDoorCmds.infoTable or {}; player.cwParentDoor = door; cwDoorCmds.infoTable.Parent = door; for k, parent in pairs(cwDoorCmds.parentData) do if (parent == door) then table.insert(cwDoorCmds.infoTable, k); end; end; Clockwork.player:Notify(player, {"YouSetActiveParentDoor"}); if (cwDoorCmds.infoTable != {}) then Clockwork.datastream:Start(player, "doorParentESP", cwDoorCmds.infoTable); end; else Clockwork.player:Notify(player, {"ThisIsNotAValidDoor"}); end; end; COMMAND:Register();
function isAtBlock(dialogObject, x, y, z) return dialogObject:isAtBlock(x,y,z); end function callTutorialHookFunc(dialogObject, turorial) return dialogObject:callTutorial(turorial); end function unhireHookFunc(dialogObject) return dialogObject:unhireConverationPartner(); end function hireHookFunc(dialogObject) return dialogObject:hireConverationPartner(); end function alwaysTrueHookFunc(dialogObject) return true; end function activateBlockHookFunc(dialogObject, x, y, z, active) return dialogObject:activateBlock(x, y, z, active); end function activateBlockSwitchHookFunc(dialogObject, x, y, z) return dialogObject:activateBlockSwitch(x,y,z); end function giveHelmetHookFunc(dialogObject) return dialogObject:giveHelmet(0); end function giveRocketLauncherHookFunc(dialogObject) return dialogObject:giveRocketLauncher(0); end function giveSniperRifleHookFunc(dialogObject) return dialogObject:giveSniperRifle(0); end function giveLaserWeaponHookFunc(dialogObject) return dialogObject:giveLaserWeapon(0); end function moveToHookFunc(dialogObject, x, y, z) return dialogObject:moveTo(x,y,z); end function giveGravityHookFunc(dialogObject, gravBool) return dialogObject:giveGravity(gravBool); end function giveTypeHookFunc(dialogObject, type, count) return dialogObject:giveType(type, count); end function mainConversationState(dialogObject) end function create(dialogObject, bindings) dSysClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogSystem" ); dSysFactoryClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogStateMachineFactory" ); dSysEntryClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogStateMachineFactoryEntry" ); hookClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua" ); dSys = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogSystem", dialogObject ); hireHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "hireHookFunc", {} ); unhireHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "unhireHookFunc", {} ); activateBlockHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "activateBlockHookFunc", {8,9,9,true} ); activateBlockSwitchHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "activateBlockSwitchHookFunc",{8,9,9} ); giveHelmetHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveHelmetHookFunc", {} ); giveRocketLauncherHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveRocketLauncherHookFunc", {} ); giveSniperRifleHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveSniperRifleHookFunc", {} ); giveLaserWeaponHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveLaserWeaponHookFunc", {} ); moveToHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "moveToHookFunc", {-6,9,7} ); isAtBlockHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "isAtBlock", {-6,9,7} ); moveToHook2 = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "moveToHookFunc", {8,9,8} ); isAtBlockHook2 = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "isAtBlock", {8,9,8} ); moveToHook3 = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "moveToHookFunc", {4,9,8} ); isAtBlockHook3 = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "isAtBlock", {4,9,8} ); doorOpenHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "activateBlockHookFunc", {-6,9,13, false} ); doorCloseHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "activateBlockHookFunc", {6,9,8, true} ); moveToHook4 = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "moveToHookFunc", {0,9,8} ); shipFlyTutHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "callTutorialHookFunc", {"TutorialBasics02ShipBasics"} ); alwaysTrueHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "alwaysTrueHookFunc", {} ); giveGravityHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveGravityHookFunc", {true} ); giveTypeHook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "giveTypeHookFunc", {1,100}); factory = dSys:getFactory(bindings); s0 = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "Greetings ".. dialogObject:getEntity():getName() ..", I'm \"NPC-01\"!\n\n" .. "I will teach you about one of the most important things in the StarMade Universe: Ships!\n" , 2000 ); s1 = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "Block count is not all that matters, the architecture and design also has an important role on the effectiveness\n".. "and efficiency of every structure in StarMade.\n\n".. "For now we are only talking about Ships.\n" , 2000 ); s2 = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "Every ship has a core. A core is the heart of a ship, and without it the ship will not\n".. "function, so be sure to protect it at any cost.\n\n" .. "Additionally the core block will serve as your vessel's point of control,\n" .. "so be sure you keep that in mind when building.\n" , 2000 ); s3 = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "That over there is a small pre-built ship. The core is at the centre.\n".. "You can enter the core by pressing 'R', and take control of the ship.\n\n" , 2000 ); -- enter tutorial state. let player fly over to other player sEnd = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "I've taught you everything I know.\n" .. "Talk to NPC-02 for the next steps in the tutorial!\n\nHave a good time!" , 2000 ); okEntry0 = luajava.newInstance( "org.schema.game.common.data.player.dialog.CancelDialogEntry", "Ok", 2000 ); okEntry1 = luajava.newInstance( "org.schema.game.common.data.player.dialog.CancelDialogEntry", "Ok", 2000 ); okEntry2 = luajava.newInstance( "org.schema.game.common.data.player.dialog.CancelDialogEntry", "Ok", 2000 ); okEntry3 = luajava.newInstance( "org.schema.game.common.data.player.dialog.CancelDialogEntry", "Ok", 2000 ); s0:setEntryMarking("s0"); s1:setEntryMarking("s1"); s2:setEntryMarking("s2"); s3:setEntryMarking("s3"); sEnd:setEntryMarking("sEnd");sEnd:setAwnserEntry(false); s0:add(s1, "Tell me about ships!"); s0:setHook(giveGravityHook); s0:addReaction(giveGravityHook, -1, s0); s0:addReaction(giveGravityHook, 0, s0); s0:addReaction(giveGravityHook, 1, s0); s1:setHook(moveToHook); moveToHook:setStartState("s1"); moveToHook:setEndState("s1"); s1:addReaction(moveToHook, -1, s1); s1:addReaction(moveToHook, 0, s1); s1:addReaction(moveToHook, 1, s1); s1:add(sEnd, "You should not see this ->(sEnd)"); s1:add(s2, "I see!"); s2:add(s3, "The Ship Core is important, got it!"); s3:add(okEntry3, "Ok!"); okEntry3:setHook(doorOpenHook); doorOpenHook:setFollowUp(shipFlyTutHook); doorOpenHook:setCondition(alwaysTrueHook); doorOpenHook:setStartState("sEnd"); doorOpenHook:setEndState("sEnd"); shipFlyTutHook:setStartState("sEnd"); shipFlyTutHook:setEndState("sEnd"); factory:setRootEntry(s0); dSys:add(factory) return dSys --frame = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogSystem", "Texts" ); --frame:test() end
function Makazradon_OnEnterCombat(Unit,Event) Unit:RegisterEvent("Makazradon_Cripple", 45000, 0) Unit:RegisterEvent("Makazradon_FelCleave", 19000, 0) Unit:RegisterEvent("Makazradon_RainOfFire", 18000, 0) end function Makazradon_Cripple(Unit,Event) Unit:FullCastSpellOnTarget(11443,Unit:GetClosestPlayer()) end function Makazradon_FelCleave(Unit,Event) Unit:FullCastSpellOnTarget(38742,Unit:GetClosestPlayer()) end function Makazradon_RainOfFire(Unit,Event) Unit:FullCastSpellOnTarget(38741,Unit:GetClosestPlayer()) end function Makazradon_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Makazradon_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent(21501, 1, "Makazradon_OnEnterCombat") RegisterUnitEvent(21501, 2, "Makazradon_OnLeaveCombat") RegisterUnitEvent(21501, 4, "Makazradon_OnDied")
function opponentNoteHit() health = getProperty('health') if getProperty('health') > 0.1 then setProperty('health', health- 0.0095); end end function onStepHit() if curStep == 30 then noteTweenAlpha("NoteAlphal1", 0, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal2", 1, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal3", 2, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal4", 3, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal5", 4, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal6", 5, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal7", 6, 1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal8", 7, 1, 0.5, cubelnout) end if curStep == 55 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 60 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 65 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 70 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 75 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 80 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 85 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 90 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 95 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 100 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 105 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 110 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 115 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 120 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 125 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 130 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 135 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 140 then noteTweenY("NoteMove1", 4, 20, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 20, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 20, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 20, 0.5, cubelnout) end if curStep == 185 then noteTweenX("NoteMove1", 4, 900, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 900, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 900, 0.5, cubelnout) end if curStep == 190 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 200 then noteTweenAlpha("NoteAlphal1", 0, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal2", 1, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal3", 2, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal4", 3, -1, 0.5, cubelnout) end if curStep == 205 then noteTweenX("NoteMove1", 4, 900, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 900, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 900, 0.5, cubelnout) end if curStep == 210 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 215 then noteTweenX("NoteMove1", 4, 900, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 900, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 900, 0.5, cubelnout) end if curStep == 220 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 225 then noteTweenX("NoteMove1", 4, 900, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 900, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 900, 0.5, cubelnout) end if curStep == 230 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 235 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 240 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 245 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 250 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 255 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 260 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 265 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 270 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 275 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 280 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 300 then noteTweenX("NoteMove1", 4, 0, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 0, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 0, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 0, 0.5, cubelnout) end if curStep == 305 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep ==310 then noteTweenAngle("NoteAngle1", 4, 3500, 15.0, cubeInout) noteTweenAngle("NoteAngle2", 5, 3500, 15.0, cubeInout) noteTweenAngle("NoteAngle3", 6, 3500, 15.0, cubeInout) noteTweenAngle("NoteAngle4", 7, 3500, 15.0, cubeInout) end if curStep == 315 then noteTweenX("NoteMove1", 4, 0, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 0, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 0, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 0, 0.5, cubelnout) end if curStep == 320 then noteTweenX("NoteMove1", 4, 700, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 800, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 900, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 325 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 350 then noteTweenX("NoteMove1", 4, 1000, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 900, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 800, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 700, 0.5, cubelnout) end if curStep == 1 then noteTweenAlpha("NoteAlphal1", 0, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal2", 1, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal3", 2, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal4", 3, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal5", 4, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal6", 5, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal7", 6, -1, 0.5, cubelnout) noteTweenAlpha("NoteAlphal8", 7, -1, 0.5, cubelnout) end if curStep == 315 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 320 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 325 then noteTweenY("NoteMove1", 4, 10, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 10, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 10, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 10, 0.5, cubelnout) end if curStep == 330 then noteTweenY("NoteMove1", 4, 150, 0.5, cubelnout) noteTweenY("NoteMove2", 5, 150, 0.5, cubelnout) noteTweenY("NoteMove3", 6, 150, 0.5, cubelnout) noteTweenY("NoteMove4", 7, 150, 0.5, cubelnout) end if curStep == 340 then noteTweenX("NoteMove1", 4, 1000, 0.5, cubelnout) noteTweenX("NoteMove2", 5, 1000, 0.5, cubelnout) noteTweenX("NoteMove3", 6, 1000, 0.5, cubelnout) noteTweenX("NoteMove4", 7, 1000, 0.5, cubelnout) end if curStep == 1 then makeLuaText("subtitles", "Esse ModChart foi feito por DotorBiscoito", 500, 400, 550) addLuaText("subtitles") elseif curStep == 20 then setTextString("subtitles", "Não Mecha No ModChart") elseif curStep == 40 then removeLuaText("subtitles", true) end if curStep == 3 then showOnlyStrums = true end end
local ternary = function(condition, positive, negative) if condition then return positive end return negative end local BinarySearchTree = {} function BinarySearchTree:new() local obj = {} self.__index = self self._root = nil return setmetatable(obj, self) end function BinarySearchTree:is_root(value) return self._root.value == value end function BinarySearchTree:is_leaf(value) local found = false local current = self._root while found == false and current ~= nil do -- if value is smaller than current, then to go the left if value < current.value then current = current.left -- if value is bigger than current, then to go the right elseif value > current.value then current = current.right -- else we found it! :D else found = true end end -- if node doesn't have children, it's a leaf return found and current.left == nil and current.right == nil end function BinarySearchTree:_create_node(value) return { value = value, left = nil, right = nil } end function BinarySearchTree:add(value) local node = self:_create_node(value) -- if it's the first node, it's the root if self._root == nil then self._root = node return true end local current = self._root while true do -- if the value is smaller than the current, -- this value should go to left of the tree if value < current.value then -- if there's no left node, then the new node should be create there if current.left == nil then current.left = node return true -- if not, the program continues though the left node else current = current.left end -- if the value is bigger than the current, -- this value should go to right of the tree elseif value > current.value then -- if there's no right node, then the new node should be create there if current.right == nil then current.right = node return true -- if not, the program continues though the right node else current = current.right end else return false end end end function BinarySearchTree:contains(value) local found = false local current = self._root -- when value is less than the current node, go left -- when value is greater than the current node, go right -- when the values are equal, we found it! while not found and current do if value < current.value then current = current.left elseif value > current.value then current = current.right else found = true end end return found end function BinarySearchTree:remove(value) local found = false local current = self._root local parent = nil -- search and picks up the node to remove while not found and current do if value < current.value then parent = current current = current.left elseif value > current.value then parent = current current = current.right else found = true end end if not found then return false end -- figure out how many children the node has local child_count = ternary(current.left ~= nil, 1, 0) + ternary(current.right ~= nil, 1, 0) -- when the node is the root if current == self._root then -- if node doesn't have children, just remove it if child_count == 0 then self._root = nil return true end -- when it has one child, move child to the root if child_count == 1 then self._root = ternary(current.right == nil, current.left, current.right) return true end if child_count == 2 then local replacement = self._root.left local replacement_parent = nil -- figure out the right-most leaf node to be the new root while replacement.right ~= nil do replacement_parent = replacement replacement = replacement.right end -- it's not the first node on the left if replacement_parent ~= nil then replacement_parent.right = replacement.left replacement.right = self._root.right replacement.left = self._root.left else -- assign the childre replacement.right = self._root.right end -- assign the new root self._root = replacement return true end -- when value is not in the root else if child_count == 0 then -- if the value is less than its parent's, null out to the left pointer if current.value < parent.value then parent.left = nil -- if not, null out to the right pointer else parent.right = nil end return true end if child_count == 1 then -- if the value is less than its parent's, reset the pointer of the left if current.value < parent.value then parent.left = ternary(current.left == nil, current.right, current.left) -- if the value is greater than its parent's, reset the pointer of the right else parent.right = ternary(current.left == nil, current.right, current.left) end return true end if child_count == 2 then replacement = current.left replacement_parent = current -- pick up the right-most node while replacement.right ~= nil do replacement_parent = replacement replacement = replacement.right end -- assign children to the replacement replacement_parent.right = replacement.left replacement.right = current.right replacement.left = current.left if current.value < parent.value then parent.left = replacement else parent.right = replacement end end return true end end function BinarySearchTree:size() local size = 0 self:traverse(function() size = size + 1 end) return size end function BinarySearchTree:destroy() self:traverse(function(node) self:remove(node.value) end) return true end function BinarySearchTree:get_smallest() function _find(node) local current = node -- make a loop while there's left node while current.left ~= nil do current = current.left end -- return the last node of left return current.value end return _find(self._root, 0) end function BinarySearchTree:get_biggest() function _find(node) local current = node -- make a loop while there's right node while current.right ~= nil do current = current.right end -- return the last node of right return current.value end return _find(self._root, 0) end function BinarySearchTree:_max_depth(node) if node == nil then return 0 end return 1 + math.max(self:_max_depth(node.left), self:_max_depth(node.right)) end function BinarySearchTree:_min_depth(node) if node == nil then return 0 end return 1 + math.min(self:_min_depth(node.left), self:_min_depth(node.right)) end function BinarySearchTree:is_balanced() return (self:_max_depth(self._root) - self:_min_depth(self._root) <= 1) end function BinarySearchTree:in_order(callback) -- first, traverse to the left, then to root and -- then to the right function _in_order(node) if node == nil then return end _in_order(node.left) callback(node) _in_order(node.right) end _in_order(self._root) end function BinarySearchTree:pre_order(callback) -- first of all, root -- after traverse to left and -- then to the right function _pre_order(node) if node == nil then return end callback(node) _pre_order(node.left) _pre_order(node.right) end _pre_order(self._root) end function BinarySearchTree:post_order(callback) -- first, traverse to left -- then to right -- then to root function _post_order(node) if node == nil then return end _post_order(node.left) _post_order(node.right) callback(node) end _post_order(self._root) end function BinarySearchTree:traverse(callback) self:in_order(callback) end return BinarySearchTree
--[[ -- added by passion @ 2019/11/14 16:39:51 -- UIBoardUIMain模型层 -- 注意: -- 1、成员变量预先在OnCreate、OnEnable函数声明,提高代码可读性 -- 2、OnCreate内放窗口生命周期内保持的成员变量,窗口销毁时才会清理 -- 3、OnEnable内放窗口打开时才需要的成员变量,窗口关闭后及时清理 -- 4、OnEnable函数每次在窗口打开时调用,可传递参数用来初始化Model --]] local UUIBoardNPCModel = BaseClass("UUIBoardNPCModel", UIBaseModel) local base = UIBaseModel-- 创建 local function OnCreate(self) base.OnCreate(self) -- 窗口生命周期内保持的成员变量放这 end -- 打开 local function OnEnable(self, owner, height) base.OnEnable(self) self.owner = owner; self.target = owner.transform; self.height = height or 1.9; end -- 关闭 local function OnDestroy(self) base.OnDestroy(self) -- 清理成员变量 end UUIBoardNPCModel.OnCreate = OnCreate UUIBoardNPCModel.OnEnable = OnEnable UUIBoardNPCModel.OnDisable = OnDisable UUIBoardNPCModel.OnDestroy = OnDestroy return UUIBoardNPCModel
local lookuptable = { [":"] = "=",["["] = "{",["]"] = "}",["\""]="",["("]="[",[")"]="]",} local function replaceIntKey(s1) return "("..s1.."):" end function str2Table(retStr) local contentStr = retStr local bHasStr = false local string=string local tonumber = tonumber contentStr = string.gsub(contentStr,"\"(%d+)\":",replaceIntKey) contentStr = string.gsub(contentStr,"[\":%[%]%(%)]",lookuptable) local tempTable = { "do local _=",contentStr," return _ end" } contentStr = table.concat(tempTable,"\n") local serpent= require("src/utils/serpent") local ok,jsonObj= serpent.load(contentStr) if ok ~= true then print(ok) end assert(ok,ok) return jsonObj end
while true do local left = redstone.getInput("left") if left then for i = 0, 15 do redstone.setAnalogOutput("right", i) os.sleep(0.2) end os.sleep(5) redstone.setAnalogOutput("right", 0) print("Input found") else print("No input") end os.queueEvent("fakeEvent") os.pullEvent() end
vim.g.FerretExecutableArguments = { rg = '--vimgrep --no-heading --no-config --max-columns 4096 --hidden --glob !.git', }
--- A builtin build system: back-end to provide a portable way of building C-based Lua modules. local builtin = {} local unpack = unpack or table.unpack local fs = require("luarocks.fs") local path = require("luarocks.path") local util = require("luarocks.util") local cfg = require("luarocks.core.cfg") local dir = require("luarocks.dir") function builtin.autodetect_external_dependencies(build) if not build or not build.modules then return nil end local extdeps = {} local any = false for _, data in pairs(build.modules) do if type(data) == "table" and data.libraries then local libraries = data.libraries if type(libraries) == "string" then libraries = { libraries } end local incdirs = {} local libdirs = {} for _, lib in ipairs(libraries) do local upper = lib:upper():gsub("%+", "P"):gsub("[^%w]", "_") any = true extdeps[upper] = { library = lib } table.insert(incdirs, "$(" .. upper .. "_INCDIR)") table.insert(libdirs, "$(" .. upper .. "_LIBDIR)") end if not data.incdirs then data.incdirs = incdirs end if not data.libdirs then data.libdirs = libdirs end end end return any and extdeps or nil end local function autoextract_libs(external_dependencies, variables) if not external_dependencies then return nil, nil, nil end local libs = {} local incdirs = {} local libdirs = {} for name, data in pairs(external_dependencies) do if data.library then table.insert(libs, data.library) table.insert(incdirs, variables[name .. "_INCDIR"]) table.insert(libdirs, variables[name .. "_LIBDIR"]) end end return libs, incdirs, libdirs end do local function get_cmod_name(file) local fd = io.open(dir.path(fs.current_dir(), file), "r") if not fd then return nil end local data = fd:read("*a") fd:close() return (data:match("int%s+luaopen_([a-zA-Z0-9_]+)")) end local skiplist = { ["spec"] = true, [".luarocks"] = true, ["lua_modules"] = true, ["test.lua"] = true, ["tests.lua"] = true, } function builtin.autodetect_modules(libs, incdirs, libdirs) local modules = {} local install local copy_directories local prefix = "" for _, parent in ipairs({"src", "lua", "lib"}) do if fs.is_dir(parent) then fs.change_dir(parent) prefix = parent.."/" break end end for _, file in ipairs(fs.find()) do local base = file:match("^([^\\/]*)") if not skiplist[base] then local luamod = file:match("(.*)%.lua$") if luamod then modules[path.path_to_module(file)] = prefix..file else local cmod = file:match("(.*)%.c$") if cmod then local modname = get_cmod_name(file) or path.path_to_module(file:gsub("%.c$", ".lua")) modules[modname] = { sources = prefix..file, libraries = libs, incdirs = incdirs, libdirs = libdirs, } end end end end if prefix ~= "" then fs.pop_dir() end local bindir = (fs.is_dir("src/bin") and "src/bin") or (fs.is_dir("bin") and "bin") if bindir then install = { bin = {} } for _, file in ipairs(fs.list_dir(bindir)) do table.insert(install.bin, dir.path(bindir, file)) end end for _, directory in ipairs({ "doc", "docs", "samples", "tests" }) do if fs.is_dir(directory) then if not copy_directories then copy_directories = {} end table.insert(copy_directories, directory) end end return modules, install, copy_directories end end --- Run a command displaying its execution on standard output. -- @return boolean: true if command succeeds (status code 0), false -- otherwise. local function execute(...) io.stdout:write(table.concat({...}, " ").."\n") return fs.execute(...) end --- Driver function for the builtin build back-end. -- @param rockspec table: the loaded rockspec. -- @return boolean or (nil, string): true if no errors occurred, -- nil and an error message otherwise. function builtin.run(rockspec) assert(rockspec:type() == "rockspec") local compile_object, compile_library, compile_static_library local build = rockspec.build local variables = rockspec.variables local checked_lua_h = false local function add_flags(extras, flag, flags) if flags then if type(flags) ~= "table" then flags = { tostring(flags) } end util.variable_substitutions(flags, variables) for _, v in ipairs(flags) do table.insert(extras, flag:format(v)) end end end if cfg.is_platform("mingw32") then compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-c", "-o", object, "-I"..variables.LUA_INCDIR, source, unpack(extras)) end compile_library = function(library, objects, libraries, libdirs) local extras = { unpack(objects) } add_flags(extras, "-L%s", libdirs) add_flags(extras, "-l%s", libraries) extras[#extras+1] = dir.path(variables.LUA_LIBDIR, variables.LUALIB) extras[#extras+1] = "-l" .. (variables.MSVCRT or "m") local ok = execute(variables.LD.." "..variables.LIBFLAG, "-o", library, unpack(extras)) return ok end --[[ TODO disable static libs until we fix the conflict in the manifest, which will take extending the manifest format. compile_static_library = function(library, objects, libraries, libdirs, name) local ok = execute(variables.AR, "rc", library, unpack(objects)) if ok then ok = execute(variables.RANLIB, library) end return ok end ]] elseif cfg.is_platform("win32") then compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-c", "-Fo"..object, "-I"..variables.LUA_INCDIR, source, unpack(extras)) end compile_library = function(library, objects, libraries, libdirs, name) local extras = { unpack(objects) } add_flags(extras, "-libpath:%s", libdirs) add_flags(extras, "%s.lib", libraries) local basename = dir.base_name(library):gsub(".[^.]*$", "") local deffile = basename .. ".def" local def = io.open(dir.path(fs.current_dir(), deffile), "w+") local exported_name = name:gsub("%.", "_") exported_name = exported_name:match('^[^%-]+%-(.+)$') or exported_name def:write("EXPORTS\n") def:write("luaopen_"..exported_name.."\n") def:close() local ok = execute(variables.LD, "-dll", "-def:"..deffile, "-out:"..library, dir.path(variables.LUA_LIBDIR, variables.LUALIB), unpack(extras)) local basedir = "" if name:find("%.") ~= nil then basedir = name:gsub("%.%w+$", "\\") basedir = basedir:gsub("%.", "\\") end local manifestfile = basedir .. basename..".dll.manifest" if ok and fs.exists(manifestfile) then ok = execute(variables.MT, "-manifest", manifestfile, "-outputresource:"..basedir..basename..".dll;2") end return ok end --[[ TODO disable static libs until we fix the conflict in the manifest, which will take extending the manifest format. compile_static_library = function(library, objects, libraries, libdirs, name) local ok = execute(variables.AR, "-out:"..library, unpack(objects)) return ok end ]] else compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-I"..variables.LUA_INCDIR, "-c", source, "-o", object, unpack(extras)) end compile_library = function (library, objects, libraries, libdirs) local extras = { unpack(objects) } add_flags(extras, "-L%s", libdirs) if cfg.gcc_rpath then add_flags(extras, "-Wl,-rpath,%s", libdirs) end add_flags(extras, "-l%s", libraries) if cfg.link_lua_explicitly then extras[#extras+1] = "-L"..variables.LUA_LIBDIR extras[#extras+1] = "-llua" end return execute(variables.LD.." "..variables.LIBFLAG, "-o", library, unpack(extras)) end compile_static_library = function(library, objects, libraries, libdirs, name) local ok = execute(variables.AR, "rc", library, unpack(objects)) if ok then ok = execute(variables.RANLIB, library) end return ok end end local ok, err local lua_modules = {} local lib_modules = {} local luadir = path.lua_dir(rockspec.name, rockspec.version) local libdir = path.lib_dir(rockspec.name, rockspec.version) if not build.modules then if rockspec:format_is_at_least("3.0") then local libs, incdirs, libdirs = autoextract_libs(rockspec.external_dependencies, rockspec.variables) local install, copy_directories build.modules, install, copy_directories = builtin.autodetect_modules(libs, incdirs, libdirs) build.install = build.install or install build.copy_directories = build.copy_directories or copy_directories else return nil, "Missing build.modules table" end end for name, info in pairs(build.modules) do local moddir = path.module_to_path(name) if type(info) == "string" then local ext = info:match("%.([^.]+)$") if ext == "lua" then local filename = dir.base_name(info) if filename == "init.lua" and not name:match("%.init$") then moddir = path.module_to_path(name..".init") else local basename = name:match("([^.]+)$") filename = basename..".lua" end local dest = dir.path(luadir, moddir, filename) lua_modules[info] = dest else info = {info} end end if type(info) == "table" then if not checked_lua_h then local lua_incdir, lua_h = variables.LUA_INCDIR, "lua.h" if not fs.exists(dir.path(lua_incdir, lua_h)) then return nil, "Lua header file "..lua_h.." not found (looked in "..lua_incdir.."). \n" .. "You need to install the Lua development package for your system." end checked_lua_h = true end local objects = {} local sources = info.sources if info[1] then sources = info end if type(sources) == "string" then sources = {sources} end for _, source in ipairs(sources) do local object = source:gsub("%.[^.]*$", "."..cfg.obj_extension) if not object then object = source.."."..cfg.obj_extension end ok = compile_object(object, source, info.defines, info.incdirs) if not ok then return nil, "Failed compiling object "..object end table.insert(objects, object) end local module_name = name:match("([^.]*)$").."."..util.matchquote(cfg.lib_extension) if moddir ~= "" then module_name = dir.path(moddir, module_name) ok, err = fs.make_dir(moddir) if not ok then return nil, err end end lib_modules[module_name] = dir.path(libdir, module_name) ok = compile_library(module_name, objects, info.libraries, info.libdirs, name) if not ok then return nil, "Failed compiling module "..module_name end --[[ TODO disable static libs until we fix the conflict in the manifest, which will take extending the manifest format. module_name = name:match("([^.]*)$").."."..util.matchquote(cfg.static_lib_extension) if moddir ~= "" then module_name = dir.path(moddir, module_name) end lib_modules[module_name] = dir.path(libdir, module_name) ok = compile_static_library(module_name, objects, info.libraries, info.libdirs, name) if not ok then return nil, "Failed compiling static library "..module_name end ]] end end for _, mods in ipairs({{ tbl = lua_modules, perms = "read" }, { tbl = lib_modules, perms = "exec" }}) do for name, dest in pairs(mods.tbl) do fs.make_dir(dir.dir_name(dest)) ok, err = fs.copy(name, dest, mods.perms) if not ok then return nil, "Failed installing "..name.." in "..dest..": "..err end end end if fs.is_dir("lua") then ok, err = fs.copy_contents("lua", luadir) if not ok then return nil, "Failed copying contents of 'lua' directory: "..err end end return true end return builtin
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) --acquire ESX RegisterServerEvent('esx_fork:getPaid') AddEventHandler('esx_fork:getPaid', function(amount) local xPlayer = ESX.GetPlayerFromId(source) --get xPlayer xPlayer.addMoney(math.floor(amount)) end) RegisterServerEvent('esx_fork:getPunished') AddEventHandler('esx_fork:getPunished', function(amount) local xPlayer = ESX.GetPlayerFromId(source) --get xPlayer xPlayer.removeMoney(math.random(amount - 300, amount)) --remove money from player end)
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: group_label.lua -- brief: displays label on units in a group -- author: gunblob -- -- Copyright (C) 2008. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Group Label", desc = "Displays label on units in a group", author = "gunblob", date = "June 12, 2008", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local glPushMatrix = gl.PushMatrix local glTranslate = gl.Translate local glPopMatrix = gl.PopMatrix local glColor = gl.Color local glText = gl.Text local glBillboard = gl.Billboard local spGetGroupList = Spring.GetGroupList local spGetGroupUnits = Spring.GetGroupUnits local spGetUnitViewPosition = Spring.GetUnitViewPosition local SpIsUnitInView = Spring.IsUnitInView local textColor = {0.7, 1.0, 0.7, 1.0} local textSize = 12.0 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Callins -- function widget:Initialize() if Spring.IsReplay() or Spring.GetGameFrame() > 0 then widget:PlayerChanged() end end function widget:PlayerChanged(playerID) if Spring.GetSpectatingState() and Spring.GetGameFrame() > 0 then widgetHandler:RemoveWidget(self) end end function widget:GameStart() widget:PlayerChanged() end -- -- Rendering -- function widget:DrawWorld() local groups = spGetGroupList() for group, _ in pairs(groups) do units = spGetGroupUnits(group) for _, unit in ipairs(units) do if SpIsUnitInView(unit) then local ux, uy, uz = spGetUnitViewPosition(unit) glPushMatrix() glTranslate(ux, uy, uz) glBillboard() glColor(textColor) glText("" .. group, -10.0, -15.0, textSize, "cn") glPopMatrix() end end end end
Drugs.StartProcessActions = function() function processActions() local tasks = {} for rawPlayerId, actions in pairs(Drugs.ProcessActions or {}) do local playerId = tonumber(rawPlayerId or '0') or 0 if (playerId > 0) then table.insert(tasks, function(cb) if (not Drugs.PlayerIsAllowed(playerId, actions.name or 'unknown')) then cb() else local locationName = string.lower(((Drugs.ProcessActions or {})[tostring(playerId)] or {}).name or 'unknown') if (locationName == 'unknown') then cb() else Drugs.TriggerZoneProcessor(playerId, locationName, cb) end end end) end end Async.parallel(tasks, function(results) SetTimeout(1000, processActions) end) end SetTimeout(1000, processActions) end Drugs.SyncNumberOfPolice = function() function syncNumberOfPolice() Drugs.UpdatePolice() SetTimeout(ServerConfig.SyncPoliceInterval, syncNumberOfPolice) end SetTimeout(ServerConfig.SyncPoliceInterval, syncNumberOfPolice) end Drugs.UpdatePolice = function() local xPlayers = Drugs.ESX.GetPlayers() local newNumberOfCops = 0 for _, playerId in pairs(xPlayers or {}) do local xPlayer = Drugs.ESX.GetPlayerFromId(playerId) if (xPlayer ~= nil and xPlayer.job ~= nil and string.lower(xPlayer.job.name) == 'police') then newNumberOfCops = newNumberOfCops + 1 end end Drugs.NumberOfCops = newNumberOfCops end
function toggleShader(thePlayer, apply) triggerClientEvent(thePlayer, "switchRoadshine3", thePlayer, apply) end
data:extend({ { type = "equipment-grid", name = "huge-equipment-grid", width = 20, height = 20, equipment_categories = {"armor"} }, { type = "equipment-grid", name = "mini-equipment-grid", width = 6, height = 4, equipment_categories = {"armor"} }, }) local rob = table.deepcopy(data.raw['roboport-equipment']['personal-roboport-mk2-equipment']) rob.name="personal-roboport-mk3-equipment" rob.take_result = "personal-roboport-mk3-equipment" rob.sprite = { filename = "__FasterEnd__/graphics/personal-roboport-mk3.png", width = 64, height = 64, priority = "medium" } rob.energy_source = { type = "electric", buffer_capacity = "1GJ", input_flow_limit = "5MW", usage_priority = "secondary-input" } rob.charging_energy = "2MW" rob.robot_limit = 50 rob.construction_radius = 50 rob.charging_station_count = 10 local bat = table.deepcopy(data.raw['battery-equipment']['battery-mk2-equipment']) bat.name = "battery-mk3-equipment" bat.sprite = { filename = "__FasterEnd__/graphics/battery-mk3-equipment.png", width = 32, height = 64, priority = "medium" } bat.energy_source = { type = "electric", buffer_capacity = "2GJ", input_flow_limit = "2GW", output_flow_limit = "2GW", usage_priority = "terciary" } local huge_armor = table.deepcopy(data.raw['armor']['power-armor-mk2']) huge_armor.name = "power-armor-mk3" huge_armor.icon = "__FasterEnd__/graphics/power-armor-mk3.png" huge_armor.durability = 50000 huge_armor.equipment_grid = "huge-equipment-grid" huge_armor.inventory_size_bonus = 60 huge_armor.order = "f" huge_armor.resistances = { { type = "physical", decrease = 10, percent = 50 }, { type = "explosion", decrease = 30, percent = 50 }, { type = "acid", decrease = 8, percent = 50 }, { type = "fire", decrease = 5, percent = 50 } } local mini_armor = table.deepcopy(data.raw['armor']['modular-armor']) mini_armor.name = "mini-power-armor" mini_armor.icon = "__FasterStart__/graphics/icons/mini-power-armor.png" mini_armor.resistances = {} mini_armor.durability = 5000 mini_armor.equipment_grid = "mini-equipment-grid" local mini_reactor = table.deepcopy(data.raw['generator-equipment']['fusion-reactor-equipment']) mini_reactor.name = "mini-fusion-reactor-equipment" mini_reactor.sprite = { filename = "__FasterStart__/graphics/equipment/mini-fusion-reactor-equipment.png", width = 65, height = 128, priority = "medium" } mini_reactor.shape = { width = 2, height = 4, type = "full" } mini_reactor.power = "250kW" local flr = table.deepcopy(data.raw['logistic-robot']['logistic-robot']) flr.name = "fusion-logistic-robot" flr.icon = "__FasterEnd__/graphics/fusion-logistic-robot-icon.png" flr.energy_per_tick = "0kJ" flr.energy_per_move = "0kJ" flr.idle = { filename = "__FasterEnd__/graphics/fusion-logistic-robot.png", priority = "high", line_length = 16, width = 41, height = 42, frame_count = 1, shift = {0.015625, -0.09375}, direction_count = 16, y = 42 } flr.idle_with_cargo = { filename = "__FasterEnd__/graphics/fusion-logistic-robot.png", priority = "high", line_length = 16, width = 41, height = 42, frame_count = 1, shift = {0.015625, -0.09375}, direction_count = 16 } flr.in_motion = { filename = "__FasterEnd__/graphics/fusion-logistic-robot.png", priority = "high", line_length = 16, width = 41, height = 42, frame_count = 1, shift = {0.015625, -0.09375}, direction_count = 16, y = 126 } flr.in_motion_with_cargo = { filename = "__FasterEnd__/graphics/fusion-logistic-robot.png", priority = "high", line_length = 16, width = 41, height = 42, frame_count = 1, shift = {0.015625, -0.09375}, direction_count = 16, y = 84 } local fcr = table.deepcopy(data.raw['construction-robot']['construction-robot']) fcr.name = "fusion-construction-robot" fcr.icon = "__FasterStart__/graphics/icons/fusion-construction-robot.png" fcr.minable.result = "fusion-construction-robot" fcr. energy_per_tick = "0kJ" fcr.energy_per_move = "0kJ" fcr.idle.filename = "__FasterStart__/graphics/entity/construction-robot-nuclear.png" fcr.idle.hr_version.filename = "__FasterStart__/graphics/entity/hr-construction-robot.png" fcr.in_motion.filename = "__FasterStart__/graphics/entity/construction-robot-nuclear.png" fcr.in_motion.hr_version.filename = "__FasterStart__/graphics/entity/hr-construction-robot.png" fcr.shadow_idle.filename = "__FasterStart__/graphics/entity/construction-robot-nuclear-shadow.png" fcr.shadow_idle.hr_version.filename = "__FasterStart__/graphics/entity/hr-construction-robot-shadow.png" fcr.shadow_in_motion.filename = "__FasterStart__/graphics/entity/construction-robot-nuclear-shadow.png" fcr.shadow_in_motion.hr_version.filename = "__FasterStart__/graphics/entity/hr-construction-robot-shadow.png" fcr.working.filename = "__FasterStart__/graphics/entity/construction-robot-nuclear-working.png" fcr.working.hr_version.filename = "__FasterStart__/graphics/entity/hr-construction-robot-working.png" fcr.shadow_working.stripes = util.multiplystripes(2, { { filename = "__FasterStart__/graphics/entity/construction-robot-nuclear-shadow.png", width_in_frames = 16, height_in_frames = 1, } }) data:extend({mini_armor,mini_reactor,fcr,flr,huge_armor,bat,rob})
--[[ Copyright (c) 2020 robot256 (MIT License) * Project: Vehicle Wagon 2 rewrite * File: config.lua * Description: Hold constants for data and control phases --]] LOADING_DISTANCE = 10 -- Allowable distance between vehicle and wagon when Loading CAPSULE_RANGE = 12 -- Range in Winch capsule prototype RANGE_COLOR = {r=0.08, g=0.08, b=0, a=0.01} -- Color of the loading/unloaidng range graphics KEEPOUT_RANGE_COLOR = {r=0.12, g=0, b=0, a=0.01} -- Color of the loading/unloaidng range graphics UNLOAD_RANGE = 6 -- Allowable distance between vehicle and wagon when Unloading LOADING_EFFECT_TIME = 120 -- duration of sound and loading ramp beam UNLOADING_EFFECT_TIME = 120 -- duration of sound and loading ramp beam EXTRA_RAMP_TIME = 20 BED_CENTER_OFFSET = -0.6 -- Y offset of center of flatbed used to position icons and loading ramp graphics BED_WIDTH = 0.475 -- Half-Width of flatbed used to position loading ramp graphics MIN_LOADING_RAMP_LENGTH = 1 -- Don't squish the belt so much when right on top of the wagon
local M = { git = { enable = true, }, update_focused_file = { update_cwd = true, }, actions = { open_file = { window_picker = { enable = false, }, }, }, } return M
--[==[ ****THIS MODULE CURRENTLY SUPPORTS LUA 5.1 ONLY! A module that brings pattern matching from functional programming languages into Lua's tables. This module relies heavily on (one-sided) unification. This file refers to a 'substitution hash' which is just a table with keys being "variable" names and values as the values they represent. If the value is nil, then it is a "free variable" and may later be bound to a more concrete value. The value can also be another variable, which will usually be further looked up if it is bound. 10 functions are exported: case, var, is_var, call, DO, match, match_all, match_nomt, match_all_nomt and match_cond --more examples in 'test.lua' and 'examples.lua' local T = require 'TPatterns' local case, match, var, match_cond, match_all = T.case, T.match, T.var, T.match_cond, T.match_all local call, DO, match_nomt, match_all_nomt = T.call, T.DO, T.match_nomt, T.match_all_nomt Usages>> match (obj) { case(c1) - "*result here*", case(c2) - function(t) return 'functions also allowed.' end } local ans = match {2, 4, 6, 8} { case{2, var'x', 6, var'y'} - 'x+y', case{1, 3, 5, var'z'} - 'z' } ans will be 12. match (1) { case(1) - 'true' } returns true match {2, 4, 6, 8} { case{2, var'x', 6, var'y'} - 'x+y', case{1, 3, 5, var'z'} - 'z' } returns 12 match {pi = 3.14, deg = 60, lucky = 7} { case{pi = var'x', deg = 60} - 'x' } returns 3.14 match_all {pi = 3.14, deg = 60, lucky = 7} { case{pi = var'x', deg = 60} - 'x' } returns nil match { case{a = var'x', b = var'y', c = var'z'} - 'z', case{a = var'x'} - 'x' } {a=3, b=5} returns 3 match (point(1, 2)) { case(var'x') - 'x' } returns point(1, 2) match_all {1, 3, a = 5, b = 7} { case{var'_', var'_', a = var'_', b = var'x'} - DO('type(x)', {}) } returns 'number' match {1, 2} { case{var'x', var'x'} - '3', case{var'x', var'_', var'_', var'_'} - '5' } returns nil match_all (pair(3, 4)) { case{fst = 3, snd = 4} - '1', case(pair(3, 4)) - '2' } returns 2 match_nomt (point(1, 2)) { case{ x = var'x', y = var'y' } - 'x+y+135', case(point(1, 2)) - '1' } returns 138 match {a = 1, b = 3, c = 5, d = 7} { case{a = var's', b = var't', c = var'u', d = var'v'} - function(t) return t.s + t.t + t.u + t.v end } returns 16 match_cond (function(x) return (type(x) ~= 'number' and true) or x > 3 end) (pair(4, 7)) { case(pair(var'x', var'y')) - call(function(a, b, c) return a + b + c end, var'x', var'y', 5), case(pair(4, var'z')) - DO('double(z)',{double = function(x) return x*2 end} ) } returns 16 They can be used as switch statements e.g. match (value) { case(5) - ... , case('hello') - ... } But their strength is in using the binded variables. e.g. local append; append = match_all_nomt { case( mempty, var'ys' ) - 'ys', case({head = var'x', tail = var'xs'}, var'ys') - function(t) return cons(t.x, append(t.xs, t.ys)) end } defines a function `append` that takes two lists of the form { head = value, tail = restOfList } where mempty = empty list and concatenates them together. ]==] -- [ INIT ] local sm, gm, ipairs, pairs = setmetatable, getmetatable, ipairs, pairs local loadstring, type, assert, tostring = loadstring, type, assert, tostring local error, setfenv, unpack, select = error, setfenv, unpack, select local walk, isVar -- Generates a string that will assign values to (all) the variable(s) provided -- based on the substitution hash once loaded and ran as a function -- with the hash as first argument local function declareVars(obj) if isVar(obj) then -- the (...) argument refers to the subst hash return 'local '..obj.name..'='..'(...).'..obj.name..';' elseif type(obj) == 'table' then local accu = '' for _, v in pairs(obj) do accu = accu..declareVars(v) end return accu else return '' end end -- Wraps a string to be load(string)ed and an environment -- for the resulting function to look up with -- NOTE: If env does not have a meta-table, it will be set to from_G -- Also, in the expression, access the subst hash with (...) local doMT = {} local function DO(str, env) return sm({str, env}, doMT) end -- Stores a function and the arguments to it, -- which may be variables (to be looked up in the subst hash later) -- NOTE: Final parameter to 'f' is the substitution hash! local callMT = {} local function call(f, ...) return sm({func = f, args = {...}}, callMT) end -- meta-table for environments to declare that the global environment is used local from_G = {__index = _G} -- Meta-table for the completed case, something of the form case(...) - DO/call(...) -- getFunc returns a function that takes a substitution hash and evaulates the call/DO blocks local caseMT = {getFunc = function(self) local expr = self[2] --extract rhs -- if rhs is a DO block if gm(expr) == doMT then -- append the str expression with all variables being pre-bound -- to their corresponding values inside the given hash (first arg.) local header = declareVars(self[1]) -- Generate the function with the given env local f = loadstring( header .. 'return '..expr[1] ) local env = expr[2] if gm(env) then return setfenv(f, env) else return setfenv(f, sm(env, from_G)) end -- if rhs is a call block elseif gm(expr) == callMT then -- generate the (normal) function that takes the hash return function(subst) -- each variable is looked up in the hash before being passed -- to inner function local accu = {} for _, v in ipairs(expr.args) do if isVar(v) then accu[#accu+1] = walk(v, subst) else accu[#accu+1] = v end end -- final argument is subst hash accu[#accu+1] = subst -- eventually, call the inner, wrapped function with bound args and hash return expr.func(unpack(accu)) end else error("match> 'DO' or 'call' block expected.", 2) end end } ; caseMT.__index = caseMT -- Meta table for generating full cases local halfcaseMT = {__sub = function(self, expr) -- Syntatic sugars. case(...) - "{expr}" = case(...) - DO("{expr}", {}) -- and case(...) - function(hash) ??? end = case(...) - call(function(hash) ??? end) if type(expr) == 'string' then return sm({self[1], DO(expr, {})}, caseMT) end if type(expr) == 'function' then return sm({self[1], call(expr)}, caseMT) end return sm({self[1], expr}, caseMT) end} -- Metatable for variables local varMT = {__tostring = function(self) return '$('..self.name..')' end} -- [ FUNCTIONS ] isVar = function(x) return gm(x) == varMT end --forward declared --Create a custom "variable" with the given name local function var(name) return sm({name = name}, varMT) end -- Look up the ultimate value of v in subst -- i.e. return subst[v.name] or subst[subst[v.name]] or ... -- until it reaches a value or a free variable z such that subst[z.name] is nil function walk(v, subst) --forward declared if not isVar(v) then return v else local res = walk(subst[v.name], subst) -- returns the end result of the look-up chain, whether it's a variable or value return (res~=nil and res) or v end end -- Helper function. Look at 'unify(case, obj, constraint)' below local function unify_helper(x, y, subst, constraint) assert(not isVar(y), 'match> There can only be variables in the Cases!') -- Look up the value or free variable ultimately associated with x in subst local u = walk(x, subst) -- Check constraint given if not constraint(y, u, subst) then return nil end -- With "_", always passes ("unification" succeeds, nothing new is bound) if isVar(u) and u.name == '_' then return subst end -- If u is a (free!) variable then bind y to it if isVar(u) then subst[u.name] = y return subst -- If it's a value, check if it's equal to y elseif u == y then return subst -- If they're both tables, check inside contents elseif type(u) == 'table' and type(y) == 'table' then -- Check array part if #u > 0 then -- If their arrays don't have the same size, it fails to unify if #u ~= #y then return nil end -- Check that elements at each index can be unified -- while remembering the same variables (and constraint) for i, e in ipairs(u) do subst = unify_helper(e, y[i], subst, constraint) if not subst then return nil end end end -- Check hash part, make sure all elements at each key *of only u* can be unified for k, e in pairs(u) do local r = y[k] -- Fails if case has a key not in obj if r == nil then return nil end subst = unify_helper(e, r, subst, constraint) if not subst then return nil end end -- If nothing fails, passes, binding necessary inner-variables to values return subst end -- If they aren't both tables and they're not equal, unification fails end -- Attempts to unify the case and the obj(ect) -- Unification succeeds if the constraint holds AND: case == obj or case is a (free) variable or -- both are tables and the values at each key *of the case* can be unified, -- and if case has an array part, values at each indexes can be unified -- (remembering all already-bound variables, given the same constraint) -- The constraint is called each time a unification attempt is made -- It is called with the two inputs and the substitution hash. -- It must always return true for unification to succeed local function unify(case, obj, constraint) --BECAREFUL!!! Unification is one-sided! return unify_helper(case, obj, {}, constraint) end -- Wraps obj with the halfcaseMT meta-table. Needs other half (right-side of '-') to be completed -- case(a1, a2, ...) is basically syntactic sugar for case({a1, a2, ...}) local function case(obj, ...) return select('#', ...)==0 and sm({obj}, halfcaseMT) or sm({ {obj, ...} }, halfcaseMT) end -- USAGE: match_cond (constraint) (obj) (cases) where cases is an array of cases -- Alternatively: match_cond (constraint) (cases) (obj) where obj is an *empty* table or a non-table -- match_cond (constraint) (o1, o2, o3, ...) (c1, c2, c3, ...) is -- syntatic sugar for match_cond (constraint) {o1, o2, o3, ...} {c1, c2, c3, ...} local function match_cond(constraint) --stores first set of values return function(a, ...) local x = (select('#', ...) == 0 and a) or {a, ...} ; --stores second set of values return function(b, ...) local y = (select('#', ...) == 0 and b) or {b, ...} ; --check that cases is (probably) given and assign appropriate sets of values to obj/cases local obj, cases assert(type(x) == 'table' or type(y) == 'table', 'match> an array of Cases must be given!') if type(y) == 'table' and #y > 0 and gm(y[1]) == caseMT then obj = x; cases = y else obj = y; cases = x end -- Attempt to unify (under constraint) each case based on index until it succeeds -- Then, calls first succeeded case's function/expression with the substition hash for _, c in ipairs(cases) do local subst = unify(c[1], obj, constraint) if subst then return (c:getFunc())(subst) end end end end end -- match_cond with no additional constraint on unification local match_nomt = match_cond(function() return true end) -- Check that all (sub-)tables have the same meta-table -- non-tables pass the constraint automatically local function checkMt(vals, vars) if type(vals) == 'table' and type(vars) == 'table' and not isVar(vars) then return gm(vals) == gm(vars) else return true end end local match = match_cond(checkMt) -- attempts to unify with checkMt constraint -- Counts the number of keys in a table local function size(t) local accu = 0 for _, _ in pairs(t) do accu = accu + 1 end return accu end -- Constraint that ensures all (sub-)tables have all the same keys local function checkSize(vals, vars) if type(vals) == 'table' and type(vars) == 'table' and not isVar(vars) then return size(vals) == size(vars) else return true end end -- Attempts unification but ensure all keys match local match_all_nomt = match_cond(checkSize) -- Attempts unification with all keys and meta-tables matching local match_all = match_cond(function(x, y) return checkSize(x, y) and checkMt(x, y) end) -- [ MODULE TEST/EXPORT ] return {case = case, match = match, match_all = match_all, match_nomt = match_nomt, match_all_nomt = match_all_nomt, match_cond = match_cond, DO = DO, call = call, var = var, is_var = isVar}
local command = vim.api.nvim_create_user_command command('FloatWinsClose', function() local wins = vim.api.nvim_list_wins() for _, win in ipairs(wins) do if vim.api.nvim_win_get_config(win).relative ~= '' then vim.api.nvim_win_close(win, true) end end end, { nargs = 0 })
local ok, mod ok, mod = pcall(require,'luasodium.crypto_hash.ffi') if ok then return mod end ok, mod = pcall(require,'luasodium.crypto_hash.core') if ok then return mod end return require'luasodium.crypto_hash.pureffi'
--[[ LibPlayerSpells-1.0 - Additional information about player spells. (c) 2013-2018 Adirelle (adirelle@gmail.com) This file is part of LibPlayerSpells-1.0. LibPlayerSpells-1.0 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. LibPlayerSpells-1.0 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 General Public License for more details. You should have received a copy of the GNU General Public License along with LibPlayerSpells-1.0. If not, see <http://www.gnu.org/licenses/>. --]] local MAJOR, MINOR, lib = "LibPlayerSpells-1.0", 11 if LibStub then local oldMinor lib, oldMinor = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end if oldMinor and oldMinor < 8 then -- The internal data changed at minor 8, wipe anything coming from the previous version wipe(lib) end else lib = {} end local Debug = function() end if AdiDebug then Debug = AdiDebug:Embed({}, MAJOR) end local _G = _G local ceil = _G.ceil local error = _G.error local format = _G.format local GetSpellInfo = _G.GetSpellInfo local gsub = _G.string.gsub local ipairs = _G.ipairs local max = _G.max local next = _G.next local pairs = _G.pairs local setmetatable = _G.setmetatable local tonumber = _G.tonumber local tostring = _G.tostring local type = _G.type local wipe = _G.wipe local bor = _G.bit.bor local band = _G.bit.band local bxor = _G.bit.bxor local bnot = _G.bit.bnot -- Basic constants use for the bitfields lib.constants = { -- Special types -- these alters how the 13 lower bits are to be interpreted DISPEL = 0x80000000, CROWD_CTRL = 0x40000000, -- Sources DEATHKNIGHT = 0x00000001, DEMONHUNTER = 0x00000002, DRUID = 0x00000004, HUNTER = 0x00000008, MAGE = 0x00000010, MONK = 0x00000020, PALADIN = 0x00000040, PRIEST = 0x00000080, ROGUE = 0x00000100, SHAMAN = 0x00000200, WARLOCK = 0x00000400, WARRIOR = 0x00000800, RACIAL = 0x00001000, -- Racial trait -- Crowd control types, *requires* CROWD_CTRL, else this messes up sources DISORIENT = 0x00000001, INCAPACITATE = 0x00000002, ROOT = 0x00000004, STUN = 0x00000008, TAUNT = 0x00000010, -- Dispel types, *requires* DISPEL, else this messes up sources CURSE = 0x00000001, DISEASE = 0x00000002, MAGIC = 0x00000004, POISON = 0x00000008, ENRAGE = 0x00000010, -- Targeting HELPFUL = 0x00004000, -- Usable on allies HARMFUL = 0x00008000, -- Usable on enemies PERSONAL = 0x00010000, -- Only usable on self PET = 0x00020000, -- Only usable on pet -- Various flags AURA = 0x00040000, -- Applies an aura INVERT_AURA = 0x00080000, -- Watch this as a debuff on allies or a buff on enemies UNIQUE_AURA = 0x00100000, -- Only one aura on a given unit COOLDOWN = 0x00200000, -- Has a cooldown SURVIVAL = 0x00400000, -- Survival spell BURST = 0x00800000, -- Damage/healing burst spell POWER_REGEN = 0x01000000, -- Recharge any power IMPORTANT = 0x02000000, -- Important spell the player should react to INTERRUPT = 0x04000000, KNOCKBACK = 0x08000000, SNARE = 0x10000000, RAIDBUFF = 0x20000000, } local constants = lib.constants local CROWD_CTRL_TYPES = { constants.DISORIENT, constants.INCAPACITATE, constants.ROOT, constants.STUN, constants.TAUNT, } local DISPEL_TYPES = { constants.CURSE, constants.DISEASE, constants.ENRAGE , constants.MAGIC, constants.POISON, } local CROWD_CTRL_CATEGORY_NAMES = { [constants.DISORIENT] = _G.LOSS_OF_CONTROL_DISPLAY_DISORIENT, [constants.INCAPACITATE] = _G.LOSS_OF_CONTROL_DISPLAY_INCAPACITATE, [constants.ROOT] = _G.LOSS_OF_CONTROL_DISPLAY_ROOT, [constants.STUN] = _G.LOSS_OF_CONTROL_DISPLAY_STUN, [constants.TAUNT] = _G.LOSS_OF_CONTROL_DISPLAY_TAUNT, } local DISPEL_TYPE_NAMES = { [constants.CURSE] = _G.ENCOUNTER_JOURNAL_SECTION_FLAG8, [constants.DISEASE] = _G.ENCOUNTER_JOURNAL_SECTION_FLAG10, [constants.ENRAGE] = _G.ENCOUNTER_JOURNAL_SECTION_FLAG11, [constants.MAGIC] = _G.ENCOUNTER_JOURNAL_SECTION_FLAG7, [constants.POISON] = _G.ENCOUNTER_JOURNAL_SECTION_FLAG9, } -- Convenient bitmasks lib.masks = { CLASS = bor( constants.DEATHKNIGHT, constants.DEMONHUNTER, constants.DRUID, constants.HUNTER, constants.MAGE, constants.MONK, constants.PALADIN, constants.PRIEST, constants.ROGUE, constants.SHAMAN, constants.WARLOCK, constants.WARRIOR ), SOURCE = bor( constants.DEATHKNIGHT, constants.DEMONHUNTER, constants.DRUID, constants.HUNTER, constants.MAGE, constants.MONK, constants.PALADIN, constants.PRIEST, constants.ROGUE, constants.SHAMAN, constants.WARLOCK, constants.WARRIOR, constants.RACIAL ), TARGETING = bor( constants.HELPFUL, constants.HARMFUL, constants.PERSONAL, constants.PET ), TYPE = bor( constants.CROWD_CTRL, constants.DISPEL ), CROWD_CTRL_TYPE = bor( constants.DISORIENT, constants.INCAPACITATE, constants.ROOT, constants.STUN, constants.TAUNT ), DISPEL_TYPE = bor( constants.CURSE, constants.DISEASE, constants.ENRAGE, constants.MAGIC, constants.POISON ), } local masks = lib.masks -- Spells and their flags lib.__spells = lib.__spells or {} local spells = lib.__spells -- Spells by categories lib.__categories = lib.__categories or { DEATHKNIGHT = {}, DEMONHUNTER = {}, DRUID = {}, HUNTER = {}, MAGE = {}, MONK = {}, PALADIN = {}, PRIEST = {}, ROGUE = {}, SHAMAN = {}, WARLOCK = {}, WARRIOR = {}, RACIAL = {}, } local categories = lib.__categories -- Special spells lib.__specials = lib.__specials or { CROWD_CTRL = {}, DISPEL = {}, } local specials = lib.__specials -- Versions of the different categories lib.__versions = lib.__versions or {} local versions = lib.__versions -- Buff to provider map. -- The provider is the spell from the spellbook than can provides the given buff. -- Said otherwise, a buff cannot appear on a player if the provider spell is not in his spellbook. lib.__providers = lib.__providers or {} local providers = lib.__providers -- Buff to modified map. -- Indicate which spell is modified by a buff. lib.__modifiers = lib.__modifiers or {} local modifiers = lib.__modifiers -- Spell to category map. -- Indicate which category defined a spell. lib.__sources = lib.__sources or {} local sources = lib.__sources local function ParseFilter(filter) local flags = 0 for word in filter:gmatch("[%a_]+") do local value = constants[word] or masks[word] if not value then error(format("%s: invalid filter: %q (because of %q)", MAJOR, tostring(filter), tostring(word)), 5) end flags = bor(flags, value) end return flags end -- A weak table to memoize parsed filters lib.__filters = setmetatable( wipe(lib.__filters or {}), { __mode = 'kv', __index = function(self, key) if not key then return 0 end local value = type(key) == "string" and ParseFilter(key) or tonumber(key) self[key] = value return value end, } ) local filters = lib.__filters filters[""] = 0 --- Return version information about a category -- @param category (string) The category. -- @return (number) A version number suitable for comparison. -- @return (number) The interface (i.e. patch) version. -- @return (number) Minor version for the given interface version. function lib:GetVersionInfo(category) local cats = { strsplit(" ", category) } local v for i = 1, #cats do if not categories[cats[i]] then error(format("%s: invalid category: %q", MAJOR, tostring(category)), 2) end v = versions[cats[i]] or 0 end return v, floor(v/100), v % 100 end local TRUE = function() return true end --- Create a flag tester callback. -- This callback takes a flag as an argument and returns true when the conditions are met. -- @param anyOf (string|number) The tested value should contain at least one these flags. -- @param include (string|number) The tested value must contain all these flags. -- @param exclude (string|number) The testes value must not contain any of these flags. -- @return (function) The tester callback. function lib:GetFlagTester(anyOf, include, exclude) local anyOfMask = filters[anyOf] if include or exclude then local includeMask, excludeMask = filters[include], filters[exclude] local mask = bor(includeMask, excludeMask) local expected = bxor(mask, excludeMask) if anyOf then return function(flags) return flags and band(flags, anyOfMask) ~= 0 and band(flags, mask) == expected end else return function(flags) return flags and band(flags, mask) == expected end end elseif anyOf then return function(flags) return flags and band(flags, anyOfMask) ~= 0 end else return TRUE end end --- Create a spell tester callback. -- This callback takes a spell identifier as an argument and returns true when the conditions are met. -- @param anyOf (string|number) The tested value should contain at least one these flags. -- @param include (string|number) The tested value must contain all these flags. -- @param exclude (string|number) The testes value must not contain any of these flags. -- @return (function) The tester callback. function lib:GetSpellTester(anyOf, include, exclude) local tester = lib:GetFlagTester(anyOf, include, exclude) return function(spellId) return tester(spells[spellId or false] or 0) end end -- Filtering iterator local function FilterIterator(tester, spellId) local flags repeat spellId, flags = next(spells, spellId) if spellId and tester(flags) then return spellId, flags, providers[spellId], modifiers[spellId], specials.CROWD_CTRL[spellId], sources[spellId], specials.DISPEL[spellId] end until not spellId end -- Iterate through spells. -- @return An iterator suitable for for .. in .. do loops. function lib:IterateSpells(anyOf, include, exclude) return FilterIterator, lib:GetFlagTester(anyOf, include, exclude) end --- Iterate through spell categories. -- The iterator returns the category name and the spells in that category. -- @return An iterator suitable for .. in .. do loops. function lib:IterateCategories() return pairs(categories) end --- Return the list of crowd control types. -- @return (table) function lib:GetCrowdControlTypes() return CROWD_CTRL_TYPES end --- Return the list of dispel types. -- @return (table) function lib:GetDispelTypes() return DISPEL_TYPES end --- Return the localized name of the category a crowd control aura belongs to. -- Can be called with either a bitmask or a spellId. -- @param bitmask (number) a bitmask for the aura. -- @param spellId (number) spell identifier of the aura. -- @return (string|nil) The localized category name or nil. function lib:GetCrowdControlCategoryName(bitmask, spellId) bitmask = bitmask or spellId and specials.CROWD_CTRL[spellId] if not bitmask then return end for mask, name in pairs(CROWD_CTRL_CATEGORY_NAMES) do if band(bitmask, mask) > 0 then return name end end end --- Return a table containing the localized names of the dispel types. -- Can be called with either a bitmask or a spellId. -- @param bitmask (number) a bitmask for the spell. -- @param spellId (number) spell identifier of the spell. -- @return (table|nil) A table of localized dispel type names or nil. function lib:GetDispelTypeNames(bitmask, spellId) bitmask = bitmask or spellId and specials.DISPEL[spellId] if not bitmask then return end local names = {} for mask, name in pairs(DISPEL_TYPE_NAMES) do if band(bitmask, mask) > 0 then names[#names + 1] = name end end return names end --- Return information about a spell. -- @param spellId (number) The spell identifier. -- @return (number) The spell flags or nil if it is unknown. -- @return (number|table) Spell(s) providing the given spell. -- @return (number|table) Spell(s) modified by the given spell. -- @return (number) Crowd control category, if the spell is a crowd control. -- @return (string) Spell source(s). -- @return (number) Dispel category, if the spell is a dispel. function lib:GetSpellInfo(spellId) local flags = spellId and spells[spellId] if flags then return flags, providers[spellId], modifiers[spellId], specials.CROWD_CTRL[spellId], sources[spellId], specials.DISPEL[spellId] end end -- Filter valid spell ids. -- This can fails when the client cache is empty (e.g. after a major patch). -- Accept a table, in which case it is recursively validated. local function FilterSpellId(spellId, spellType, errors) if type(spellId) == "table" then local ids = {} for i, subId in pairs(spellId) do local validated = FilterSpellId(subId, spellType, errors) if validated then tinsert(ids, validated) end end return next(ids) and ids or nil elseif type(spellId) ~= "number" then errors[spellId] = format("invalid %s, expected number, got %s", spellType, type(spellId)) elseif not GetSpellInfo(spellId) then errors[spellId] = format("unknown %s", spellType) else return spellId end end -- Flatten and validate the spell data. local function FlattenSpellData(source, target, prefix, errorLevel) prefix = strtrim(prefix) for key, value in pairs(source) do local keyType, valueType = type(key), type(value) if valueType == "number" then -- value is a spell id target[value] = prefix elseif keyType == "number" and value == true then -- key is a spell id, value is true target[key] = prefix elseif keyType == "number" and valueType == "string" then -- key is a spell id, value is a flag target[key] = prefix.." "..value elseif keyType == "string" and valueType == "table" then -- Value is a nested table, key indicates common flags FlattenSpellData(value, target, prefix.." "..key, errorLevel+1) else error(format("%s: invalid spell definition: [%q] = %q", MAJOR, tostring(key), tostring(value)), errorLevel+1) end end end -- either a or b is not nil -- a and b are either a number or a table local function Merge(a, b) if not a then return b end if not b then return a end local hash = {} if type(a) == "number" then hash[a] = true else for i = 1, #a do hash[a[i]] = true end end if type(b) == "number" then hash[b] = true else for i = 1, #b do hash[b[i]] = true end end local merged = {} for k in pairs(hash) do merged[#merged + 1] = k end if #merged == 1 then return merged[1] end table.sort(merged) return merged end function lib:__RegisterSpells(category, interface, minor, newSpells, newProviders, newModifiers) if not categories[category] then error(format("%s: invalid category: %q", MAJOR, tostring(category)), 2) end local version = tonumber(interface) * 100 + minor if (versions[category] or 0) >= version then return end versions[category] = version local categoryFlag = constants[category] or 0 -- Wipe previous spells local db, crowd_ctrl, dispels = categories[category], specials.CROWD_CTRL, specials.DISPEL for spellId in pairs(db) do db[spellId] = nil -- wipe the rest only if the current category is the only source local sourceFlags = band(spells[spellId], masks.SOURCE) if bxor(sourceFlags, categoryFlag) == 0 then spells[spellId] = nil providers[spellId] = nil modifiers[spellId] = nil crowd_ctrl[spellId] = nil dispels[spellId] = nil sources[spellId] = nil end if spells[spellId] then -- there are other sources -- remove current category from source flags spells[spellId] = bxor(spells[spellId], categoryFlag) -- can't remove old providers -> slight performance hit but no problem -- can't remove old modifiers -> slight performance hit but no problem -- crowd_ctrl and dispels contain no source information sources[spellId] = strtrim(gsub(sources[spellId], category, "")) end end -- Flatten the spell definitions local defs = {} FlattenSpellData(newSpells, defs, "", 2) -- Useful constants local CROWD_CTRL = constants.CROWD_CTRL local DISPEL = constants.DISPEL local TYPE = masks.TYPE local CROWD_CTRL_TYPE = masks.CROWD_CTRL_TYPE local NOT_CC_TYPE = bnot(CROWD_CTRL_TYPE) local DISPEL_TYPE = masks.DISPEL_TYPE local NOT_DISPEL_TYPE = bnot(DISPEL_TYPE) local errors = {} -- Build the flags for spellId, flagDef in pairs(defs) do spellId = FilterSpellId(spellId, "spell", errors) if spellId then local flags = filters[flagDef] if band(flags, TYPE) == CROWD_CTRL then crowd_ctrl[spellId] = band(flags, CROWD_CTRL_TYPE) -- clear the crowd control flags flags = band(flags, NOT_CC_TYPE) elseif band(flags, TYPE) == DISPEL then dispels[spellId] = band(flags, DISPEL_TYPE) -- clear the dispel flags flags = band(flags, NOT_DISPEL_TYPE) end db[spellId] = bor(db[spellId] or 0, flags, categoryFlag) -- TODO: db[spellId] can't be present? end end -- Consistency checks if newProviders then for spellId, providerId in pairs(newProviders) do if not db[spellId] then if not errors[spellId] then errors[spellId] = "only in providers" end newProviders[spellId] = nil else local validSpellId = FilterSpellId(spellId, "provided spell", errors) local validProviderId = FilterSpellId(providerId, "provider spell", errors) newProviders[spellId] = validSpellId and validProviderId end end end if newModifiers then for spellId, modified in pairs(newModifiers) do if not db[spellId] then if not errors[spellId] then errors[spellId] = "only in modifiers" end newModifiers[spellId] = nil else local validSpellId = FilterSpellId(spellId, "modifier spell", errors) local validModified = FilterSpellId(modified, "modified spell", errors) newModifiers[spellId] = validSpellId and validModified end end end -- Copy the new values to the merged categories for spellId in pairs(db) do spells[spellId] = bor(spells[spellId] or 0, db[spellId]) providers[spellId] = Merge(newProviders and newProviders[spellId] or spellId, providers[spellId]) modifiers[spellId] = Merge(newModifiers and newModifiers[spellId] or providers[spellId], modifiers[spellId]) sources[spellId] = format("%s%s", sources[spellId] and sources[spellId].." " or "", category) end local errorCount = 0 for spellId, msg in pairs(errors) do Debug(category, format("spell #%d: %s", spellId, msg)) errorCount = errorCount + 1 end return errorCount end return lib
-- -- Author: guobin -- Date: 2017-12-16 18:32:45 -- CONSOLE_LOG = true --控制台是否输出日志 LOG_LEVEL = 0 --文件日志的登记 0 debug; 1 info; 2 warning; 3 error LOG_PATH = "logs"
local buttonPadding = ScreenScale(14) * 0.5 -- base menu button DEFINE_BASECLASS("DButton") local PANEL = {} AccessorFunc(PANEL, "backgroundColor", "BackgroundColor") AccessorFunc(PANEL, "backgroundAlpha", "BackgroundAlpha") function PANEL:Init() self:SetFont("ixMenuButtonFont") self:SetTextColor(color_white) self:SetPaintBackground(false) self:SetContentAlignment(4) self:SetTextInset(buttonPadding, 0) self.backgroundColor = Color(0, 0, 0) self.backgroundAlpha = 128 self.currentBackgroundAlpha = 0 end function PANEL:SetText(text, noTranslation) surface.SetFont("ixMenuButtonFont") BaseClass.SetText(self, noTranslation and text:upper() or L(text):upper()) local w, h = surface.GetTextSize(self:GetText()) self:SetSize(w + 64, h + 32) end function PANEL:PaintBackground(width, height) surface.SetDrawColor(ColorAlpha(self.backgroundColor, self.currentBackgroundAlpha)) surface.DrawRect(0, 0, width, height) end function PANEL:Paint(width, height) self:PaintBackground(width, height) BaseClass.Paint(self, width, height) end function PANEL:SetTextColorInternal(color) BaseClass.SetTextColor(self, color) self:SetFGColor(color) end function PANEL:SetTextColor(color) self:SetTextColorInternal(color) self.color = color end function PANEL:SetDisabled(bValue) local color = self.color if (bValue) then self:SetTextColorInternal(Color(math.max(color.r - 60, 0), math.max(color.g - 60, 0), math.max(color.b - 60, 0))) else self:SetTextColorInternal(color) end BaseClass.SetDisabled(self, bValue) end function PANEL:OnCursorEntered() if (self:GetDisabled()) then return end local color = self:GetTextColor() self:SetTextColorInternal(Color(math.max(color.r - 25, 0), math.max(color.g - 25, 0), math.max(color.b - 25, 0))) self:CreateAnimation(0.15, { target = {currentBackgroundAlpha = self.backgroundAlpha} }) LocalPlayer():EmitSound("Helix.Rollover") end function PANEL:OnCursorExited() if (self:GetDisabled()) then return end if (self.color) then self:SetTextColor(self.color) else self:SetTextColor(color_white) end self:CreateAnimation(0.15, { target = {currentBackgroundAlpha = 0} }) end function PANEL:OnMousePressed(code) if (self:GetDisabled()) then return end if (self.color) then self:SetTextColor(self.color) else self:SetTextColor(ix.config.Get("color")) end LocalPlayer():EmitSound("Helix.Press") if (code == MOUSE_LEFT and self.DoClick) then self:DoClick(self) elseif (code == MOUSE_RIGHT and self.DoRightClick) then self:DoRightClick(self) end end function PANEL:OnMouseReleased(key) if (self:GetDisabled()) then return end if (self.color) then self:SetTextColor(self.color) else self:SetTextColor(color_white) end end vgui.Register("ixMenuButton", PANEL, "DButton") -- selection menu button DEFINE_BASECLASS("ixMenuButton") PANEL = {} AccessorFunc(PANEL, "backgroundColor", "BackgroundColor") AccessorFunc(PANEL, "selected", "Selected", FORCE_BOOL) AccessorFunc(PANEL, "buttonList", "ButtonList") function PANEL:Init() self.backgroundColor = color_white self.selected = false self.buttonList = {} end function PANEL:PaintBackground(width, height) local alpha = self.selected and 255 or self.currentBackgroundAlpha derma.SkinFunc("DrawImportantBackground", 0, 0, width, height, ColorAlpha(self.backgroundColor, alpha)) end function PANEL:SetSelected(bValue) self.selected = bValue if (bValue) then self:OnSelected() end end function PANEL:SetButtonList(list, bNoAdd) if (!bNoAdd) then list[#list + 1] = self end self.buttonList = list end function PANEL:OnMousePressed(key) for _, v in pairs(self.buttonList) do if (IsValid(v)) then v:SetSelected(false) end end self:SetSelected(true) BaseClass.OnMousePressed(self, key) end function PANEL:OnSelected() end vgui.Register("ixMenuSelectionButton", PANEL, "ixMenuButton")
local restserver = require("restserver") local server = restserver:new():port(8080) local message = {message = "Hello World"} server:add_resource("hello", { { method = "GET", path = "/", produces = "application/json", handler = function() return restserver.response():status(200):entity(message) end, } }) server.server_name = "Hello world Server" server:enable("restserver.xavante"):start()
--tip local function deprecatedTip(old_name,new_name) print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********") end --functions of CCControl will be deprecated end local CCControlDeprecated = { } function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent) deprecatedTip("addHandleOfControlEvent","registerControlEventHandler") print("come in addHandleOfControlEvent") self:registerControlEventHandler(func,controlEvent) end rawset(CCControl,"addHandleOfControlEvent",CCControlDeprecated.addHandleOfControlEvent) --functions of CCControl will be deprecated end --Enums of CCTableView will be deprecated begin rawset(CCTableView, "kTableViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) rawset(CCTableView,"kTableViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) rawset(CCTableView,"kTableCellTouched",cc.TABLECELL_TOUCHED) rawset(CCTableView,"kTableCellSizeForIndex",cc.TABLECELL_SIZE_FOR_INDEX) rawset(CCTableView,"kTableCellSizeAtIndex",cc.TABLECELL_SIZE_AT_INDEX) rawset(CCTableView,"kNumberOfCellsInTableView",cc.NUMBER_OF_CELLS_IN_TABLEVIEW) --Enums of CCTableView will be deprecated end --Enums of CCScrollView will be deprecated begin rawset(CCScrollView, "kScrollViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) rawset(CCScrollView,"kScrollViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) --Enums of CCScrollView will be deprecated end
local PLAYER = FindMetaTable("Player") function PLAYER:ROTGB_IsFirstPersonPlayerSpectating() return self.rotgb_PlayerFirstPersonView or false end function PLAYER:ROTGB_ToggleFirstPersonPlayerSpectating() self.rotgb_PlayerFirstPersonView = not self.rotgb_PlayerFirstPersonView end function PLAYER:ROTGB_StartSpectateRandomEntity() self:Spectate(OBS_MODE_ROAMING) self:SpectateEntity(game.GetWorld()) local possibleEntities = hook.Run("GetSpectatableEntities", self) local targetEntity = game.GetWorld() if next(possibleEntities) then targetEntity = possibleEntities[math.random(#possibleEntities)] end if IsValid(targetEntity) then self:SpectateEntity(targetEntity) hook.Run("ApplyEntitySpectateProperties", self, targetEntity, false) end end function GM:PlayerSpawnAsSpectator(ply) ply:StripWeapons() if ply:Team() == TEAM_UNASSIGNED then ply:ROTGB_StartSpectateRandomEntity() else ply:Spectate(OBS_MODE_ROAMING) end end function GM:SpectatorKeyPress(ply, action) local spectatables = hook.Run("GetSpectatableEntities", ply) local specIndex = table.KeyFromValue(spectatables, ply:GetObserverTarget()) or 1 if action == IN_ATTACK then specIndex = specIndex % #spectatables + 1 local entityToSpectate = spectatables[specIndex] ply:SpectateEntity(entityToSpectate) hook.Run("ApplyEntitySpectateProperties", ply, entityToSpectate, false) elseif action == IN_ATTACK2 then specIndex = (specIndex - 2) % #spectatables + 1 local entityToSpectate = spectatables[specIndex] ply:SpectateEntity(entityToSpectate) hook.Run("ApplyEntitySpectateProperties", ply, entityToSpectate, false) elseif action == IN_DUCK then hook.Run("ApplyEntitySpectateProperties", ply, ply:GetObserverTarget(), true) end end function GM:GetSpectatableEntities(ply) self.rotgb_SpectatorEntities = self.rotgb_SpectatorEntities or {} table.Empty(self.rotgb_SpectatorEntities) for i,v in ipairs(ents.GetAll()) do local class = v:GetClass() if (class == "point_rotgb_spectator" and v:PlayerCanSpectate(ply, hook.Run("GetDefeated"))) then table.insert(self.rotgb_SpectatorEntities, v) elseif ply:Team()~=TEAM_UNASSIGNED then if class == "gballoon_spawner" or class == "gballoon_target" then if not v:GetUnSpectatable() then table.insert(self.rotgb_SpectatorEntities, v) end elseif class == "player" then local team = v:Team() if team~=TEAM_CONNECTING and team~=TEAM_UNASSIGNED and team~=TEAM_SPECTATOR then table.insert(self.rotgb_SpectatorEntities, v) end elseif class == "worldspawn" then table.insert(self.rotgb_SpectatorEntities, v) end end end return self.rotgb_SpectatorEntities end function GM:ApplyEntitySpectateProperties(ply, ent, modChange) if IsValid(ent) or ent==game.GetWorld() then local class = ent:GetClass() if class == "point_rotgb_spectator" then ply:SetFOV(ent:GetFOV(), 0, ent) ply:SetEyeAngles(ent:GetAngles()) ply:SetPos(ent:GetPos()) ply:SetObserverMode(ent:GetRotationLocked() and OBS_MODE_FIXED or OBS_MODE_IN_EYE) --FIXME: OBS_MODE_FIXED is busted else ply:SetFOV(0) if class == "player" then if modChange then ply:ROTGB_ToggleFirstPersonPlayerSpectating() end local newObsMode = ply:ROTGB_IsFirstPersonPlayerSpectating() and OBS_MODE_IN_EYE or OBS_MODE_CHASE ply:SetObserverMode(newObsMode) elseif class == "worldspawn" then ply:Spectate(OBS_MODE_ROAMING) else ply:SetObserverMode(OBS_MODE_CHASE) end end end end
#!/usr/bin/env luajit -- run a suite -- run this from the test working dir, i.e. hydro/tests/<wherever>/ -- run this as ../suite.lua -- TODO instead, maybe run this in the local dir, with the test dir name as the param? nah, because each test shows/does dif things -- how about TODO instead, put this in a subdir called "common" or "util" or something? local ffi = require 'ffi' require 'ffi.c.stdlib' -- free local unistd = require 'ffi.c.unistd' local class = require 'ext.class' local table = require 'ext.table' local os = require 'ext.os' local file = require 'ext.file' -- save the cwd and chdir to ../.. local rundirp = unistd.getcwd(nil, 0) local rundir = ffi.string(rundirp) ffi.C.free(rundirp) --local resultsDir = 'results' --os.execute('mkdir "'..rundir..'/'..resultsDir..'" 2> '..(ffi.os == 'Windows' and 'NIL' or '/dev/null')) unistd.chdir'../..' -- set this global to have hydro run in console mode -- working on doing this cleaner... cmdline = { showfps = true, sys = 'console', exitTime = 10, } local HydroApp = class(require 'hydro.app') -- share across all app instances HydroApp.allnames = {} local configs = dofile(rundir..'/config.lua') -- could use 'require' but there is another in the newly added package.path for _,config in ipairs(configs) do local resultFile = rundir..'/results-'..config.name..'.txt' if not os.fileexists(resultFile) then -- another TODO for hydro.app ... reuse names for matching ctypes local data = table() function HydroApp:setup(args) print('running config: '..config.name) local solverClassName = config.solverClassName local solverClass = require(solverClassName) local args = table(config.solverArgs) args.app = self local solver = solverClass(args) local oldUpdate = solver.update function solver:update(...) oldUpdate(self, ...) local row = table() row:insert(self.t) if config.trackVars then for _,varName in ipairs(config.trackVars) do local var = assert(self.displayVarForName[varName]) local component = self.displayComponentFlatList[var.component] local vectorField = self:isVarTypeAVectorField(component.type) local valueMin, valueMax, valueAvg = self:calcDisplayVarRangeAndAvg(var, vectorField and component.magn or nil) row:append{valueMin, valueAvg, valueMax} end end data:insert(row) end self.solvers:insert(solver) end function HydroApp:requestExit() file[resultFile] = '#t\t'..table.mapi(config.trackVars, function(varName) return varName..' min\t' ..varName..' avg\t' ..varName..' max' end):concat'\t'..'\n' ..data:mapi(function(l) return table.concat(l, '\t') end):concat'\n' ..'\n' HydroApp.super.requestExit(self) end HydroApp():run() end end unistd.chdir(rundir) print('configs done -- plotting...') --os.execute('gnuplot plot.gnuplot') dofile'../plot.lua'
-- id int 界面id -- file_name int 界面文件名 -- title string 界面标题 -- icon string 标题衬图 -- ishelp int 是否显示帮助 -- help_id int 帮助id -- isres string 是否显示资源条 -- res tableString[k:#seq|v:#1(int)] 资源条内容 -- ismain int 是否显示返回主界面 -- isback int 是否显示返回 return { [1] = { id = 1, file_name = nil, title = "背包", icon = "", ishelp = 1, help_id = 1, isres = "1", res = { [1] = 1, [2] = 2, }, ismain = 1, isback = 1, }, [2] = { id = 2, file_name = nil, title = "精灵", icon = "", ishelp = 1, help_id = 2, isres = "1", res = { [1] = 1, [2] = 2, }, ismain = 1, isback = 1, }, [3] = { id = 3, file_name = nil, title = "看板娘", icon = "", ishelp = 1, help_id = 3, isres = "1", res = { [1] = 1, [2] = 2, }, ismain = 1, isback = 1, }, }
-- THIS FILE IS GENERATED. DO NOT EDIT MANUALLY. -- stylua: ignore start return {properties = {["volar-document-features.trace.server"] = {default = "off",description = "Traces the communication between VS Code and the language server.",enum = { "off", "messages", "verbose" },scope = "window",type = "string"},["volar-language-features-2.trace.server"] = {default = "off",description = "Traces the communication between VS Code and the language server.",enum = { "off", "messages", "verbose" },scope = "window",type = "string"},["volar-language-features.trace.server"] = {default = "off",description = "Traces the communication between VS Code and the language server.",enum = { "off", "messages", "verbose" },scope = "window",type = "string"},["volar.autoCompleteRefs"] = {default = false,description = "Auto-complete Ref value with `.value`.",type = "boolean"},["volar.autoWrapParentheses"] = {default = true,description = "Auto-wrap `()` to As Expression in interpolations for fix issue #520.",type = "boolean"},["volar.codeLens.pugTools"] = {default = false,description = "[pug ☐] code lens.",type = "boolean"},["volar.codeLens.references"] = {default = true,description = "[references] code lens.",type = "boolean"},["volar.codeLens.scriptSetupTools"] = {default = false,description = "[ref sugar ☐] code lens.",type = "boolean"},["volar.completion.autoImportComponent"] = {default = true,description = "Enabled auto-import for component with tag completion.",type = "boolean"},["volar.completion.preferredAttrNameCase"] = {default = "auto-kebab",description = "Preferred attr name case.",enum = { "auto-kebab", "auto-camel", "kebab", "camel" },enumDescriptions = { 'Auto Detect from Content (Preferred :kebab-case="...")', 'Auto Detect from Content (Preferred :camelCase="...")', ':kebab-case="..."', ':camelCase="..."' },type = "string"},["volar.completion.preferredTagNameCase"] = {default = "auto",description = "Preferred tag name case.",enum = { "auto", "both", "kebab", "pascal" },enumDescriptions = { "Auto Detect from Content", "<kebab-case> and <PascalCase>", "<kebab-case>", "<PascalCase>" },type = "string"},["volar.icon.preview"] = {default = true,description = "Show Vite / Nuxt App preview icon.",type = "boolean"},["volar.icon.splitEditors"] = {default = true,description = "Show split editor icon in title area of editor.",type = "boolean"},["volar.preview.backgroundColor"] = {default = "#fff",description = "Component preview background color.",type = "string"},["volar.preview.port"] = {default = 3333,description = "Default port for component preview server.",type = "number"},["volar.preview.script.nuxi"] = {default = "node {NUXI_BIN} dev --port {PORT}",type = "string"},["volar.preview.script.vite"] = {default = "node {VITE_BIN} --port={PORT}",type = "string"},["volar.preview.transparentGrid"] = {default = true,description = "Component preview background style.",type = "boolean"},["volar.splitEditors.layout.left"] = {default = { "script", "scriptSetup", "styles" },type = "array"},["volar.splitEditors.layout.right"] = {default = { "template", "customBlocks" },type = "array"},["volar.takeOverMode.enabled"] = {default = "auto",description = "Take over language support for *.ts.",enum = { "auto", true, false },enumDescriptions = { "Auto enable take over mode when built-in TS extension disabled.", "Alway enable take over mode.", "Never enable take over mode." },type = "boolean"},["volar.vueserver.maxOldSpaceSize"] = {default = vim.NIL,description = 'Set --max-old-space-size option on server process. If you have problem on frequently "Request textDocument/** failed." error, try setting higher memory(MB) on it.',type = { "number", "null" }},["volar.vueserver.useSecondServer"] = {default = false,description = "Use second server to progress heavy diagnostic works, the main server workhorse computing intellisense, operations such as auto-complete can respond faster. Note that this will lead to more memory usage.",type = "boolean"}},title = "Volar",type = "object"}
-- workaround for a current haxe-lua problem in haxes development branch return nil
kHydrasPerHive = 3 kWhipSupply = 25 -- was 5 kSentriesPerBattery = 2 -- was 3 kAdrenalineAbilityMaxEnergy = 200 -- was 160 kHandGrenadeWeight = 0 -- was 0.1 kLayMineWeight = 0 -- was 0.10 kFocusDamageBonusAtMax = 0.5 -- was 0.33
--- Functionality related to saving/loading data -- module("vn.save", package.seeall) ---Access to global storage -------------------------------------------------------------------------------------------------------------- @section globals ---Sets a shared global variable. All save slots have access to the same set of <em>shared</em> globals. Shared -- globals are often used to mark routes as cleared or unlocked. -- @string name The name of the shared global. Names starting with -- <code>vn.</code> are reserved for use by NVList. -- @param value The new value to store for <code>name</code>. function setSharedGlobal(name, value) Save.getSharedGlobals():set(name, value) end ---Returns a value previously stored using <code>setSharedGlobal</code>. -- @param name The name of the shared global. -- @return The stored value, or <code>nil</code> if none exists. -- @see setSharedGlobal function getSharedGlobal(name) return Save.getSharedGlobals():get(name) end ---Quicksave -------------------------------------------------------------------------------------------------------------- @section Quicksave ---Saves in the quick-save slot with the given number (1..99) -- @param[opt=nil] userdata table -- @param[opt=nil] screenshot table (screenshot, width, height) function quickSave(slot, userdata, screenshot) slot = Save.getQuickSaveSlot(slot or 1) return Save.save(slot, userdata, screenshot) end ---Loads the quick-save slot with the given number (1..99) -- If no save file exists with that number, this function does nothing function quickLoad(slot) slot = Save.getQuickSaveSlot(slot or 1) if not Save.getSaveExists(slot) then Log.warn("Nothing to quickLoad, save {} doesn't exist", slot) return end return Save.load(slot) end ---Autosave -------------------------------------------------------------------------------------------------------------- @section Autosave local KEY_AUTOSAVE_SLOTS = "autoSaveSlots" ---Returns the number of autosave slots. -- @treturn int The number of autosave slots, or <code>0</code> if autosaving is turned off. function getAutoSaveSlots() return getSharedGlobal(KEY_AUTOSAVE_SLOTS) or 4 end ---Changes the number of autosave slots used. -- @int slots The number of autosave slots to cycle through. Use 0 to effectively turn off auto saving. function setAutoSaveSlots(slots) setSharedGlobal(KEY_AUTOSAVE_SLOTS, slots or 0) end