content
stringlengths
5
1.05M
local _, ts_utils = pcall(require, 'nvim-treesitter.ts_utils') local configs = require'nvim-treesitter.configs' local M = {} M.tbl_filetypes = { 'html', 'javascript', 'typescript', 'javascriptreact', 'typescriptreact', 'svelte', 'vue', 'tsx', 'jsx' } M.tbl_skipTag = { 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'slot', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr','menuitem' } local HTML_TAG = { start_tag_pattern = 'start_tag', start_name_tag_pattern = 'tag_name', end_tag_pattern = "end_tag", end_name_tag_pattern = "tag_name", close_tag_pattern = 'erroneous_end_tag', close_name_tag_pattern = 'erroneous_end_tag_name', element_tag = 'element', skip_tag_pattern = {'quoted_attribute_value', 'end_tag'}, } local JSX_TAG = { start_tag_pattern = 'jsx_opening_element', start_name_tag_pattern = 'identifier', end_tag_pattern = "jsx_closing_element", end_name_tag_pattern = "identifier", close_tag_pattern = 'jsx_closing_element', close_name_tag_pattern = 'identifier', element_tag = 'jsx_element', skip_tag_pattern = {'jsx_closing_element','jsx_expression', 'string', 'jsx_attribute'}, } M.enable_rename = true M.enable_close = true M.setup = function (opts) opts = opts or {} M.tbl_filetypes = opts.filetypes or M.tbl_filetypes M.tbl_skipTag = opts.skip_tag or M.tbl_skipTag M.enable_rename = opts.enable_rename or M.enable_rename M.enable_close = opts.enable_close or M.enable_close end local function is_in_table(tbl, val) if tbl == nil then return false end for _, value in pairs(tbl) do if val== value then return true end end return false end M.is_supported = function (lang) return is_in_table(M.tbl_filetypes,lang) end local function is_jsx() return is_in_table({'typescriptreact', 'javascriptreact', 'javascript.jsx', 'typescript.tsx', 'javascript', 'typescript'}, vim.bo.filetype) end local function get_ts_tag() local ts_tag = HTML_TAG if is_jsx() then ts_tag = JSX_TAG end return ts_tag end M.on_file_type = function () end local function find_child_match(opts) local target = opts.target local pattern = opts.pattern local skip_tag_pattern = opts.skip_tag_pattern assert(target ~= nil, "find child target not nil :" .. pattern) for node in target:iter_children() do local node_type = node:type() if node_type ~= nil and node_type == pattern and not is_in_table(skip_tag_pattern, node_type) then return node end end end local function find_parent_match(opts) local target = opts.target local max_depth = opts.max_depth or 10 local pattern = opts.pattern local skip_tag_pattern = opts.skip_tag_pattern assert(target ~= nil, "find parent target not nil :" .. pattern) local cur_depth = 0 local cur_node = target while cur_node ~= nil do local node_type = cur_node:type() if is_in_table(skip_tag_pattern,node_type) then return nil end if node_type ~= nil and node_type == pattern then return cur_node elseif cur_depth < max_depth then cur_depth = cur_depth + 1 cur_node = cur_node:parent() else return nil end end return nil end local function get_tag_name(node) local tag_name = nil if node ~=nil then tag_name = ts_utils.get_node_text(node)[1] end return tag_name end local function find_tag_node(opt) local target = opt.target or ts_utils.get_node_at_cursor() local tag_pattern = opt.tag_pattern local name_tag_pattern = opt.name_tag_pattern local skip_tag_pattern = opt.skip_tag_pattern local find_child = opt.find_child or false local node if find_child then node = find_child_match({ target = target, pattern = tag_pattern, skip_tag_pattern = skip_tag_pattern }) else node = find_parent_match({ target = target, pattern = tag_pattern, skip_tag_pattern = skip_tag_pattern }) end if node == nil then return nil end local tbl_name_pattern = vim.split(name_tag_pattern, '>') local name_node = node for _, pattern in pairs(tbl_name_pattern) do name_node = find_child_match({ target = name_node, pattern = pattern }) end return name_node end local function find_close_tag_node(opt) opt.find_child=true return find_tag_node(opt) end local function checkCloseTag() local ts_tag = get_ts_tag() local tag_node = find_tag_node({ tag_pattern = ts_tag.start_tag_pattern, name_tag_pattern = ts_tag.start_name_tag_pattern, skip_tag_pattern = ts_tag.skip_tag_pattern }) if tag_node ~=nil then local tag_name = get_tag_name(tag_node) if tag_name ~= nil and is_in_table(M.tbl_skipTag, tag_name) then return false end -- case 6,9 check close on exist node local element_node = find_parent_match({ target = tag_node, pattern = ts_tag.element_tag, max_depth = 2 }) if tag_node ~= nil then local close_tag_node = find_close_tag_node({ target = element_node, tag_pattern = ts_tag.end_tag_pattern, name_tag_pattern = ts_tag.end_name_tag_pattern, }) if close_tag_node ~= nil then local start_row = tag_node:range() local close_start_row = close_tag_node:range() if start_row == close_start_row and tag_name == get_tag_name(close_tag_node) then return false end end end return true,tag_name end return false end M.closeTag = function () local result, tag_name = checkCloseTag() if result == true and tag_name ~= nil then vim.cmd(string.format([[normal! a</%s>]],tag_name)) vim.cmd[[normal! F>]] end end local function replaceTextNode(node, tag_name) if node == nil then return end local start_row, start_col, end_row, end_col = node:range() if start_row == end_row then local line = vim.fn.getline(start_row + 1) local newline = line:sub(0, start_col) .. tag_name .. line:sub(end_col + 1, string.len(line)) vim.fn.setline(start_row + 1,{newline}) end end local function check_tag_correct(node) if node == nil then return false end local texts = ts_utils.get_node_text(node) if string.match(texts[1],"^%<") and string.match(texts[#texts],"%>$") then return true end return false end local function rename_start_tag() local ts_tag = get_ts_tag() local tag_node = find_tag_node({ tag_pattern = ts_tag.start_tag_pattern, name_tag_pattern = ts_tag.start_name_tag_pattern, }) if tag_node == nil then return end if not check_tag_correct(tag_node:parent()) then return end local tag_name = get_tag_name(tag_node) tag_node = find_parent_match({ target = tag_node, pattern = ts_tag.element_tag, max_depth = 2 }) if tag_node == nil then return end local close_tag_node = find_close_tag_node({ target = tag_node, tag_pattern = ts_tag.close_tag_pattern, name_tag_pattern = ts_tag.close_name_tag_pattern, }) if close_tag_node ~= nil then local close_tag_name = get_tag_name(close_tag_node) if tag_name ~=close_tag_name then replaceTextNode(close_tag_node, tag_name) end else close_tag_node = find_child_match({ target = tag_node, pattern = 'ERROR' }) if close_tag_node ~=nil then local close_tag_name = get_tag_name(close_tag_node) if close_tag_name=='</>' then replaceTextNode(close_tag_node, "</"..tag_name..">") end end end end local function rename_end_tag() local ts_tag = get_ts_tag() local tag_node = find_tag_node({ tag_pattern = ts_tag.close_tag_pattern, name_tag_pattern = ts_tag.close_name_tag_pattern, }) if tag_node == nil then return end if not check_tag_correct(tag_node:parent()) then return end local tag_name = get_tag_name(tag_node) tag_node = find_parent_match({ target = tag_node, pattern = ts_tag.element_tag, max_depth = 2 }) if tag_node == nil then return end local start_tag_node = find_close_tag_node({ target = tag_node, tag_pattern = ts_tag.start_tag_pattern, name_tag_pattern = ts_tag.start_name_tag_pattern, }) if not check_tag_correct(start_tag_node:parent()) then return end if start_tag_node ~= nil then local start_tag_name = get_tag_name(start_tag_node) if tag_name ~= start_tag_name then replaceTextNode(start_tag_node, tag_name) end end end local function validate_rename() local cursor = vim.api.nvim_win_get_cursor('.') local line = vim.fn.getline(cursor[1]) local char = line:sub(cursor[2] + 1, cursor[2] + 1) -- only rename when last character is a word if string.match(char,'%w') then return true end return false end M.renameTag = function () if validate_rename() then rename_start_tag() rename_end_tag() end end M.attach = function (bufnr) local config = configs.get_module('autotag') M.setup(config) if is_in_table(M.tbl_filetypes, vim.bo.filetype) then if M.enable_close == true then vim.cmd[[inoremap <silent> <buffer> > ><c-c>:lua require('nvim-ts-autotag.internal').closeTag()<CR>a]] end if M.enable_rename == true then bufnr = bufnr or vim.api.nvim_get_current_buf() vim.cmd("augroup nvim_ts_xmltag_" .. bufnr) vim.cmd[[autocmd!]] vim.cmd[[autocmd InsertLeave <buffer> call v:lua.require('nvim-ts-autotag.internal').renameTag() ]] vim.cmd[[augroup end]] end end end M.detach = function ( ) end -- _G.AUTO = M return M
ActorPlayer = { speed=3.5, color1={242, 190, 101, 255}, color2={148, 84, 20, 255}, color3={36, 130, 15, 255}, color4={47, 40, 89, 255}, playerImage='fem_char' }
-- hdf5-udf simple_vector.h5 simple_vector.lua Simple.lua:2000:float function dynamic_dataset() local udf_data = lib.getData("Simple.lua") local udf_dims = lib.getDims("Simple.lua") print("udf_dims=" .. udf_dims[1]) local N = udf_dims[1] for i=1, N do udf_data[i] = i-1 end end
local day23 = require("day23") describe("day23", function() describe("Part 1", function() it("should work for the sample input", function() assert.are.equal(92658374, day23.part1("389125467", 10)) assert.are.equal(67384529, day23.part1("389125467", 100)) end) it("should work for the real input", function() -- my input assert.are.equal(25398647, day23.part1("952316487", 100)) end) end) describe("Part 2", function() it("should work for the sample input", function() assert.are.equal(149245887792, day23.part2("389125467")) end) it("should work for the real input", function() assert.are.equal(363807398885, day23.part2("952316487", 100)) end) end) end)
--[[FDOC @id CharaTppIntelObject @category Script Character @brief 情報ギミック ]]-- --[[ 配置スクリプト Command.StartGroup() local locator = Command.CreateData( Editor.GetInstance(), "ChCharacterLocatorData" ) local params = Command.CreateEntity( "TppGadgetLocatorParameter" ) local objectCreator = Command.CreateEntity( "TppGadgetObjectCreator" ) Command.SetProperty{ entity=locator, property="params", value=params } Command.SetProperty{ entity=locator, property="objectCreator", value=objectCreator } Command.SetProperty{ entity=locator, property="scriptPath", value="Tpp/Scripts/Gimmicks/CharaTppIntelObject.lua" } Command.AddPropertyElement{ entity=params.fileResources, property="resources", key="parts" } Command.SetProperty{ entity=params.fileResources, property="resources", key="parts", value="/Assets/tpp/parts/weapon/mis/ms03_case0_def.parts" } Command.EndGroup() --]] CharaTppIntelObject = { --[[ C++化対応済み ---------------------------------------- --各システムとの依存関係の定義 -- -- GeoやGrなどの各システムのJob実行タイミングを -- 「キャラクタのJob実行後」に合わせ、 -- システムを正常に動作させるために必要。 -- 使用するシステム名を記述してください。 -- -- "Gr" : 描画を使うなら必要 -- "Geo" : 当たりを使うなら必要 -- "Nt" : 通信同期を使うなら必要 -- "Fx" : エフェクトを使うなら必要 -- "Sd" : サウンドを使うなら必要 -- "Noise" : ノイズを使うなら必要 -- "Nav" : 経路探索を使うなら必要 -- "GroupBehavior" : 連携を使うなら必要 -- "Ui" : UIを使うなら必要 ---------------------------------------- dependSyncPoints = { "Gr", "Geo", "Nt", "Fx", "Sd", "Noise", }, pluginIndexEnumInfoName = "TppGadgetPluginDefine", ---------------------------------------- --生成処理 OnCreate() -- キャラクタ生成時に呼ばれる関数 -- プラグインの生成などを行う ---------------------------------------- OnCreate = function( chara ) local charaObj = chara:GetCharacterObject() charaObj.gadgetType = 262144 end, AddGadgetPlugins = function( chara ) --プラグインの生成 chara:AddPlugins{ -- スイッチアクションプラグイン "PLG_GADGET_INTEL_ACTION", TppGadgetIntelActionPlugin{ name = "IntelAction", parent = "ActionRoot", bodyPlugin = "Body", isAlwaysAwake = true, }, } end, ]] }
module("kinfo", package.seeall) setfenv(1, getfenv(2)); kinfo = kinfo or {} kinfo.enabled = false kinfo.colors = kinfo.colors or {} function kinfo:doInfo() local param = kinstall.params[1] if param == 'color' then local cmd = table.concat(kinstall.params, ' ', 2) if string.trim(cmd) == '' then cecho('\n<gold>Kolory afektów:\n') for name, color in pairs(kinfo.colors) do decho('<'..color[1]..','..color[2]..','..color[3]..'>'.. name ..' ') end echo('\n\n') return end local parts = string.split(cmd, "=") local affName = string.trim(parts[1]) if #parts == 1 then clearCmdLine() printCmdLine('+info color ' .. affName .. ' = ') showColors() cecho('\n<gold>Wybierz kolor klikając go, następnie wcisnij enter\n') return end local color = string.trim(parts[2]) cecho('\n<gold>Ustawiono kolor dla '.. affName ..' na ' .. color .. '\n') kinfo.colors[affName] = color_table[color] kinstall:setConfig('kinfoColors', yajl.to_string(kinfo.colors)) return end if param ~= "silent" then cecho('<gold>Włączam panel postaci\n') end kinfo:addBox() kinstall:setConfig('info', 't') kinfo.enabled = true end function kinfo:undoInfo() local param = kinstall.params[1] if param ~= 'silent' then cecho('<gold>Wyłączam panel postaci\n') end kinfo:removeBox() kinstall:setConfig('info', 'n') kinfo.enabled = false end function kinfo:doUninstall() kinfo:unregister() end function kinfo:doInit() local colors = kinstall:getConfig('kinfoColors') if colors == nil or colors == "" or colors == false then colors = "{}" end kinfo.colors = yajl.to_value(colors) if kinstall:getConfig('info') == 't' then kinfo:register() kinfo:doInfo() end end function kinfo:doUpdate() kinfo:charInfoEventHandler() end -- -- -- function kinfo:register() kinfo:unregister() kinfo.charInfoEvent = registerAnonymousEventHandler("gmcp.Char", "kinfo:charInfoEventHandler") kinfo.receivingGmcpTimer = tempTimer(2, [[ kinfo:checkGmcp() ]], true) end function kinfo:unregister() if kinfo.charInfoEvent then killAnonymousEventHandler(kinfo.charInfoEvent) end if kinfo.receivingGmcpTimer then killTimer(kinfo.receivingGmcpTimer) end end -- -- Wyswietla informacje o graczy i grupie w okienku -- function kinfo:addBox() kgui:addBox('info', 0, "Gracz", "info") kgui:setBoxContent('info', '<center>Zaloguj się do gry lub włącz GMCP</center>') end -- -- Info o braku danych -- function kinfo:checkGmcp() if kinstall.receivingGmcp == false then kgui:setBoxContent('info', '<center>Zaloguj się do gry lub włącz GMCP</center>') end end -- -- Usuwa info z okienka -- function kinfo:removeBox() kgui:removeBox('info') kgui:update() end -- -- Wyswietla informacje do okienka -- function kinfo:charInfoEventHandler() if kinfo.enabled == false then return end local char = gmcp.Char if char == nil then return end local vitals = char.Vitals if vitals == nil then return end local cond = char.Condition if cond == nil then return end local affs = char.Affects if affs == nil then return end if kgui.ui.info == nil or kgui.ui.info.wrapper == nil then return end local fontSize = kgui.baseFontHeight local compact = false local titleFontSizePx = math.floor(kgui.baseFontHeightPx * 1.5) local titleFontSize = math.floor(fontSize * 1.5) local infoFontSizePx = kgui.baseFontHeightPx local infoFontSize = fontSize if kgui.uiState.info ~= nil and kgui.uiState.info.socket == "bottomBar" then compact = true titleFontSizePx = kgui.baseFontHeightPx titleFontSize = fontSize infoFontSizePx = math.ceil(titleFontSizePx * 0.8) infoFontSize = math.ceil(titleFontSize*0.8) end local txt = '<span style="white-space:nowrap;height:' .. titleFontSizePx .. 'px;line-height:' .. titleFontSizePx .. 'px"><span style="font-size:' .. titleFontSize .. 'px;">' .. kgui:transliterate(vitals.name) .. '</span>' local sex = 'mężczyzna' if vitals.sex == 'F' then sex = 'kobieta' end txt = txt .. '<span style="font-size:' .. fontSize .. 'px;">, ' .. sex .. ', lev. ' .. vitals.level .. '</span></span>\n' local list = {} local height = titleFontSizePx local posText = kinfo:translatePos(vitals.pos) table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;">' .. posText .. '</span>') if cond.smoking == true then local s = "ćmisz&nbsp;fajkę" table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#dd0000">'..s..'</span>') end if cond.hungry == true then local s = "jesteś&nbsp;głodny" if vitals.sex == "F" then s = "Jesteś głodna" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#dd0000">'..s..'</span>') end if cond.thirsty == true then local s = "jesteś&nbsp;spragniony" if vitals.sex == "F" then s = "Jesteś spragniona" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#dd0000">'..s..'</span>') end if cond.sleepy == true then local s = "jesteś&nbsp;śpiący" if vitals.sex == "F" then s = "Jesteś śpiąca" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#dd0000">'..s..'</span>') end if cond.overweight == true then local s = "jesteś&nbsp;przeciążony" if vitals.sex == "F" then s = "Jesteś przeciążona" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#dd0000">'..s..'</span>') end if cond.drunk == true then local s = "jesteś&nbsp;pijany" if vitals.sex == "F" then s = "Jesteś pijana" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#ff8800">'..s..'</span>') end if cond.halucinations == true then local s = "jesteś&nbsp;na&nbsp;haju" table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#ff8800">'..s..'</span>') end if cond.bleedingWound == true then local s = "twoje&nbsp;rany&nbsp;krwawią" table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#ff0000">'..s..'</span>') end if cond.bleed == true then local s = "jesteś&nbsp;okaleczony" if vitals.sex == "F" then s = "Jesteś okaleczona" end table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#ff0000">'..s..'</span>') end if cond.thighJab == true then local s = "krwawisz&nbsp;z&nbsp;uda" table.insert(list, '<span style="font-size:' .. infoFontSize .. 'px;color:#ff0000">'..s..'</span>') end local cond = table.concat(list, ", ") if compact == false then txt = txt .. '<div style="font-family:\''..getFont()..'\';white-space:wrap;width:100%">' .. cond .. '</div>' height = height + kinfo:calculateTextHeight(cond, kgui.ui.info.wrapper:get_width() - kgui.boxPadding * 2 - 4, infoFontSize, infoFontSizePx) else txt = txt .. ', <span style="font-family:\''..getFont()..'\';white-space:wrap">' .. cond .. '</span>' height = kinfo:calculateTextHeight(cond, kgui.ui.info.wrapper:get_width() - kgui.boxPadding * 2 - 4, infoFontSize, infoFontSizePx) end -- AFEKTY -- sprawdzamy czy mamy informacje o afektach if affs[1] ~= nil and affs[1].unavailable ~= nil then height = height + kgui.baseFontHeightPx kgui:setBoxContent('info', txt .. '<center>' .. kgui:transliterate(affs[1].unavailable) .. '</center>', height) kgui:update() return end if #affs > 0 and compact == false then txt = txt .. '<div style="height:'..math.floor(fontSize * 0.5)..'px;font-size:'..math.floor(fontSize * 0.5)..'px;line-height:'..math.floor(fontSize * 0.5)..'px">&nbsp;</div>' height = height + math.floor(fontSize * 0.5) end txt = txt .. '\n' -- wykrywamy czy postac jest czarujaca isMage = false for _, aff in ipairs(affs) do if aff.name ~= '' then isMage = true end end if isMage == true then -- wersja dla magow, same nazwy czarow -- oraz jesli affekt nie jest czarem i nie ma nazwy - jako tekstu local rawAffs = {} for _, aff in ipairs(affs) do if aff.name == '' then table.insert(rawAffs, aff) end end height = height + infoFontSizePx * #rawAffs for _, rawAff in ipairs(rawAffs) do local color = "#44aa44" if rawAff.negative == true then color = "#dd0000" end local customColor = kinfo.colors[kgui:transliterate(rawAff.desc)] if customColor ~= nil then color = 'rgb(' .. customColor[1] .. ',' .. customColor[2] .. ',' .. customColor[3] .. ')' end local desc = utf8.gsub(kgui:transliterate(rawAff.desc), ' ', '&nbsp;') if type(rawAff.extraValue) == 'string' or type(rawAff.extraValue) == 'number' then desc = '(' .. utf8.gsub(rawAff.extraValue, ' ', '&nbsp;' ) .. ') ' .. desc end local bgColor = 'rgba(0,0,0,0)'; if rawAff.ending ~= nil and rawAff.ending == true then bgColor = 'rgba(80,0,0,255)' end txt = txt .. '<div style="line-height:' .. infoFontSize .. 'px;background-color:'..bgColor..';font-size:'..infoFontSize..'px;color:'.. color ..'">' .. desc .. '</div>' end -- same nazwy afektow w formie word-wrap local list = {} for _, aff in ipairs(affs) do if aff.name ~= '' then local color = "#44aa44" if aff.negative == true then color = "#dd0000" end local customColor = kinfo.colors[kgui:transliterate(aff.name)] if customColor ~= nil then color = 'rgb(' .. customColor[1] .. ',' .. customColor[2] .. ',' .. customColor[3] .. ')' end local affName = utf8.gsub(kgui:transliterate(aff.name), ' ', '&nbsp;') if type(aff.extraValue) == 'string' or type(aff.extraValue) == 'number' then affName = '(' .. utf8.gsub(aff.extraValue, ' ', '&nbsp;') .. ') ' .. affName end local bgColor = 'rgba(0,0,0,0)'; if aff.ending ~= nil and aff.ending == true then bgColor = 'rgba(80,0,0,255)' end table.insert(list, '<span style="background-color:'..bgColor..';font-size:'..infoFontSize..'px;color:'..color..'">'..affName..'</span>') end end if #list > 0 then local afekty = table.concat(list, ", ") txt = txt .. '<div style="line-height:' .. infoFontSize .. 'px;white-space:wrap;width:100%;font-family:\''..getFont()..'\'">' .. afekty .. '</div>' height = height + kinfo:calculateTextHeight(afekty, kgui.ui.info.wrapper:get_width() - kgui.boxPadding * 2 - 4, infoFontSize, infoFontSizePx) end else -- wersja z opisami, dla nie czarujacych if #affs > 6 then infoFontSize = math.floor(infoFontSize * 0.85) end if #affs > 8 then infoFontSize = math.floor(infoFontSize * 0.75) end height = height + infoFontSizePx * #affs for _, aff in ipairs(affs) do local color = "#44aa44" if aff.negative == true then color = "#dd0000" end local customColor = kinfo.colors[kgui:transliterate(aff.desc)] if customColor ~= nil then color = 'rgb(' .. customColor[1] .. ',' .. customColor[2] .. ',' .. customColor[3] .. ')' end local desc = utf8.gsub(kgui:transliterate(aff.desc), ' ', '&nbsp;') if type(aff.extraValue) == 'string' or type(aff.extraValue) == 'number' then desc = '(' .. utf8.gsub(aff.extraValue, ' ', '&nbsp;') .. ') ' .. desc end local bgColor = 'rgba(0,0,0,0)'; if aff.ending ~= nil and aff.ending == true then bgColor = 'rgba(80,0,0,255)' end txt = txt .. '<div style="line-height:'..infoFontSize..'px;background-color:'..bgColor..';font-size:'..infoFontSize..'px;color:'.. color ..'">' .. desc .. '</div>' end end kgui:setBoxContent('info', txt, height) kgui:update() end function kinfo:translatePos(text) if text == "dead" then return '<span style="color:#ff0000">martwy</span>' end if text == "mortally wounded" then return '<span style="color:#ff0000">umierający</span>' end if text == "incapacitated" then return '<span style="color:#ff0000">unieruchomiony</span>' end if text == "stunned" then return '<span style="color:#ff8800">oszołomiony</span>' end if text == "sleeping" then return '<span style="color:#cccc00">śpisz</span>' end if text == "resting" then return '<span style="color:#00cc00">odpoczywasz</span>' end if text == "sitting" then return '<span style="color:#ffff00">siedzisz</span>' end if text == "fighting" then return '<span style="color:#ff8800">walczysz</span>' end if text == "standing" then return '<span style="color:#00cc00">stoisz</span>' end return text end function kinfo:calculateTextHeight(txt, maxWidth, fontSize, lineHeight) local fontWidth = calcFontSize(fontSize, getFont()) local text = utf8.gsub(utf8.gsub(txt, '&nbsp;', '-'), '\<[^>]+\>', '') local wrapped = kinfo:textwrap(text, math.floor(maxWidth/fontWidth)) local linesCount = select(2, wrapped:gsub('\n', '\n')) return (1 + linesCount) * lineHeight end function kinfo:splittokens(s) local res = {} for w in s:gmatch("%S+") do res[#res+1] = w end return res end function kinfo:textwrap(text, linewidth) if not linewidth then linewidth = 75 end local spaceleft = linewidth local res = {} local line = {} for _, word in ipairs(kinfo:splittokens(text)) do if #word + 1 > spaceleft then table.insert(res, table.concat(line, ' ')) line = {word} spaceleft = linewidth - #word else table.insert(line, word) spaceleft = spaceleft - (#word + 1) end end table.insert(res, table.concat(line, ' ')) return table.concat(res, '\n') end
local lazy = require("bufferline.lazy") ---@module "bufferline.ui" local ui = lazy.require("bufferline.ui") ---@module "bufferline.pick" local pick = lazy.require("bufferline.pick") ---@module "bufferline.config" local config = lazy.require("bufferline.config") ---@module "bufferline.constants" local constants = lazy.require("bufferline.constants") ---@module "bufferline.diagnostics" local diagnostics = lazy.require("bufferline.diagnostics") ---@module "bufferline.utils" local utils = lazy.require("bufferline.utils") local api = vim.api local M = {} local padding = constants.padding local function tab_click_component(num) return "%" .. num .. "T" end local function render(tabpage, is_active, style, highlights) local h = highlights local hl = is_active and h.tab_selected.hl or h.tab.hl local separator_hl = is_active and h.separator_selected.hl or h.separator.hl local separator_component = style == "thick" and "▐" or "▕" local name = padding .. padding .. tabpage.tabnr .. padding return { { highlight = hl, text = name, attr = { prefix = tab_click_component(tabpage.tabnr) } }, { highlight = separator_hl, text = separator_component }, } end function M.get() local tabs = vim.fn.gettabinfo() local current_tab = vim.fn.tabpagenr() local highlights = config.highlights local style = config.options.separator_style return utils.map(function(tab) local is_active_tab = current_tab == tab.tabnr local components = render(tab, is_active_tab, style, highlights) return { component = components, id = tab.tabnr, windows = tab.windows, } end, tabs) end ---@param tab_num integer ---@return integer local function get_active_buf_for_tab(tab_num) local window = api.nvim_tabpage_get_win(tab_num) return api.nvim_win_get_buf(window) end ---Choose the active window's buffer as the buffer for that tab ---@param buf integer ---@return string local function get_buffer_name(buf) local name = (buf and api.nvim_buf_is_valid(buf)) and api.nvim_buf_get_name(buf) or "[No name]" return name end local function get_valid_tabs() return vim.tbl_filter(function(t) return api.nvim_tabpage_is_valid(t) end, api.nvim_list_tabpages()) end ---Filter the buffers to show based on the user callback passed in ---@param buf_nums integer[] ---@param callback fun(buf: integer, bufs: integer[]): boolean ---@return integer[] local function apply_buffer_filter(buf_nums, callback) if type(callback) ~= "function" then return buf_nums end local filtered = {} for _, buf in ipairs(buf_nums) do if callback(buf, buf_nums) then table.insert(filtered, buf) end end return next(filtered) and filtered or buf_nums end --- Get tab buffers based on open windows within the tab --- this is similar to tabpagebuflist but doesn't involve --- the viml round trip or the quirk where it occasionally returns --- a number ---@param tab_num number ---@return number[] local function get_tab_buffers(tab_num) return vim.tbl_map(api.nvim_win_get_buf, api.nvim_tabpage_list_wins(tab_num)) end ---@param state BufferlineState ---@return Tabpage[] function M.get_components(state) local options = config.options local tabs = get_valid_tabs() local Tabpage = require("bufferline.models").Tabpage ---@type Tabpage[] local components = {} pick.reset() local filter = options.custom_filter for i, tab_num in ipairs(tabs) do local active_buf = get_active_buf_for_tab(tab_num) local buffers = get_tab_buffers(tab_num) local buffer if filter then buffers = apply_buffer_filter(buffers, filter) buffer = filter(active_buf) and active_buf or buffers[1] else buffer = active_buf end local path = get_buffer_name(buffer) local all_diagnostics = diagnostics.get(options) -- TODO: decide how diagnostics should render if the focused -- window doesn't have any errors but a neighbouring window does -- local match = utils.find(buffers, function(item) -- return all_diagnostics[item].count > 0 -- end) local tab = Tabpage:new({ path = path, buf = buffer, buffers = buffers, id = tab_num, ordinal = i, diagnostics = all_diagnostics[buffer], name_formatter = options.name_formatter, hidden = false, focusable = true, }) tab.letter = pick.get(tab) components[#components + 1] = tab end return vim.tbl_map(function(tab) return ui.element(state, tab) end, components) end return M
ix.faction = ix.faction or {} ix.faction.teams = ix.faction.teams or {} ix.faction.indices = ix.faction.indices or {} local CITIZEN_MODELS = { "models/humans/group01/male_01.mdl", "models/humans/group01/male_02.mdl", "models/humans/group01/male_04.mdl", "models/humans/group01/male_05.mdl", "models/humans/group01/male_06.mdl", "models/humans/group01/male_07.mdl", "models/humans/group01/male_08.mdl", "models/humans/group01/male_09.mdl", "models/humans/group02/male_01.mdl", "models/humans/group02/male_03.mdl", "models/humans/group02/male_05.mdl", "models/humans/group02/male_07.mdl", "models/humans/group02/male_09.mdl", "models/humans/group01/female_01.mdl", "models/humans/group01/female_02.mdl", "models/humans/group01/female_03.mdl", "models/humans/group01/female_06.mdl", "models/humans/group01/female_07.mdl", "models/humans/group02/female_01.mdl", "models/humans/group02/female_03.mdl", "models/humans/group02/female_06.mdl", "models/humans/group01/female_04.mdl" } function ix.faction.LoadFromDir(directory) for _, v in ipairs(file.Find(directory.."/*.lua", "LUA")) do local niceName = v:sub(4, -5) FACTION = ix.faction.teams[niceName] or {index = table.Count(ix.faction.teams) + 1, isDefault = false} if (PLUGIN) then FACTION.plugin = PLUGIN.uniqueID end ix.util.Include(directory.."/"..v, "shared") if (!FACTION.name) then FACTION.name = "Unknown" ErrorNoHalt("Faction '"..niceName.."' is missing a name. You need to add a FACTION.name = \"Name\"\n") end if (!FACTION.description) then FACTION.description = "noDesc" ErrorNoHalt("Faction '"..niceName.."' is missing a description. You need to add a FACTION.description = \"Description\"\n") end if (!FACTION.color) then FACTION.color = Color(150, 150, 150) ErrorNoHalt("Faction '"..niceName.."' is missing a color. You need to add FACTION.color = Color(1, 2, 3)\n") end team.SetUp(FACTION.index, FACTION.name or "Unknown", FACTION.color or Color(125, 125, 125)) FACTION.models = FACTION.models or CITIZEN_MODELS FACTION.uniqueID = FACTION.uniqueID or niceName for _, v2 in pairs(FACTION.models) do if (type(v2) == "string") then util.PrecacheModel(v2) elseif (type(v2) == "table") then util.PrecacheModel(v2[1]) end end if (!FACTION.GetModels) then function FACTION:GetModels(client) return self.models end end ix.faction.indices[FACTION.index] = FACTION ix.faction.teams[niceName] = FACTION FACTION = nil end end function ix.faction.Get(identifier) return ix.faction.indices[identifier] or ix.faction.teams[identifier] end function ix.faction.GetIndex(uniqueID) for k, v in ipairs(ix.faction.indices) do if (v.uniqueID == uniqueID) then return k end end end if (CLIENT) then function ix.faction.HasWhitelist(faction) local data = ix.faction.indices[faction] if (data) then if (data.isDefault) then return true end local ixData = ix.localData and ix.localData.whitelists or {} return ixData[Schema.folder] and ixData[Schema.folder][data.uniqueID] == true or false end return false end end
local FirstNames = { "Hudson", "Jordan", "Austin", "Nathan", "Alex", "Hayden", "John", "Jasper", "Boris", "Horace", "Morris", "Doris", "Julian", "Nate", "Seth", "Luca", "Jackson", "Isaac", "David", "Matthew", "Thomas", "Sam", "Oscar", "Timothy", "Anthony", "Archer", "Christian", "Bailey", "Jayden", "Michael", "Brodie", "Caleb", "Tyler", "Jacob", "Archie", "Beau", "Gabriel", "Flynn", "Samuel", "Koby", "Sebastian", "Hugo", "Angus", "Ryder", "Leo", "Declan", "Dominic", "Toby", "Daniel", "Harry", "Joel", "Tory", "Tristan", "Will", "Taj", "Xavier", "Christopher", "Zane", "Jai", "Zac", "Thomas", "Nicholas", "Benjamin", "Marcus", "Tyson", "Andrew", "Jack", "Levi", "Ballow", "Walter", "Horatio", "Quentin" } local Surnames = { "Schenk", "Beeby", "Salisbury", "Atherton", "McColl", "Elsey", "Bowles", "Macleod", "McElhone", "Schey", "Pridham", "Wallwork", "Lassetter", "Manton", "Leary", "England", "McNess", "hutchins", "Ronald", "Stones", "Angas", "Lawrenson", "Dadswell", "Crummer", "Gloucester", "Cochran", "Ernest", "Todd", "Talbot", "Vogel", "Pryor", "Peacock", "Lakeland", "Hallahan", "Avery", "Edgerton", "Pohlman", "Nock", "Resch", "Hassall", "Waley", "Lyle", "Keynes", "Eagar", "Copeland", "Gunson", "Morell", "Cheel", "Sumsuma", "Ellen", "Dove", "Pizzey", "Morwood", "DeBavay", "Tier", "Wilding", "Stoneman", "Whittell", "Corey", "Patrick", "Loghlin", "Mortlock", "Bulcock", "chumleigh", "Sani", "Timbery", "Wheare", "Mondalmi", "Ferres", "Buckley", "Chessman", "Macadam", "Whittle", "Dacomb", "Tomkinson", "Woollacott", "Learmonth", "Cullen", "Sato", "Gibson", "Medland", "Stang", "Trout", "cabena", "Edith", "Ryder", "Hardy", "Ballow", "Kabu", "Haenke", "Pescott", "Cudmore", "Aplin", "Zahel", "Kenyon" } concommand.Add("rp_innocent", function() RunConsoleCommand( "say", "/rpname " .. table.Random( FirstNames ) .. " " .. table.Random( Surnames )) end)
local numbershers = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"} local frameX = 10 local frameY = 45 local active = false local whee local spacingY = 20 local textzoom = 0.35 local ActiveSS = 0 local SSQuery = {} SSQuery[0] = {} SSQuery[1] = {} local frameWidth = capWideScale(360, 400) local frameHeight = 350 local offsetX = 10 local offsetY = 20 local activebound = 0 for i = 1, #ms.SkillSets + 1 do SSQuery[0][i] = "0" SSQuery[1][i] = "0" end local function FilterInput(event) if event.type ~= "InputEventType_Release" and ActiveSS > 0 and active then local shouldUpdate = false if event.button == "Start" or event.button == "Back" then ActiveSS = 0 MESSAGEMAN:Broadcast("NumericInputEnded") SCREENMAN:set_input_redirected(PLAYER_1, false) return true elseif event.DeviceInput.button == "DeviceButton_backspace" then SSQuery[activebound][ActiveSS] = SSQuery[activebound][ActiveSS]:sub(1, -2) shouldUpdate = true elseif event.DeviceInput.button == "DeviceButton_delete" then SSQuery[activebound][ActiveSS] = "" shouldUpdate = true else for i = 1, #numbershers do if event.DeviceInput.button == "DeviceButton_" .. numbershers[i] then shouldUpdate = true if SSQuery[activebound][ActiveSS] == "0" then SSQuery[activebound][ActiveSS] = "" end SSQuery[activebound][ActiveSS] = SSQuery[activebound][ActiveSS] .. numbershers[i] if (ActiveSS < #ms.SkillSets + 1 and #SSQuery[activebound][ActiveSS] > 2) or #SSQuery[activebound][ActiveSS] > 3 then SSQuery[activebound][ActiveSS] = numbershers[i] end end end end if SSQuery[activebound][ActiveSS] == "" then shouldUpdate = true SSQuery[activebound][ActiveSS] = "0" end if shouldUpdate then FILTERMAN:SetSSFilter(tonumber(SSQuery[activebound][ActiveSS]), ActiveSS, activebound) whee:SongSearch("") -- stupid workaround? MESSAGEMAN:Broadcast("UpdateFilter") end end end local translated_info = { Mode = THEME:GetString("TabFilter", "Mode"), HighestOnly = THEME:GetString("TabFilter", "HighestOnly"), On = THEME:GetString("OptionNames", "On"), Off = THEME:GetString("OptionNames", "Off"), Matches = THEME:GetString("TabFilter", "Matches"), CommonPackFilter = THEME:GetString("TabFilter", "CommonPackFilter"), Length = THEME:GetString("TabFilter", "Length"), AND = THEME:GetString("TabFilter", "AND"), OR = THEME:GetString("TabFilter", "OR"), ExplainStartInput = THEME:GetString("TabFilter", "ExplainStartInput"), ExplainCancelInput = THEME:GetString("TabFilter", "ExplainCancelInput"), ExplainGrey = THEME:GetString("TabFilter", "ExplainGrey"), ExplainBounds = THEME:GetString("TabFilter", "ExplainBounds"), ExplainHighest = THEME:GetString("TabFilter", "ExplainHighest"), MaxRate = THEME:GetString("TabFilter", "MaxRate"), Title = THEME:GetString("TabFilter", "Title"), MinRate = THEME:GetString("TabFilter", "MinRate") } local f = Def.ActorFrame { InitCommand = function(self) self:xy(frameX, frameY):halign(0) end, Def.Quad { InitCommand = function(self) self:zoomto(frameWidth, frameHeight):halign(0):valign(0):diffuse(color("#333333CC")) end }, Def.Quad { InitCommand = function(self) self:zoomto(frameWidth, offsetY):halign(0):valign(0):diffuse(getMainColor("frames")):diffusealpha(0.5) end }, LoadFont("Common Normal") .. { InitCommand = function(self) self:xy(5, offsetY - 9):zoom(0.6):halign(0):diffuse(getMainColor("positive")):settext(translated_info["Title"]) end }, OnCommand = function(self) whee = SCREENMAN:GetTopScreen():GetMusicWheel() SCREENMAN:GetTopScreen():AddInputCallback(FilterInput) self:visible(false) end, SetCommand = function(self) self:finishtweening() if getTabIndex() == 5 then self:visible(true) active = true else MESSAGEMAN:Broadcast("NumericInputEnded") self:visible(false) self:queuecommand("Off") active = false end end, TabChangedMessageCommand = function(self) self:queuecommand("Set") end, MouseRightClickMessageCommand = function(self) ActiveSS = 0 MESSAGEMAN:Broadcast("NumericInputEnded") MESSAGEMAN:Broadcast("UpdateFilter") SCREENMAN:set_input_redirected(PLAYER_1, false) end, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX, frameY):zoom(0.3):halign(0) self:settext(translated_info["ExplainStartInput"]) end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX, frameY + 20):zoom(0.3):halign(0) self:settext(translated_info["ExplainCancelInput"]) end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX, frameY + 40):zoom(0.3):halign(0) self:settext(translated_info["ExplainGrey"]) end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX, frameY + 60):zoom(0.3):halign(0) self:settext(translated_info["ExplainBounds"]) end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX, frameY + 80):zoom(0.3):halign(0) self:settext(translated_info["ExplainHighest"]) end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175):zoom(textzoom):halign(0) end, SetCommand = function(self) self:settextf("%s:%5.1fx", translated_info["MaxRate"], FILTERMAN:GetMaxFilterRate()) end, MaxFilterRateChangedMessageCommand = function(self) self:queuecommand("Set") end, ResetFilterMessageCommand = function(self) self:queuecommand("Set") end }, Def.Quad { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175):zoomto(130, 18):halign(0):diffusealpha(0) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:SetMaxFilterRate(FILTERMAN:GetMaxFilterRate() + 0.1) MESSAGEMAN:Broadcast("MaxFilterRateChanged") whee:SongSearch("") end end, MouseRightClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:SetMaxFilterRate(FILTERMAN:GetMaxFilterRate() - 0.1) MESSAGEMAN:Broadcast("MaxFilterRateChanged") whee:SongSearch("") end end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY):zoom(textzoom):halign(0) end, SetCommand = function(self) self:settextf("%s:%5.1fx", translated_info["MinRate"], FILTERMAN:GetMinFilterRate()) end, MaxFilterRateChangedMessageCommand = function(self) self:queuecommand("Set") end, ResetFilterMessageCommand = function(self) self:queuecommand("Set") end }, Def.Quad { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY):zoomto(130, 18):halign(0):diffusealpha(0) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:SetMinFilterRate(FILTERMAN:GetMinFilterRate() + 0.1) MESSAGEMAN:Broadcast("MaxFilterRateChanged") whee:SongSearch("") end end, MouseRightClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:SetMinFilterRate(FILTERMAN:GetMinFilterRate() - 0.1) MESSAGEMAN:Broadcast("MaxFilterRateChanged") whee:SongSearch("") end end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 2):zoom(textzoom):halign(0) end, SetCommand = function(self) if FILTERMAN:GetFilterMode() then self:settextf("%s: %s", translated_info["Mode"], translated_info["AND"]) else self:settextf("%s: %s", translated_info["Mode"], translated_info["OR"]) end end, FilterModeChangedMessageCommand = function(self) self:queuecommand("Set") end, ResetFilterMessageCommand = function(self) self:queuecommand("Set") end }, Def.Quad { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 2):zoomto(120, 18):halign(0):diffusealpha(0) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:ToggleFilterMode() MESSAGEMAN:Broadcast("FilterModeChanged") whee:SongSearch("") end end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 3):zoom(textzoom):halign(0) end, SetCommand = function(self) if FILTERMAN:GetHighestSkillsetsOnly() then self:settextf("%s: %s", translated_info["HighestOnly"], translated_info["On"]) else self:settextf("%s: %s", translated_info["HighestOnly"], translated_info["Off"]) end if FILTERMAN:GetFilterMode() then self:diffuse(color("#666666")) else self:diffuse(color("#FFFFFF")) end end, FilterModeChangedMessageCommand = function(self) self:queuecommand("Set") end, ResetFilterMessageCommand = function(self) self:queuecommand("Set") end }, Def.Quad { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 3):zoomto(160, 18):halign(0):diffusealpha(0) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:ToggleHighestSkillsetsOnly() MESSAGEMAN:Broadcast("FilterModeChanged") whee:SongSearch("") end end }, LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 4):zoom(textzoom):halign(0):settext("") end, FilterResultsMessageCommand = function(self, msg) self:settextf("%s: %i/%i", translated_info["Matches"], msg.Matches, msg.Total) end }, LoadFont("Common Large") .. { BeginCommand = function(self) self:xy(frameX + frameWidth / 2, 175 + spacingY * 5):zoom(textzoom):halign(0):maxwidth(300) self.packlistFiltering = FILTERMAN:GetFilteringCommonPacks() self.enabled = SCREENMAN:GetTopScreen():GetName() == "ScreenNetSelectMusic" if not self.enabled then self:visible(false) end self:queuecommand("Set") end, MouseLeftClickMessageCommand = function(self) if self.enabled and isOver(self) and active then self.packlistFiltering = whee:SetPackListFiltering(not self.packlistFiltering) self:queuecommand("Set") end end, SetCommand = function(self) self:settextf("%s: %s", translated_info["CommonPackFilter"], (self.packlistFiltering and translated_info["On"] or translated_info["Off"])) end, FilterModeChangedMessageCommand = function(self) self:queuecommand("Set") end, ResetFilterMessageCommand = function(self) self:queuecommand("Set") end } } local function CreateFilterInputBox(i) local t = Def.ActorFrame { LoadFont("Common Large") .. { InitCommand = function(self) self:addx(10):addy(175 + (i - 1) * spacingY):halign(0):zoom(textzoom) end, SetCommand = function(self) self:settext(i == (#ms.SkillSets + 1) and translated_info["Length"] or ms.SkillSetsTranslated[i]) end }, Def.Quad { InitCommand = function(self) self:addx(i == (#ms.SkillSets + 1) and 159 or 150):addy(175 + (i - 1) * spacingY):zoomto( i == (#ms.SkillSets + 1) and 27 or 18, 18 ):halign(1) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then ActiveSS = i activebound = 0 MESSAGEMAN:Broadcast("NumericInputActive") self:diffusealpha(0.1) SCREENMAN:set_input_redirected(PLAYER_1, true) end end, SetCommand = function(self) if ActiveSS == i and activebound == 0 then self:diffuse(color("#666666")) else self:diffuse(color("#000000")) end end, UpdateFilterMessageCommand = function(self) self:queuecommand("Set") end, NumericInputEndedMessageCommand = function(self) self:queuecommand("Set") end, NumericInputActiveMessageCommand = function(self) self:queuecommand("Set") end }, LoadFont("Common Large") .. { InitCommand = function(self) self:addx(i == (#ms.SkillSets + 1) and 159 or 150):addy(175 + (i - 1) * spacingY):halign(1):maxwidth(60):zoom( textzoom ) end, SetCommand = function(self) local fval = FILTERMAN:GetSSFilter(i, 0) -- lower bounds self:settext(fval) if fval <= 0 and ActiveSS ~= i then self:diffuse(color("#666666")) elseif activebound == 0 then self:diffuse(color("#FFFFFF")) end end, UpdateFilterMessageCommand = function(self) self:queuecommand("Set") end, NumericInputActiveMessageCommand = function(self) self:queuecommand("Set") end }, Def.Quad { InitCommand = function(self) self:addx(i == (#ms.SkillSets + 1) and 193 or 175):addy(175 + (i - 1) * spacingY):zoomto( i == (#ms.SkillSets + 1) and 27 or 18, 18 ):halign(1) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then ActiveSS = i activebound = 1 MESSAGEMAN:Broadcast("NumericInputActive") self:diffusealpha(0.1) SCREENMAN:set_input_redirected(PLAYER_1, true) end end, SetCommand = function(self) if ActiveSS == i and activebound == 1 then self:diffuse(color("#666666")) else self:diffuse(color("#000000")) end end, UpdateFilterMessageCommand = function(self) self:queuecommand("Set") end, NumericInputEndedMessageCommand = function(self) self:queuecommand("Set") end, NumericInputActiveMessageCommand = function(self) self:queuecommand("Set") end }, LoadFont("Common Large") .. { InitCommand = function(self) self:addx(i == (#ms.SkillSets + 1) and 193 or 175):addy(175 + (i - 1) * spacingY):halign(1):maxwidth(60):zoom( textzoom ) end, SetCommand = function(self) local fval = FILTERMAN:GetSSFilter(i, 1) -- upper bounds self:settext(fval) if fval <= 0 and ActiveSS ~= i then self:diffuse(color("#666666")) elseif activebound == 1 then self:diffuse(color("#FFFFFF")) end end, UpdateFilterMessageCommand = function(self) self:queuecommand("Set") end, NumericInputActiveMessageCommand = function(self) self:queuecommand("Set") end } } return t end --reset button f[#f + 1] = Def.Quad { InitCommand = function(self) self:xy(frameX + frameWidth - 150, frameY + 250):zoomto(60, 20):halign(0.5):diffuse(getMainColor("frames")):diffusealpha( 0 ) end, MouseLeftClickMessageCommand = function(self) if isOver(self) and active then FILTERMAN:ResetAllFilters() for i = 1, #ms.SkillSets do SSQuery[0][i] = "0" SSQuery[1][i] = "0" end activebound = 0 ActiveSS = 0 MESSAGEMAN:Broadcast("UpdateFilter") MESSAGEMAN:Broadcast("ResetFilter") MESSAGEMAN:Broadcast("NumericInputEnded") SCREENMAN:set_input_redirected(PLAYER_1, false) whee:SongSearch("") end end } f[#f + 1] = LoadFont("Common Large") .. { InitCommand = function(self) self:xy(frameX + frameWidth - 150, frameY + 250):halign(0.5):zoom(0.35) self:settext(THEME:GetString("TabFilter", "Reset")) end } for i = 1, (#ms.SkillSets + 1) do f[#f + 1] = CreateFilterInputBox(i) end return f
require "mods" require "playerprofile" require "playerdeaths" require "saveindex" require "map/extents" local LOAD_UPFRONT_MODE = false local MainScreen = nil if PLATFORM == "PS4" then MainScreen = require "screens/mainscreen_ps4" else MainScreen = require "screens/mainscreen" end -- Always on broadcasting widget BroadcastingWidget = require "widgets/broadcastingwidget" if PLATFORM == "WIN32_STEAM" or PLATFORM == "WIN32" then global_broadcastnig_widget = BroadcastingWidget() global_broadcastnig_widget:SetHAnchor(ANCHOR_LEFT) global_broadcastnig_widget:SetVAnchor(ANCHOR_TOP) end global_loading_widget = nil if PLATFORM == "PS4" then LoadingWidget = require "widgets/loadingwidget" global_loading_widget = LoadingWidget() global_loading_widget:SetHAnchor(ANCHOR_LEFT) global_loading_widget:SetVAnchor(ANCHOR_BOTTOM) end local DeathScreen = require "screens/deathscreen" local PopupDialogScreen = require "screens/popupdialog" local WorldGenScreen = require "screens/worldgenscreen" local CharacterSelectScreen = require "screens/characterselectscreen" local PauseScreen = require "screens/pausescreen" local PlayerHud = require "screens/playerhud" Print (VERBOSITY.DEBUG, "[Loading frontend assets]") local start_game_time = nil LOADED_CHARACTER = nil TheSim:SetRenderPassDefaultEffect( RENDERPASS.BLOOM, "shaders/anim_bloom.ksh" ) TheSim:SetErosionTexture( "images/erosion.tex" ) BACKEND_PREFABS = {"hud", "forest", "cave", "maxwell", "fire", "character_fire", "shatter"} FRONTEND_PREFABS = {"frontend"} RECIPE_PREFABS = {} --this is suuuuuper placeholdery. We need to think about how to handle all of the different types of updates for this local function DoAgeWorld() for k,v in pairs(Ents) do --send things to their homes if v.components.homeseeker and v.components.homeseeker.home then if v.components.homeseeker.home.components.childspawner then v.components.homeseeker.home.components.childspawner:GoHome(v) end if v.components.homeseeker.home.components.spawner then v.components.homeseeker.home.components.spawner:GoHome(v) end end end end local function KeepAlive() if global_loading_widget then global_loading_widget:ShowNextFrame() TheSim:RenderOneFrame() global_loading_widget:ShowNextFrame() end end local function ShowLoading() if global_loading_widget then global_loading_widget:SetEnabled(true) end end local function LoadAssets(asset_set) if LOAD_UPFRONT_MODE then return end ShowLoading() assert(asset_set) Settings.current_asset_set = asset_set RECIPE_PREFABS = {} for k,v in pairs(Recipes) do table.insert(RECIPE_PREFABS, v.name) if v.placer then table.insert(RECIPE_PREFABS, v.placer) end end local load_frontend = Settings.reset_action == nil local in_backend = Settings.last_reset_action ~= nil local in_frontend = not in_backend KeepAlive() if Settings.current_asset_set == "FRONTEND" then if Settings.last_asset_set == "FRONTEND" then print( "\tFE assets already loaded" ) for i,file in ipairs(PREFABFILES) do -- required from prefablist.lua LoadPrefabFile("prefabs/"..file) end ModManager:RegisterPrefabs() else print("\tUnload BE") TheSim:UnloadPrefabs(RECIPE_PREFABS) TheSim:UnloadPrefabs(BACKEND_PREFABS) print("\tUnload BE done") KeepAlive() TheSystemService:SetStalling(true) TheSim:UnregisterAllPrefabs() RegisterAllDLC() for i,file in ipairs(PREFABFILES) do -- required from prefablist.lua LoadPrefabFile("prefabs/"..file) end ModManager:RegisterPrefabs() TheSystemService:SetStalling(false) KeepAlive() print("\tLoad FE") TheSystemService:SetStalling(true) TheSim:LoadPrefabs(FRONTEND_PREFABS) TheSystemService:SetStalling(false) print("\tLoad FE: done") KeepAlive() end else if Settings.last_asset_set == "BACKEND" then print( "\tBE assets already loaded" ) RegisterAllDLC() for i,file in ipairs(PREFABFILES) do -- required from prefablist.lua LoadPrefabFile("prefabs/"..file) end ModManager:RegisterPrefabs() else print("\tUnload FE") TheSim:UnloadPrefabs(FRONTEND_PREFABS) print("\tUnload FE done") KeepAlive() TheSystemService:SetStalling(true) TheSim:UnregisterAllPrefabs() RegisterAllDLC() for i,file in ipairs(PREFABFILES) do -- required from prefablist.lua LoadPrefabFile("prefabs/"..file) end InitAllDLC() ModManager:RegisterPrefabs() TheSystemService:SetStalling(false) KeepAlive() print ("\tLOAD BE") TheSystemService:SetStalling(true) TheSim:LoadPrefabs(BACKEND_PREFABS) TheSystemService:SetStalling(false) KeepAlive() TheSystemService:SetStalling(true) TheSim:LoadPrefabs(RECIPE_PREFABS) TheSystemService:SetStalling(false) print ("\tLOAD BE : done") KeepAlive() end end Settings.last_asset_set = Settings.current_asset_set end function GetTimePlaying() if not start_game_time then return 0 end return GetTime() - start_game_time end function CalculatePlayerRewards(wilson) local Progression = require "progressionconstants" print("Calculating progression") --increment the xp counter and give rewards local days_survived = GetClock().numcycles local start_xp = wilson.profile:GetXP() local reward_xp = Progression.GetXPForDays(days_survived) local new_xp = math.min(start_xp + reward_xp, Progression.GetXPCap()) local capped = Progression.IsCappedXP(start_xp) local all_rewards = Progression.GetRewardsForTotalXP(new_xp) for k,v in pairs(all_rewards) do wilson.profile:UnlockCharacter(v) end wilson.profile:SetXP(new_xp) print("Progression: ",days_survived, start_xp, reward_xp, new_xp) return days_survived, start_xp, reward_xp, new_xp, capped end local function HandleDeathCleanup(wilson, data) local game_time = GetClock():ToMetricsString() if SaveGameIndex:GetCurrentMode() == "survival" or SaveGameIndex:GetCurrentMode() == "cave" then local playtime = GetTimePlaying() playtime = math.floor(playtime*1000) SetTimingStat("time", "scenario", playtime) SendTrackingStats() local days_survived, start_xp, reward_xp, new_xp, capped = CalculatePlayerRewards(wilson) ProfileStatsSet("xp_gain", reward_xp) ProfileStatsSet("xp_total", new_xp) SubmitCompletedLevel() --close off the instance wilson.components.health.invincible = true wilson.profile:Save(function() SaveGameIndex:EraseCurrent(function() scheduler:ExecuteInTime(3, function() TheFrontEnd:PushScreen(DeathScreen(days_survived, start_xp, nil, capped)) end) end) end) elseif SaveGameIndex:GetCurrentMode() == "adventure" then SaveGameIndex:OnFailAdventure(function() scheduler:ExecuteInTime(3, function() TheFrontEnd:Fade(false, 3, function() StartNextInstance({reset_action=RESET_ACTION.LOAD_SLOT, save_slot = SaveGameIndex:GetCurrentSaveSlot(), playeranim="failadventure"}) end) end) end) end end local function OnPlayerDeath(wilson, data) print ("OnPlayerDeath") local cause = data.cause or "unknown" local will_resurrect = wilson.components.resurrectable and wilson.components.resurrectable:CanResurrect() print ("OnPlayerDeath() ", cause, tostring(will_resurrect)) wilson.HUD:Hide() if cause ~= "file_load" then TheMixer:PushMix("death") Morgue:OnDeath({killed_by=cause, days_survived=GetClock().numcycles or 0, character=GetPlayer().prefab, location= (wilson.components.area_aware and wilson.components.area_aware.current_area.story) or "unknown", world= (GetWorld().meta and GetWorld().meta.level_id) or "unknown"}) local game_time = GetClock():ToMetricsString() RecordDeathStats(cause, GetClock():GetPhase(), wilson.components.sanity.current, wilson.components.hunger.current, will_resurrect) ProfileStatsAdd("killed_by_"..cause) ProfileStatsAdd("deaths") end if will_resurrect or cause == "file_load" then local res = wilson.components.resurrectable:FindClosestResurrector() print ("OnPlayerDeath() ", tostring(res)) local delay = 4 if cause == "file_load" then TheFrontEnd:Fade(false, 0) delay = 0 end -- if the resurrector is in this file then: if res then local resfn = function() TheMixer:PopMix("death") if wilson.components.resurrectable:DoResurrect() then if delay == 0 then TheFrontEnd:Fade(true, 3) end ProfileStatsAdd("resurrections") else HandleDeathCleanup(wilson, data) end end if delay > 0 then scheduler:ExecuteInTime(delay, resfn) else resfn() end elseif cause ~= "file_load" then -- if the resurrector is in another file then: -- set start params -- save this file -- load file -- Its in a different file res = SaveGameIndex:GetResurrector() if res then DoAgeWorld() SaveGameIndex:SaveCurrent(function() SaveGameIndex:GotoResurrector(function() TheFrontEnd:Fade(false, 8.3, function() StartNextInstance({reset_action=RESET_ACTION.LOAD_SLOT, save_slot = SaveGameIndex:GetCurrentSaveSlot(), playeranim="file_load"}) end) end) end, "resurrect") end end else HandleDeathCleanup(wilson, data) end end function SetUpPlayerCharacterCallbacks(wilson) --set up on ondeath handler wilson:ListenForEvent( "death", function(inst, data) OnPlayerDeath(wilson, data) end) wilson:ListenForEvent( "quit", function() Print (VERBOSITY.DEBUG, "I SHOULD QUIT!") TheMixer:PushMix("death") wilson.HUD:Hide() local playtime = GetTimePlaying() playtime = math.floor(playtime*1000) RecordQuitStats() SetTimingStat("time", "scenario", playtime) ProfileStatsSet("time_played", playtime) SendTrackingStats() SendAccumulatedProfileStats() --TheSim:UnloadPrefabs(LOADED_CHARACTER) --LOADED_CHARACTER = nil EnableAllDLC() StartNextInstance() end) wilson:ListenForEvent( "daycomplete", function(it, data) if not wilson.components.health:IsDead() then RecordEndOfDayStats() ProfileStatsAdd("nights_survived_iar") SendAccumulatedProfileStats() end end, GetWorld()) wilson:ListenForEvent("builditem", function(inst, data) ProfileStatsAdd("build_item_"..data.item.prefab) end) wilson:ListenForEvent("buildstructure", function(inst, data) ProfileStatsAdd("build_structure_"..data.item.prefab) end) end local function StartGame(wilson) TheFrontEnd:GetSound():KillSound("FEMusic") -- just in case... start_game_time = GetTime() SetUpPlayerCharacterCallbacks(wilson) -- wilson:DoTaskInTime(3, function() TheSim:Hook() end) end local deprecated = { turf_webbing = true } local replace = { farmplot = "slow_farmplot", farmplot2 = "fast_farmplot", farmplot3 = "fast_farmplot", sinkhole= "cave_entrance", cave_stairs= "cave_entrance" } POPULATING = false function PopulateWorld(savedata, profile, playercharacter, playersavedataoverride) POPULATING = true TheSystemService:SetStalling(true) playercharacter = playercharacter or "wilson" Print(VERBOSITY.DEBUG, "PopulateWorld") Print(VERBOSITY.DEBUG, "[Instantiating objects...]" ) local wilson = nil if savedata then --figure out our start info local spawnpoint = Vector3(0,0,0) local playerdata = {} if savedata.playerinfo then if savedata.playerinfo.x and savedata.playerinfo.z then local y = savedata.playerinfo.y or 0 spawnpoint = Vector3(savedata.playerinfo.x, y, savedata.playerinfo.z) end if savedata.playerinfo.data then playerdata = savedata.playerinfo.data end end local travel_direction = SaveGameIndex:GetDirectionOfTravel() local cave_num = SaveGameIndex:GetCaveNumber() --print("travel_direction:", travel_direction, "cave#:",cave_num) local spawn_ent = nil if travel_direction == "ascend" then if savedata.ents["cave_entrance"] then if cave_num == nil then spawn_ent = savedata.ents["cave_entrance"][1] else for k,v in ipairs(savedata.ents["cave_entrance"]) do if v.data and v.data.cavenum == cave_num then spawn_ent = v break end end end end elseif travel_direction == "descend" then if savedata.ents["cave_exit"] then spawn_ent = savedata.ents["cave_exit"][1] end end if spawn_ent and spawn_ent.x and spawn_ent.z then spawnpoint = Vector3(spawn_ent.x or 0, spawn_ent.y or 0, spawn_ent.z or 0) end if playersavedataoverride then playerdata = playersavedataoverride end local newents = {} --local world = SpawnPrefab("forest") local world = nil local ceiling = nil if savedata.map.prefab == "cave" then world = SpawnPrefab("cave") -- ceiling = SpawnPrefab("ceiling") else world = SpawnPrefab("forest") end --spawn the player character and set him up if not LOAD_UPFRONT_MODE then local old_loaded_character = LOADED_CHARACTER and LOADED_CHARACTER[1] if old_loaded_character ~= playercharacter then if old_loaded_character then TheSim:UnLoadPrefabs(LOADED_CHARACTER) end LOADED_CHARACTER = {playercharacter} TheSim:LoadPrefabs(LOADED_CHARACTER) end end wilson = SpawnPrefab(playercharacter) assert(wilson, "could not spawn player character") wilson:SetProfile(Profile) wilson.Transform:SetPosition(spawnpoint:Get()) --this was spawned by the level file. kinda lame - we should just do everything from in here. local ground = GetWorld() if ground then ground.Map:SetSize(savedata.map.width, savedata.map.height) ground.Map:SetFromString(savedata.map.tiles) if savedata.map.prefab == "cave" then ground.Map:SetPhysicsWallDistance(0.75)--0) -- TEMP for STREAM TheFrontEnd:GetGraphicsOptions():DisableStencil() TheFrontEnd:GetGraphicsOptions():DisableLightMapComponent() -- TheFrontEnd:GetGraphicsOptions():EnableStencil() -- TheFrontEnd:GetGraphicsOptions():EnableLightMapComponent() ground.Map:Finalize(1) else ground.Map:SetPhysicsWallDistance(0)--0.75) TheFrontEnd:GetGraphicsOptions():DisableStencil() TheFrontEnd:GetGraphicsOptions():DisableLightMapComponent() ground.Map:Finalize(0) end if savedata.map.nav then print("Loading Nav Grid") ground.Map:SetNavSize(savedata.map.width, savedata.map.height) ground.Map:SetNavFromString(savedata.map.nav) else print("No Nav Grid") end ground.hideminimap = savedata.map.hideminimap ground.topology = savedata.map.topology ground.meta = savedata.meta assert(savedata.map.topology.ids, "[MALFORMED SAVE DATA] Map missing topology information. This save file is too old, and is missing neccessary information.") for i=#savedata.map.topology.ids,1, -1 do local name = savedata.map.topology.ids[i] if string.find(name, "LOOP_BLANK_SUB") ~= nil then table.remove(savedata.map.topology.ids, i) table.remove(savedata.map.topology.nodes, i) for eid=#savedata.map.topology.edges,1,-1 do if savedata.map.topology.edges[eid].n1 == i or savedata.map.topology.edges[eid].n2 == i then table.remove(savedata.map.topology.edges, eid) end end end end if ground.topology.level_number ~= nil then local levels = require("map/levels") if levels.story_levels[ground.topology.level_number] ~= nil then profile:UnlockWorldGen("preset", levels.story_levels[ground.topology.level_number].name) end end if ground.topology.level_number == 2 and ground:HasTag("cave") then ground:AddTag("ruin") ground:AddComponent("nightmareclock") ground:AddComponent("nightmareambientsoundmixer") end wilson:AddComponent("area_aware") --wilson:AddComponent("area_unlock") if ground.topology.override_triggers then wilson:AddComponent("area_trigger") wilson.components.area_trigger:RegisterTriggers(ground.topology.override_triggers) end for i,node in ipairs(ground.topology.nodes) do local story = ground.topology.ids[i] -- guard for old saves local story_depth = nil if ground.topology.story_depths then story_depth = ground.topology.story_depths[i] end if story ~= "START" then story = string.sub(story, 1, string.find(story,":")-1) -- -- if Profile:IsWorldGenUnlocked("tasks", story) == false then -- wilson.components.area_unlock:RegisterStory(story) -- end end wilson.components.area_aware:RegisterArea({idx=i, type=node.type, poly=node.poly, story=story, story_depth=story_depth}) if node.type == "Graveyard" or node.type == "MistyCavern" then if node.area_emitter == nil then local mist = SpawnPrefab( "mist" ) mist.Transform:SetPosition( node.cent[1], 0, node.cent[2] ) mist.components.emitter.area_emitter = CreateAreaEmitter( node.poly, node.cent ) if node.area == nil then node.area = 1 end local ext = ResetextentsForPoly(node.poly) mist.entity:SetAABB(ext.radius, 2) mist.components.emitter.density_factor = math.ceil(node.area / 4)/31 mist.components.emitter:Emit() end end end if savedata.map.persistdata ~= nil then ground:SetPersistData(savedata.map.persistdata) end wilson.components.area_aware:StartCheckingPosition() end wilson:SetPersistData(playerdata, newents) if savedata.playerinfo and savedata.playerinfo.id then newents[savedata.playerinfo.id] = {entity=wilson, data=playerdata} end if GetWorld().components.colourcubemanager then GetWorld().components.colourcubemanager:StartBlend(0) GetWorld().components.colourcubemanager:OnUpdate(0) end --set the clock (LEGACY! this is now handled via the world object's normal serialization) if savedata.playerinfo.day and savedata.playerinfo.dayphase and savedata.playerinfo.timeleftinera then GetClock().numcycles = savedata.playerinfo and savedata.playerinfo.day or 0 if savedata.playerinfo and savedata.playerinfo.dayphase == "night" then GetClock():StartNight(true) elseif savedata.playerinfo and savedata.playerinfo.dayphase == "dusk" then GetClock():StartDusk(true) else GetClock():StartDay(true) end if savedata.playerinfo.timeleftinera then GetClock().timeLeftInEra = savedata.playerinfo.timeleftinera end end -- Force overrides for ambient local retune = require("tuning_override") retune.OVERRIDES["areaambientdefault"].doit(savedata.map.prefab) -- Check for map overrides if ground.topology.overrides ~= nil and ground.topology.overrides ~= nil and GetTableSize(ground.topology.overrides) > 0 then for area, overrides in pairs(ground.topology.overrides) do for i,override in ipairs(overrides) do if retune.OVERRIDES[override[1]] ~= nil then retune.OVERRIDES[override[1]].doit(override[2]) end end end end -- Clean out any stale ones SaveGameIndex:ClearCurrentResurrectors() --instantiate all the dudes for prefab, ents in pairs(savedata.ents) do local prefab = replace[prefab] or prefab if not deprecated[prefab] then for k,v in ipairs(ents) do v.prefab = v.prefab or prefab -- prefab field is stripped out when entities are saved in global entity collections, so put it back SpawnSaveRecord(v, newents) end end end --post pass in neccessary to hook up references for k,v in pairs(newents) do v.entity:LoadPostPass(newents, v.data) end GetWorld():LoadPostPass(newents, savedata.map.persistdata) SaveGameIndex:LoadSavedFollowers(GetPlayer()) SaveGameIndex:LoadSavedSeasonData(GetPlayer()) if world.prefab == "cave" then GetSeasonManager():SetCaves() end --Run scenario scripts for guid, ent in pairs(Ents) do if ent.components.scenariorunner then ent.components.scenariorunner:Run() end end --Record mod information ModManager:SetModRecords(savedata.mods or {}) SetSuper(savedata.super) if SaveGameIndex:GetCurrentMode() ~= "adventure" and GetWorld().components.age and GetPlayer().components.age then local player_age = GetPlayer().components.age:GetAge() local world_age = GetWorld().components.age:GetAge() if player_age > world_age then if travel_direction == "ascend" or travel_direction == "descend" then local catch_up = player_age - world_age print ("Catching up world", catch_up, "(", player_age,"/",world_age,")" ) LongUpdate(catch_up, true) --this is a cheesy workaround for coming out of a cave at night, so you don't get immediately eaten if SaveGameIndex:GetCurrentMode() == "survival" and not GetWorld().components.clock:IsDay() then local light = SpawnPrefab("exitcavelight") light.Transform:SetPosition(GetPlayer().Transform:GetWorldPosition()) end elseif world_age <= 0 then print ("New world, reset player age.") GetPlayer().components.age.saved_age = 0 end end end --Everything has been loaded! Now fix the colour cubes... --Gross place to put this, should be using a post init. if ground.components.colourcubemanager then ground.components.colourcubemanager:StartBlend(0) end else Print(VERBOSITY.ERROR, "[MALFORMED SAVE DATA] PopulateWorld complete" ) TheSystemService:SetStalling(false) POPULATING = false return end Print(VERBOSITY.DEBUG, "[FINISHED LOADING SAVED GAME] PopulateWorld complete" ) TheSystemService:SetStalling(false) POPULATING = false return wilson end local function DrawDebugGraph(graph) -- debug draw of new map gen local debugdrawmap = CreateEntity() local draw = debugdrawmap.entity:AddDebugRender() draw:SetZ(0.1) draw:SetRenderLoop(true) for idx,node in ipairs(graph.nodes) do local colour = graph.colours[node.c] for i =1, #node.poly-1 do draw:Line(node.poly[i][1], node.poly[i][2], node.poly[i+1][1], node.poly[i+1][2], colour.r, colour.g, colour.b, 255) end draw:Line(node.poly[1][1], node.poly[1][2], node.poly[#node.poly][1], node.poly[#node.poly][2], colour.r, colour.g, colour.b, 255) draw:Poly(node.cent[1], node.cent[2], colour.r, colour.g, colour.b, colour.a, node.poly) draw:String(graph.ids[idx].."("..node.cent[1]..","..node.cent[2]..")", node.cent[1], node.cent[2], node.ts) end draw:SetZ(0.15) for idx,edge in ipairs(graph.edges) do if edge.n1 ~= nil and edge.n2 ~= nil then local colour = graph.colours[edge.c] local n1 = graph.nodes[edge.n1] local n2 = graph.nodes[edge.n2] if n1 ~= nil and n2 ~= nil then draw:Line(n1.cent[1], n1.cent[2], n2.cent[1], n2.cent[2], colour.r, colour.g, colour.b, colour.a) end end end end --OK, we have our savedata and a profile. Instatiate everything and start the game! function DoInitGame(playercharacter, savedata, profile, next_world_playerdata, fast) local was_file_load = Settings.playeranim == "file_load" --print("DoInitGame",playercharacter, savedata, profile, next_world_playerdata, fast) TheFrontEnd:ClearScreens() assert(savedata.map, "Map missing from savedata on load") assert(savedata.map.prefab, "Map prefab missing from savedata on load") assert(savedata.map.tiles, "Map tiles missing from savedata on load") assert(savedata.map.width, "Map width missing from savedata on load") assert(savedata.map.height, "Map height missing from savedata on load") assert(savedata.map.topology, "Map topology missing from savedata on load") assert(savedata.map.topology.ids, "Topology entity ids are missing from savedata on load") --assert(savedata.map.topology.story_depths, "Topology story_depths are missing from savedata on load") assert(savedata.map.topology.colours, "Topology colours are missing from savedata on load") assert(savedata.map.topology.edges, "Topology edges are missing from savedata on load") assert(savedata.map.topology.nodes, "Topology nodes are missing from savedata on load") assert(savedata.map.topology.level_type, "Topology level type is missing from savedata on load") assert(savedata.map.topology.overrides, "Topology overrides is missing from savedata on load") assert(savedata.playerinfo, "Playerinfo missing from savedata on load") assert(savedata.playerinfo.x, "Playerinfo.x missing from savedata on load") --assert(savedata.playerinfo.y, "Playerinfo.y missing from savedata on load") --y is often omitted for space, don't check for it assert(savedata.playerinfo.z, "Playerinfo.z missing from savedata on load") --assert(savedata.playerinfo.day, "Playerinfo day missing from savedata on load") assert(savedata.ents, "Entites missing from savedata on load") if savedata.map.roads then Roads = savedata.map.roads for k, road_data in pairs( savedata.map.roads ) do RoadManager:BeginRoad() local weight = road_data[1] if weight == 3 then for i = 2, #road_data do local ctrl_pt = road_data[i] RoadManager:AddControlPoint( ctrl_pt[1], ctrl_pt[2] ) end for k, v in pairs( ROAD_STRIPS ) do RoadManager:SetStripEffect( v, "shaders/road.ksh" ) end RoadManager:SetStripTextures( ROAD_STRIPS.EDGES, resolvefilepath("images/roadedge.tex"), resolvefilepath("images/roadnoise.tex") , resolvefilepath("images/roadnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.CENTER, resolvefilepath("images/square.tex"), resolvefilepath("images/roadnoise.tex") , resolvefilepath("images/roadnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.CORNERS, resolvefilepath("images/roadcorner.tex"), resolvefilepath("images/roadnoise.tex") , resolvefilepath("images/roadnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.ENDS, resolvefilepath("images/roadendcap.tex"), resolvefilepath("images/roadnoise.tex") , resolvefilepath("images/roadnoise.tex") ) RoadManager:GenerateVB( ROAD_PARAMETERS.NUM_SUBDIVISIONS_PER_SEGMENT, ROAD_PARAMETERS.MIN_WIDTH, ROAD_PARAMETERS.MAX_WIDTH, ROAD_PARAMETERS.MIN_EDGE_WIDTH, ROAD_PARAMETERS.MAX_EDGE_WIDTH, ROAD_PARAMETERS.WIDTH_JITTER_SCALE, true ) else for i = 2, #road_data do local ctrl_pt = road_data[i] RoadManager:AddControlPoint( ctrl_pt[1], ctrl_pt[2] ) end for k, v in pairs( ROAD_STRIPS ) do RoadManager:SetStripEffect( v, "shaders/road.ksh" ) end RoadManager:SetStripTextures( ROAD_STRIPS.EDGES, resolvefilepath("images/roadedge.tex"), resolvefilepath("images/pathnoise.tex") , resolvefilepath("images/mini_pathnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.CENTER, resolvefilepath("images/square.tex"), resolvefilepath("images/pathnoise.tex") , resolvefilepath("images/mini_pathnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.CORNERS, resolvefilepath("images/roadcorner.tex"), resolvefilepath("images/pathnoise.tex") , resolvefilepath("images/mini_pathnoise.tex") ) RoadManager:SetStripTextures( ROAD_STRIPS.ENDS, resolvefilepath("images/roadendcap.tex"), resolvefilepath("images/pathnoise.tex"), resolvefilepath("images/mini_pathnoise.tex") ) RoadManager:GenerateVB( ROAD_PARAMETERS.NUM_SUBDIVISIONS_PER_SEGMENT, 0, 0, ROAD_PARAMETERS.MIN_EDGE_WIDTH*4, ROAD_PARAMETERS.MAX_EDGE_WIDTH*4, 0, false ) end end RoadManager:GenerateQuadTree() end SubmitStartStats(playercharacter) --some lame explicit loads Print(VERBOSITY.DEBUG, "DoInitGame Loading prefabs...") Print(VERBOSITY.DEBUG, "DoInitGame Adjusting audio...") TheMixer:SetLevel("master", 0) --apply the volumes Print(VERBOSITY.DEBUG, "DoInitGame Populating world...") local wilson = PopulateWorld(savedata, profile, playercharacter, next_world_playerdata) if wilson then TheCamera:SetTarget(wilson) StartGame(wilson) TheCamera:SetDefault() TheCamera:Snap() local seasonmgr = GetSeasonManager() if seasonmgr and not seasonmgr.initialevent then seasonmgr.inst:PushEvent( "seasonChange", {season = seasonmgr.current_season} ) seasonmgr.initialevent = true end else Print(VERBOSITY.WARNING, "DoInitGame NO WILSON?") end if Profile.persistdata.debug_world == 1 then if savedata.map.topology == nil then Print(VERBOSITY.ERROR, "OI! Where is my topology info!") else DrawDebugGraph(savedata.map.topology) end end local function OnStart() Print(VERBOSITY.DEBUG, "DoInitGame OnStart Callback... turning volume up") SetPause(false) end if not TheFrontEnd:IsDisplayingError() then local hud = PlayerHud() TheFrontEnd:PushScreen(hud) hud:SetMainCharacter(wilson) if wilson.HUDPostInit then wilson.HUDPostInit(hud) end --clear the player stats, so that it doesn't count items "acquired" from the save file GetProfileStats(true) RecordSessionStartStats() --after starting everything up, give the mods additional environment variables ModManager:SimPostInit(wilson) GetPlayer().components.health:RecalculatePenalty() GetPlayer().components.sanity:RecalculatePenalty() if ( SaveGameIndex:GetCurrentMode() ~= "cave" and (SaveGameIndex:GetCurrentMode() == "survival" or SaveGameIndex:GetSlotWorld() == 1) and SaveGameIndex:GetSlotDay() == 1 and GetClock():GetNormTime() == 0) then if GetPlayer().components.inventory.starting_inventory then for k,v in pairs(GetPlayer().components.inventory.starting_inventory) do local item = SpawnPrefab(v) if item then GetPlayer().components.inventory:GiveItem(item) end end end end if fast then OnStart() else SetPause(true,"InitGame") if Settings.playeranim == "file_load" then print ("DoInitGame file_load!") TheFrontEnd:SetFadeLevel(1) GetPlayer():PushEvent("death", {cause="file_load"}) elseif Settings.playeranim == "failadventure" then GetPlayer().sg:GoToState("failadventure") GetPlayer().HUD:Show() elseif GetWorld():IsCave() then GetPlayer().sg:GoToState("caveenter") GetPlayer().HUD:Show() elseif Settings.playeranim == "wakeup" or playercharacter == "waxwell" or savedata.map.nomaxwell then if (GetClock().numcycles == 0 and GetClock():GetNormTime() == 0) then GetPlayer().sg:GoToState("wakeup") end GetPlayer().HUD:Show() --announce your freedom if you are starting as waxwell if playercharacter == "waxwell" and SaveGameIndex:GetCurrentMode() == "survival" and (GetClock().numcycles == 0 and GetClock():GetNormTime() == 0) then GetPlayer():DoTaskInTime( 3.5, function() GetPlayer().components.talker:Say(GetString("waxwell", "ANNOUNCE_FREEDOM")) end) end elseif (GetClock().numcycles == 0 and GetClock():GetNormTime() == 0) or Settings.maxwell ~= nil then local max = SpawnPrefab("maxwellintro") local speechName = "NULL_SPEECH" if Settings.maxwell then speechName = Settings.maxwell elseif SaveGameIndex:GetCurrentMode() == "adventure" then if savedata.map.override_level_string == true then local level_id = 1 if GetWorld().meta then level_id = GetWorld().meta.level_id or level_id end speechName = "ADVENTURE_"..level_id else speechName = "ADVENTURE_"..SaveGameIndex:GetSlotWorld() end else speechName = "SANDBOX_1" end max.components.maxwelltalker:SetSpeech(speechName) max.components.maxwelltalker:Initialize() max.task = max:StartThread(function() max.components.maxwelltalker:DoTalk() end) --PlayNIS("maxwellintro", savedata.map.maxwell) end local title = STRINGS.UI.SANDBOXMENU.ADVENTURELEVELS[SaveGameIndex:GetSlotLevelIndexFromPlaylist()] local subtitle = STRINGS.UI.SANDBOXMENU.CHAPTERS[SaveGameIndex:GetSlotWorld()] local showtitle = SaveGameIndex:GetCurrentMode() == "adventure" and title if showtitle then TheFrontEnd:ShowTitle(title,subtitle) end TheFrontEnd:Fade(true, 1, function() SetPause(false) TheMixer:SetLevel("master", 1) TheMixer:PushMix("normal") TheFrontEnd:HideTitle() --TheFrontEnd:PushScreen(PopupDialogScreen(STRINGS.UI.HUD.READYTITLE, STRINGS.UI.HUD.READY, {{text=STRINGS.UI.HUD.START, cb = function() OnStart() end}})) end, showtitle and 3, showtitle and function() SetPause(false) end ) end if savedata.map.hideminimap ~= nil then GetWorld().minimap:DoTaskInTime(0, function(inst) inst.MiniMap:ClearRevealedAreas(savedata.map.hideminimap) end) end if savedata.map.teleportaction ~= nil then local teleportato = TheSim:FindFirstEntityWithTag("teleportato") if teleportato then local pickPosition = function() local portpositions = GetRandomInstWithTag("teleportlocation", teleportato, 1000) if portpositions then return Vector3(portpositions.Transform:GetWorldPosition()) else return Vector3(savedata.playerinfo.x, savedata.playerinfo.y or 0, savedata.playerinfo.z) end end teleportato.action = savedata.map.teleportaction teleportato.maxwell = savedata.map.teleportmaxwell teleportato.teleportpos = pickPosition() end end end --DoStartPause("Ready!") Print(VERBOSITY.DEBUG, "DoInitGame complete") if PRINT_TEXTURE_INFO then c_printtextureinfo( "texinfo.csv" ) TheSim:Quit() end if not was_file_load and GetPlayer().components.health:GetPercent() <= 0 then SetPause(false) GetPlayer():PushEvent("death", {cause="file_load"}) end inGamePlay = true if PLATFORM == "PS4" then if not TheSystemService:HasFocus() or not TheInputProxy:IsAnyInputDeviceConnected() then TheFrontEnd:PushScreen(PauseScreen()) end end end ------------------------THESE FUNCTIONS HANDLE STARTUP FLOW local function DoLoadWorld(saveslot, playerdataoverride) local function onload(savedata) assert(savedata, "DoLoadWorld: Savedata is NIL on load") assert(GetTableSize(savedata)>0, "DoLoadWorld: Savedata is empty on load") DoInitGame(SaveGameIndex:GetSlotCharacter(saveslot), savedata, Profile, playerdataoverride) end SaveGameIndex:GetSaveData(saveslot, SaveGameIndex:GetCurrentMode(saveslot), onload) end local function DoGenerateWorld(saveslot, type_override) local function onComplete(savedata ) assert(savedata, "DoGenerateWorld: Savedata is NIL on load") assert(#savedata>0, "DoGenerateWorld: Savedata is empty on load") local function onsaved() local success, world_table = RunInSandbox(savedata) if success then LoadAssets("BACKEND") DoInitGame(SaveGameIndex:GetSlotCharacter(saveslot), world_table, Profile, SaveGameIndex:GetPlayerData(saveslot)) end end if string.match(savedata, "^error") then local success,e = RunInSandbox(savedata) print("Worldgen had an error, displaying...") DisplayError(e) else SaveGameIndex:OnGenerateNewWorld(saveslot, savedata, onsaved) end end local world_gen_options = { level_type = type_override or SaveGameIndex:GetCurrentMode(saveslot), custom_options = SaveGameIndex:GetSlotGenOptions(saveslot,SaveGameIndex:GetCurrentMode()), level_world = SaveGameIndex:GetSlotLevelIndexFromPlaylist(saveslot), profiledata = Profile.persistdata, } if world_gen_options.level_type == "adventure" then world_gen_options["adventure_progress"] = SaveGameIndex:GetSlotWorld(saveslot) elseif world_gen_options.level_type == "cave" then world_gen_options["cave_progress"] = SaveGameIndex:GetCurrentCaveLevel() end TheFrontEnd:PushScreen(WorldGenScreen(Profile, onComplete, world_gen_options)) end local function LoadSlot(slot) TheFrontEnd:ClearScreens() if SaveGameIndex:HasWorld(slot, SaveGameIndex:GetCurrentMode(slot)) then --print("Load Slot: Has World") LoadAssets("BACKEND") DoLoadWorld(slot, SaveGameIndex:GetModeData(slot, SaveGameIndex:GetCurrentMode(slot)).playerdata) else --print("Load Slot: Has no World") if SaveGameIndex:GetCurrentMode(slot) == "survival" and SaveGameIndex:IsContinuePending(slot) then --print("Load Slot: ... but continue pending") local function onsave() DoGenerateWorld(slot) end local function onSet(character) TheFrontEnd:PopScreen() SaveGameIndex:SetSlotCharacter(slot, character, onsave) end LoadAssets("FRONTEND") TheFrontEnd:PushScreen(CharacterSelectScreen(Profile, onSet, true, SaveGameIndex:GetSlotCharacter(slot))) else --print("Load Slot: ... generating new world") DoGenerateWorld(slot) end end end ----------------LOAD THE PROFILE AND THE SAVE INDEX, AND START THE FRONTEND local function DoResetAction() if LOAD_UPFRONT_MODE then print ("load recipes") RECIPE_PREFABS = {} for k,v in pairs(Recipes) do table.insert(RECIPE_PREFABS, v.name) if v.placer then table.insert(RECIPE_PREFABS, v.placer) end end TheSim:LoadPrefabs(RECIPE_PREFABS) print ("load backend") TheSim:LoadPrefabs(BACKEND_PREFABS) print ("load frontend") TheSim:LoadPrefabs(FRONTEND_PREFABS) print ("load characters") local chars = GetActiveCharacterList() TheSim:LoadPrefabs(chars) end if Settings.reset_action then if Settings.reset_action == RESET_ACTION.DO_DEMO then SaveGameIndex:DeleteSlot(1, function() SaveGameIndex:StartSurvivalMode(1, "wilson", {}, function() --print("Reset Action: DO_DEMO") DoGenerateWorld(1) end) end) elseif Settings.reset_action == RESET_ACTION.LOAD_SLOT then if not SaveGameIndex:GetCurrentMode(Settings.save_slot) then --print("Reset Action: LOAD_SLOT -- not current save") LoadAssets("FRONTEND") TheFrontEnd:ShowScreen(MainScreen(Profile)) else --print("Reset Action: LOAD_SLOT -- current save") LoadSlot(Settings.save_slot) end elseif Settings.reset_action == "printtextureinfo" then --print("Reset Action: printtextureinfo") DoGenerateWorld(1) else --print("Reset Action: none") LoadAssets("FRONTEND") TheFrontEnd:ShowScreen(MainScreen(Profile)) end else if PRINT_TEXTURE_INFO then SaveGameIndex:DeleteSlot(1, function() local function onsaved() SimReset({reset_action="printtextureinfo",save_slot=1}) end SaveGameIndex:StartSurvivalMode(1, "wilson", {}, onsaved) end) else LoadAssets("FRONTEND") TheFrontEnd:ShowScreen(MainScreen(Profile)) end end end local function OnUpdatePurchaseStateComplete() print("OnUpdatePurchaseStateComplete") --print( "[Settings]",Settings.character, Settings.savefile) if TheInput:ControllerAttached() then TheFrontEnd:StopTrackingMouse() end DoResetAction() end local function OnFilesLoaded() print("OnFilesLoaded()") UpdateGamePurchasedState(OnUpdatePurchaseStateComplete) end STATS_ENABLE = METRICS_ENABLED Profile = PlayerProfile() SaveGameIndex = SaveIndex() Morgue = PlayerDeaths() Print(VERBOSITY.DEBUG, "[Loading Morgue]") Morgue:Load( function(did_it_load) --print("Morgue loaded....[",did_it_load,"]") end ) Print(VERBOSITY.DEBUG, "[Loading profile and save index]") Profile:Load( function() SaveGameIndex:Load( OnFilesLoaded ) end ) --dont_load_save in profile
-- Bob's Functions Library mod seablock.overwrite_setting('bool-setting', 'bobmods-library-technology-cleanup', false) seablock.overwrite_setting('bool-setting', 'bobmods-library-recipe-cleanup', true)
require('prototypes/picker') require('prototypes/renamer') require('prototypes/zapper') require('prototypes/tools')
--[[ Process sequence with command-line arguments. ]] return function(self, args) local options = self:parse_args(args) --[[ <options> is map of records {type: <>, value: <>}. <result> should be map of values. ]] local result = {} for key, rec in pairs(options) do result[key] = rec.value end return result end
AddCSLuaFile(); SWEP.Base = "weapon_coi_grenade"; SWEP.PrintName = "Trick Bag"; SWEP.HoldType = "grenade"; SWEP.ViewModel = "models/weapons/c_grenade.mdl"; SWEP.WorldModel = ""; SWEP.UseHands = false; SWEP.NoDraw = true; SWEP.Primary.Ammo = "trickbag"; SWEP.Primary.ClipSize = 1; SWEP.Primary.DefaultClip = 1; SWEP.Primary.Automatic = false; function SWEP:PrimaryAttack() self:SetNextPrimaryFire( math.huge ); self:SetNextSecondaryFire( math.huge ); self.Owner:SetAnimation( PLAYER_ATTACK1 ); self.RemoveTime = CurTime() + 0.1; end function SWEP:Throw() local fwd = self.Owner:GetForward(); fwd.z = fwd.z + 0.1; local p = self.Owner:EyePos() + fwd * 18 + self.Owner:GetRight() * 8; local gpos = self:GrenadeCheckThrow( p ); local ent = ents.Create( "coi_trickbag" ); ent:SetPos( gpos ); ent:SetAngles( Angle() ); ent:SetPlayer( self.Owner ); ent:Spawn(); ent:Activate(); self.Owner:EmitSound( Sound( "coi/coin.wav" ), 100, math.random( 80, 120 ) ); end
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- This submodule allows you to create observers for accessibility elements and be notified when they trigger notifications. Not all notifications are supported by all elements and not all elements support notifications, so some trial and error will be necessary, but for compliant applications, this can allow your code to be notified when an application's user interface changes in some way. ---@class hs.axuielement.observer local M = {} hs.axuielement.observer = M -- Registers the specified notification for the specified accesibility element with the observer. -- -- Parameters: -- * `element` - the `hs.axuielement` representing an accessibility element of the application the observer was created for. -- * `notification` - a string specifying the notification. -- -- Returns: -- * the observerObject; generates an error if watcher cannot be registered -- -- Notes: -- * multiple notifications for the same accessibility element can be registered by invoking this method multiple times with the same element but different notification strings. -- * if the specified element and notification string are already registered, this method does nothing. -- * the notification string is application dependent and can be any string that the application developers choose; some common ones are found in `hs.axuielement.observer.notifications`, but the list is not exhaustive nor is an application or element required to provide them. function M:addWatcher(element, notification, ...) end -- Get or set the callback for the observer. -- -- Parameters: -- * `fn` - a function, or an explicit nil to remove, specifying the callback function the observer will invoke when the assigned elements generate notifications. -- -- Returns: -- * If an argument is provided, the observerObject; otherwise the current value. -- -- Notes: -- * the callback should expect 4 arguments and return none. The arguments passed to the callback will be as follows: -- * the observerObject itself -- * the `hs.axuielement` object for the accessibility element which generated the notification -- * a string specifying the specific notification which was received -- * a table containing key-value pairs with more information about the notification, if the element and notification type provide it. Commonly this will be an empty table indicating that no additional detail was provided. function M:callback(fn) end -- Returns true or false indicating whether the observer is currently watching for notifications and generating callbacks. -- -- Parameters: -- * None -- -- Returns: -- * a boolean value indicating whether or not the observer is currently active. ---@return boolean function M:isRunning() end -- Creates a new observer object for the application with the specified process ID. -- -- Parameters: -- * `pid` - the process ID of the application. -- -- Returns: -- * a new observerObject; generates an error if the pid does not exist or if the object cannot be created. -- -- Notes: -- * If you already have the `hs.application` object for an application, you can get its process ID with `hs.application:pid()` -- * If you already have an `hs.axuielement` from the application you wish to observe (it doesn't have to be the application axuielement object, just one belonging to the application), you can get the process ID with `hs.axuielement:pid()`. function M.new(pid, ...) end -- A table of common accessibility object notification names, provided for reference. -- -- Notes: -- * Notifications are application dependent and can be any string that the application developers choose; this list provides the suggested notification names found within the macOS Framework headers, but the list is not exhaustive nor is an application or element required to provide them. ---@type table M.notifications = {} -- Unregisters the specified notification for the specified accessibility element from the observer. -- -- Parameters: -- * `element` - the `hs.axuielement` representing an accessibility element of the application the observer was created for. -- * `notification` - a string specifying the notification. -- -- Returns: -- * the observerObject; generates an error if watcher cannot be unregistered -- -- Notes: -- * if the specified element and notification string are not currently registered with the observer, this method does nothing. function M:removeWatcher(element, notification, ...) end -- Start observing the application and trigger callbacks for the elements and notifications assigned. -- -- Parameters: -- * None -- -- Returns: -- * the observerObject -- -- Notes: -- * This method does nothing if the observer is already running function M:start() end -- Stop observing the application; no further callbacks will be generated. -- -- Parameters: -- * None -- -- Returns: -- * the observerObject -- -- Notes: -- * This method does nothing if the observer is not currently running function M:stop() end -- Returns a table of the notifications currently registered with the observer. -- -- Parameters: -- * `element` - an optional `hs.axuielement` to return a list of registered notifications for. -- -- Returns: -- * a table containing the currently registered notifications -- -- Notes: -- * If an element is specified, then the table returned will contain a list of strings specifying the specific notifications that the observer is watching that element for. -- * If no argument is specified, then the table will contain key-value pairs in which each key will be an `hs.axuielement` that is being observed and the corresponding value will be a table containing a list of strings specifying the specific notifications that the observer is watching for from from that element. function M:watching(element, ...) end
--- Make interpolation curves -- A good place to generate and test these out: http://cubic-bezier.com/ -- Based upon https://gist.github.com/gre/1926947#file-keyspline-js -- @module BezierFactory local lib = {} function lib.BezierFactory(P1x, P1y, P2x, P2y) -- Same as CSS transition thing. assert(P1x, "[BezierFactory] - Need P1x to construct a Bezier Factory") assert(P1y, "[BezierFactory] - Need P1y to construct a Bezier Factory") assert(P2x, "[BezierFactory] - Need P2x to construct a Bezier Factory") assert(P2y, "[BezierFactory] - Need P2y to construct a Bezier Factory") local function A(aA1, aA2) return 1.0 - 3.0 * aA2 + 3.0 * aA1 end local function B(aA1, aA2) return 3.0 * aA2 - 6.0 * aA1 end local function C(aA1) return 3.0 * aA1 end -- Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. local function CalculateBezier(aT, aA1, aA2) return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT end -- Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. local function GetSlope(aT, aA1, aA2) return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1) end -- Newton raphson iteration local function GetTForX(aX) local aGuessT = aX for _ = 1, 4 do local CurrentSlope = GetSlope(aGuessT, P1x, P2x) if CurrentSlope == 0 then return aGuessT end local CurrentX = CalculateBezier(aGuessT, P1x, P2x) - aX aGuessT = aGuessT - CurrentX / CurrentSlope end return aGuessT end return function(aX) -- aX is from [0, 1], it's the original time return CalculateBezier(GetTForX(aX), P1y, P2y) end end --[[ @usage local Ease = BezierFactory(0.25, 0.1, 0.25, 1) for Index = 0, 1.05, 0.05 do print(Index, ":", Ease(Index)) end --]] return lib
---- -- @file Sound ---- Brief description. -- <#Description#> -- @return <#return value description#> function Sound:calculateSerializeBufferSize() end ---- Brief description. -- <#Description#> -- @param dataBuffer <#dataBuffer description#> -- @param serializer <#serializer description#> -- @return <#return value description#> function Sound:serialize(dataBuffer, serializer) end ---- Brief description. -- <#Description#> -- @return <#return value description#> function Sound:getClassName() end ---- Brief description. -- <#Description#> -- @return <#return value description#> function Sound:getType() end ---- Brief description. -- @return <#return value description#> function Sound:getTimePosition() end ---- Brief description. -- @return <#return value description#> function Sound:setTimePosition() end ---- Brief description. -- @return <#return value description#> function Sound:getTimeLength() end ---- Brief description. -- @return <#return value description#> function Sound:isPlaying() end ---- Brief description. -- @return <#return value description#> function Sound:play() end ---- Brief description. -- @return <#return value description#> function Sound:stop() end ---- Brief description. -- @return <#return value description#> function Sound:isPaused() end ---- Brief description. -- @return <#return value description#> function Sound:pause() end ---- Brief description. -- @return <#return value description#> function Sound:unPause() end ---- Brief description. -- @return <#return value description#> function Sound:isMuted() end ---- Brief description. -- @return <#return value description#> function Sound:mute() end ---- Brief description. -- @return <#return value description#> function Sound:unMute() end ---- Brief description. -- @return <#return value description#> function Sound:getVolume() end ---- Brief description. -- @return <#return value description#> function Sound:setVolume() end ---- Brief description. -- @return <#return value description#> function Sound:getLoopCount() end ---- Brief description. -- @return <#return value description#> function Sound:setLoopCount() end ---- Brief description. -- A world transform is the node’s coordinate space transformation relative to the scene’s coordinate space. This transformation is the concatenation of the node’s transform property with that of its parent node, the parent’s parent, and so on up to the rootNode object of the scene. -- @return The function Sound:getWorldTransform() end ---- Brief description. -- @return The function NJLI.Sound.createArray() end ---- Brief description. -- @return The function NJLI.Sound.destroyArray() end ---- Brief description. -- @return The function NJLI.Sound.create() end ---- Brief description. -- @return The function NJLI.Sound.create() end ---- Brief description. -- @return The function NJLI.Sound.clone() end ---- Brief description. -- @return The function NJLI.Sound.copy() end ---- Brief description. -- @return The function NJLI.Sound.destroy() end ---- Brief description. -- @return The function NJLI.Sound.load() end ---- Brief description. -- @return The function NJLI.Sound.type() end
--[[ Disrupt Pirate Attack NOTES: - First, easy mission for LOTW ADDITIONAL REQUIREMENTS TO DO THIS MISSION: - Take it off the mission board. It should be persistent like the black market mission. ROUGH OUTLINE - Go to a sector. - Pirates are there. - Kill them all. Very simple and straightforward. DANGER LEVEL 5 - Kill 3 waves of 4 pirates each. Use weenie ships and add 1 raider in the final wave. ]] package.path = package.path .. ";data/scripts/lib/?.lua" package.path = package.path .. ";data/scripts/?.lua" include("callable") include("structuredmission") ESCCUtil = include("esccutil") local AsyncPirateGenerator = include ("asyncpirategenerator") local AsyncShipGenerator = include("asyncshipgenerator") local Balancing = include ("galaxy") local SpawnUtility = include ("spawnutility") mission._Debug = 0 mission._Name = "Disrupt Pirate Attack" --region #INIT --Standard mission data. mission.data.brief = mission._Name mission.data.title = mission._Name mission.data.icon = "data/textures/icons/silicium.png" mission.data.description = { { text = "You recieved the following request from the ${sectorName} ${giverTitle}:" }, --Placeholder { text = "..." }, --Placeholder { text = "Head to sector (${location.x}:${location.y})", bulletPoint = true, fulfilled = false }, { text = "Destroy the first wave of pirates.", bulletPoint = true, fulfilled = false, visible = false }, { text = "Destroy the second wave of pirates.", bulletPoint = true, fulfilled = false, visible = false }, { text = "Destroy the third wave of pirates.", bulletPoint = true, fulfilled = false, visible = false }, { text = "Meet the liason in sector (${location.x}:${location.y})", bulletPoint = true, fulfilled = false, visible = false } } --Can't set mission.data.reward.paymentMessage here since we are using a custom init. mission.data.accomplishMessage = "Good work. We transferred the reward to your account. Be on the lookout for more opportunities in the future." local LOTW_Mission_init = initialize function initialize(_Data_in) local _MethodName = "initialize" mission.Log(_MethodName, "Beginning...") if onServer()then if not _restoring then mission.Log(_MethodName, "Calling on server - dangerLevel : " .. tostring(_Data_in.dangerLevel) .. " - pirates : " .. tostring(_Data_in.pirates) .. " - enemy : " .. tostring(_Data_in.enemyFaction)) local _Rgen = ESCCUtil.getRand() local _X, _Y = _Data_in.location.x, _Data_in.location.y local _Sector = Sector() local _Giver = Entity(_Data_in.giver) --[[===================================================== CUSTOM MISSION DATA: .dangerLevel .pirateLevel .friendlyFaction .enemyFaction .firstWaveTaunt .waveCounter .firstTimerAdvance .secondTimerAdvance .thirdTimerAdvance =========================================================]] mission.data.custom.dangerLevel = _Data_in.dangerLevel mission.data.custom.pirateLevel = Balancing_GetPirateLevel(_X, _Y) local _EnemyFaction = Galaxy():getPirateFaction(mission.data.custom.pirateLevel) mission.data.custom.enemyFaction = _EnemyFaction.index mission.Log(_MethodName, "Enemy faction is : " .. tostring(_EnemyFaction.name)) mission.data.custom.friendlyFaction = _Giver.factionIndex mission.data.description[1].arguments = { sectorName = _Sector.name, giverTitle = _Giver.translatedTitle } mission.data.description[2].text = _Data_in.description mission.data.description[2].arguments = {x = _X, y = _Y, enemyName = mission.data.custom.enemyName } _Data_in.reward.paymentMessage = "Earned %1% credits for destroying the pirate fleet." --Run standard initialization LOTW_Mission_init(_Data_in) else --Restoring LOTW_Mission_init() end end if onClient() then if not _restoring then initialSync() else sync() end end end --endregion --region #PHASE CALLS mission.phases[1] = {} mission.phases[1].timers = {} --region #PHASE 1 TIMERS if onServer() then mission.phases[1].timers[1] = { time = 10, callback = function() local _MethodName = "Phase 1 Timer 1 Callback" local _Sector = Sector() local _X, _Y = _Sector:getCoordinates() local _Pirates = {_Sector:getEntitiesByScriptValue("is_pirate")} mission.Log(_MethodName, "Number of pirates : " .. tostring(#_Pirates) .. " timer allowed to advance : " .. tostring(mission.data.custom.firstTimerAdvance)) if _X == mission.data.location.x and _Y == mission.data.location.y and mission.data.custom.firstTimerAdvance and #_Pirates == 0 then nextPhase() end end, repeating = true} end --endregion mission.phases[1].noBossEncountersTargetSector = true --Probably going to happen anyways due to the distance from the core, but no sense in taking chances. mission.phases[1].noPlayerEventsTargetSector = true mission.phases[1].noLocalPlayerEventsTargetSector = true mission.phases[1].onTargetLocationEntered = function(x, y) local _MethodName = "Phase 1 On Target Location Entered" mission.Log(_MethodName, "Beginning...") mission.data.description[3].fulfilled = true mission.data.description[4].visible = true spawnPirateWave(false, 1) end mission.phases[1].onSectorArrivalConfirmed = function(x, y) pirateTaunt() end mission.phases[2] = {} mission.phases[2].timers = {} --region #PHASE 2 TIMERS if onServer() then mission.phases[2].timers[1] = { time = 10, callback = function() local _MethodName = "Phase 2 Timer 1 Callback" local _Sector = Sector() local _X, _Y = _Sector:getCoordinates() local _Pirates = {_Sector:getEntitiesByScriptValue("is_pirate")} mission.Log(_MethodName, "Number of pirates : " .. tostring(#_Pirates) .. " timer allowed to advance : " .. tostring(mission.data.custom.secondTimerAdvance)) if _X == mission.data.location.x and _Y == mission.data.location.y and mission.data.custom.secondTimerAdvance and #_Pirates == 0 then nextPhase() end end, repeating = true} end --endregion mission.phases[2].noBossEncountersTargetSector = true mission.phases[2].noPlayerEventsTargetSector = true mission.phases[2].noLocalPlayerEventsTargetSector = true mission.phases[2].onBeginServer = function() local _MethodName = "Phase 2 On Begin Server" mission.Log(_MethodName, "Beginning...") mission.data.description[4].fulfilled = true mission.data.description[5].visible = true spawnPirateWave(false, 2) end mission.phases[3] = {} mission.phases[3].timers = {} --region #PHASE 3 TIMERS if onServer() then mission.phases[3].timers[1] = { time = 10, callback = function() local _MethodName = "Phase 3 Timer 1 Callback" local _Sector = Sector() local _X, _Y = _Sector:getCoordinates() local _Pirates = {_Sector:getEntitiesByScriptValue("is_pirate")} mission.Log(_MethodName, "Number of pirates : " .. tostring(#_Pirates) .. " timer allowed to advance : " .. tostring(mission.data.custom.thirdTimerAdvance)) if _X == mission.data.location.x and _Y == mission.data.location.y and mission.data.custom.thirdTimerAdvance and #_Pirates == 0 then nextPhase() end end, repeating = true} end --endregion mission.phases[3].noBossEncountersTargetSector = true mission.phases[3].noPlayerEventsTargetSector = true mission.phases[3].noLocalPlayerEventsTargetSector = true mission.phases[3].showUpdateOnEnd = true mission.phases[3].onBeginServer = function() local _MethodName = "Phase 3 On Begin Server" mission.Log(_MethodName, "Beginning...") mission.data.description[5].fulfilled = true mission.data.description[6].visible = true spawnPirateWave(true, 3) end mission.phases[4] = {} mission.phases[4].noBossEncountersTargetSector = true mission.phases[4].noPlayerEventsTargetSector = true mission.phases[4].noLocalPlayerEventsTargetSector = true mission.phases[4].onBeginServer = function() local _MethodName = "Phase 4 On Begin Server" mission.Log(_MethodName, "Beginning...") mission.data.description[6].fulfilled = true mission.data.location = getNextLocation() mission.data.description[7].arguments = { x = mission.data.location.x, y = mission.data.location.y } mission.data.description[7].visible = true local _Faction = Faction(mission.data.custom.friendlyFaction) Player():sendChatMessage(_Faction.name, 0, "We have a liason waiting for you in sector \\s(%1%:%2%). Please contact them there.", mission.data.location.x, mission.data.location.y) end mission.phases[4].onTargetLocationEntered = function(x, y) --Spawn liason spawnLiason() end --endregion --region #SERVER CALLS function spawnPirateWave(_LastWave, _WaveNumber) local _MethodName = "Spawn Pirate Wave" mission.Log(_MethodName, "Beginning...") local rgen = ESCCUtil.getRand() local waveTable = { "Bandit", "Bandit" } if _LastWave then --Add a pirate/marauder and a raider. if rgen:getInt(1, 2) == 1 then table.insert(waveTable, "Pirate") else table.insert(waveTable, "Marauder") end table.insert(waveTable, "Raider") else --Add a combination of pirates and maurauders. if rgen:getInt(1, 2) == 1 then table.insert(waveTable, "Pirate") if rgen:getInt(1, 2) == 1 then table.insert(waveTable, "Marauder") else table.insert(waveTable, "Pirate") end else table.insert(waveTable, "Marauder") table.insert(waveTable, "Pirate") end end mission.data.custom.waveCounter = _WaveNumber local generator = AsyncPirateGenerator(nil, onPiratesFinished) generator:startBatch() local posCounter = 1 local distance = 100 local pirate_positions = generator:getStandardPositions(#waveTable, distance) for _, p in pairs(waveTable) do generator:createScaledPirateByName(p, pirate_positions[posCounter]) posCounter = posCounter + 1 end generator:endBatch() end function onPiratesFinished(_Generated) local _MethodName = "On Pirates Generated (Server)" local _WaveNumber = mission.data.custom.waveCounter mission.Log(_MethodName, "Beginning. Wave number is : " .. tostring(_WaveNumber)) if _WaveNumber == 1 then mission.data.custom.firstTimerAdvance = true end if _WaveNumber == 2 then mission.data.custom.secondTimerAdvance = true end if _WaveNumber == 3 then mission.data.custom.thirdTimerAdvance = true end SpawnUtility.addEnemyBuffs(_Generated) end function pirateTaunt() local _MethodName = "Pirate Taunt" mission.Log(_MethodName, "Beginning...") local _Pirates = {Sector():getEntitiesByScriptValue("is_pirate")} if not mission.data.custom.firstWaveTaunt and #_Pirates > 0 then mission.Log(_MethodName, "Broadcasting Pirate Taunt to Sector") mission.Log(_MethodName, "Entity: " .. tostring(_Pirates[1].id)) local _Lines = { "... Who are you? How dare you interrupt!", "Well, I guess you'll be the first one we kill.", "You're a long way from home, aren't you?", "... Who the hell are you?", "Looks like we found a stray one." } Sector():broadcastChatMessage(_Pirates[1], ChatMessageType.Chatter, randomEntry(_Lines)) mission.data.custom.firstWaveTaunt = true end end function spawnLiason() local _MethodName = "Spawn Relief Defenders" mission.Log(_MethodName, "Beginning...") --Spawn background corvettes. local shipGenerator = AsyncShipGenerator(nil, onFactionShipsFinished) local faction = Faction(mission.data.custom.friendlyFaction) if not faction or faction.isPlayer or faction.isAlliance then print("ERROR - COULD NOT FIND MISSION FACTION") terminate() return end shipGenerator:startBatch() shipGenerator:createDefender(faction, shipGenerator:getGenericPosition()) shipGenerator:createDefender(faction, shipGenerator:getGenericPosition()) shipGenerator:endBatch() local liasonGenerator = AsyncShipGenerator(nil, onLiasonShipFinished) liasonGenerator:startBatch() liasonGenerator:createDefender(faction, liasonGenerator:getGenericPosition()) liasonGenerator:endBatch() end function onLiasonShipFinished(_Generated) for _, _Ship in pairs(_Generated) do local _Faction = Faction(_Ship.factionIndex) local _ShipAI = ShipAI(_Ship) MissionUT.deleteOnPlayersLeft(_Ship) _Ship:removeScript("patrol.lua") _Ship:removeScript("antismuggle.lua") _Ship:addScriptOnce("player/missions/lotw/mission1/lotwliasonm1.lua") _ShipAI:setIdle() _Ship.title = tostring(_Faction.name) .. " Military Liason" end end function onFactionShipsFinished(_Generated) for _, _Ship in pairs(_Generated) do _Ship:removeScript("antismuggle.lua") --Need to get in the habit of doing this b/c the player may have stolen shit. MissionUT.deleteOnPlayersLeft(_Ship) end end function getNextLocation() local _MethodName = "Get Next Location" mission.Log(_MethodName, "Getting a location.") local x, y = Sector():getCoordinates() local target = {} target.x, target.y = MissionUT.getSector(x, y, 2, 6, false, false, false, false, false) mission.Log(_MethodName, "X coordinate of next location is : " .. tostring(target.x) .. " Y coordinate of next location is : " .. tostring(target.y)) if not target or not target.x or not target.y then mission.Log(_MethodName, "Could not find a suitable mission location. Terminating script.") terminate() return end return target end function finishAndReward() local _MethodName = "Finish and Reward" mission.Log(_MethodName, "Running win condition.") local _Player = Player() local _Faction = Faction(mission.data.custom.friendlyFaction) _Player:setValue("_lotw_story_1_accomplished", true) _Player:setValue("_lotw_faction", _Faction.index) reward() accomplish() end --endregion --region #CLIENT / SERVER CALLS function contactedLiason() local _MethodName = "Contacted Liason" if onClient() then mission.Log(_MethodName, "Calling on Client") mission.Log(_MethodName, "Invoking on server.") invokeServerFunction("contactedLiason") else mission.Log(_MethodName, "Calling on Server") finishAndReward() end end callable(nil, "contactedLiason") --endregion --region #MAKEBULLETIN CALL function formatDescription(_Station) local _Faction = Faction(_Station.factionIndex) local _Aggressive = _Faction:getTrait("aggressive") local _DescriptionType = 1 --Neutral if _Aggressive > 0.5 then _DescriptionType = 2 --Aggressive. elseif _Aggressive <= -0.5 then _DescriptionType = 3 --Peaceful. end local _FinalDescription = "" if _DescriptionType == 1 then --Neutral. _FinalDescription = "We're looking for a hot-shot captain to take care of some pirate raiders that are gathering in a nearby sector. From what intelligence we can gather, they're getting together to attack a nearby system and that's something we'd rather avoid for obvious reasons. Don't worry, you'll be well compensated for your efforts." elseif _DescriptionType == 2 then --Aggressive. _FinalDescription = "A group of raiders think that they've escaped our notice. They are wrong. We've found their pathetic fleet, and we're ready to wipe it off the face of this galaxy. However - in what you'll agree is a magnanimous display - we've decided to offer outsider captains a crack at it first. You'll be compensated for your time and for the ships destroyed. Make an example of them." elseif _DescriptionType == 3 then --Peaceful. _FinalDescription = "A group of pirate raiders are gathering nearby to launch an attack on one of our systems. We won't be able to shift enough defenses to the targeted system in time to meet the attack. So we're looking for some outside help to make up the difference. Please, many lives will be saved by your actions." end return _FinalDescription end mission.makeBulletin = function(_Station) local _MethodName = "Make Bulletin" mission.Log(_MethodName, "Making Bulletin.") --This mission happens in the same sector you accept it in. local _Sector = Sector() local target = {} --GET TARGET HERE: local x, y = _Sector:getCoordinates() local insideBarrier = MissionUT.checkSectorInsideBarrier(x, y) target.x, target.y = MissionUT.getSector(x, y, 4, 10, false, false, false, false, insideBarrier) if not target.x or not target.y then mission.Log(_MethodName, "Target.x or Target.y not set - returning nil.") return end local _DangerLevel = 5 local _Description = formatDescription(_Station) reward = ESCCUtil.clampToNearest(125000 + (50000 * Balancing.GetSectorRichnessFactor(_Sector:getCoordinates())), 5000, "Up") --SET REWARD HERE local bulletin = { -- data for the bulletin board brief = mission.data.brief, title = mission.data.title, icon = mission.data.icon, description = _Description, difficulty = "Easy", reward = "¢${reward}", script = "missions/lotw/lotwmission1.lua", formatArguments = {x = target.x, y = target.y, reward = createMonetaryString(reward)}, msg = "The pirates are gathering in sector \\s(%1%:%2%). Please destroy them.", giverTitle = _Station.title, giverTitleArgs = _Station:getTitleArguments(), checkAccept = [[ local self, player = ... if player:hasScript("missions/lotw/lotwmission1.lua") or player:getValue("_lotw_story_1_accomplished") then player:sendChatMessage(Entity(self.arguments[1].giver), 1, "You cannot accept this mission again.") return 0 end return 1 ]], onAccept = [[ local self, player = ... player:sendChatMessage(Entity(self.arguments[1].giver), 0, self.msg, self.formatArguments.x, self.formatArguments.y) ]], -- data that's important for our own mission arguments = {{ giver = _Station.index, location = target, reward = {credits = reward, relations = 12000}, description = _Description, dangerLevel = _DangerLevel }}, } return bulletin end --endregion
BlacksmithingMaterials = { [808] = {level = "1 - 14"}, -- iron ore [5413] = {level = "1 - 14"}, -- iron ingot [5820] = {level = "16 - 24"}, -- high iron ore [4487] = {level = "16 - 24"}, -- steel ingot [23103] = {level = "26 - 34"}, -- orichalcum ore [23107] = {level = "26 - 34"}, -- orichalcum ingot [23104] = {level = "36 - 44"}, -- dwarven ore [6000] = {level = "36 - 44"}, -- dwarven ingot [23105] = {level = "46 - 50"}, -- ebony ore [6001] = {level = "46 - 50"}, -- ebony ingot [4482] = {level = "VR1 - VR3"}, -- calcinium ore [46127] = {level = "VR1 - VR3"}, -- calcinium ingot [23133] = {level = "VR4 - VR6"}, -- galatite ore [46128] = {level = "VR4 - VR6"}, -- galatite ingot [23134] = {level = "VR7 - VR8"}, -- quicksilver ore [46129] = {level = "VR7 - VR8"}, -- quicksilver ingot [23135] = {level = "VR9 - VR12"}, -- voidstone ore [46130] = {level = "VR9 - VR12"}, -- voidstone ingot }
local Combination = { -- Note: combinations are put in alphabetical order (ex AltCtrl not CtrlAlt) None = 0, Shift = 1, Ctrl = 2, CtrlShift = 3, Alt = 4, AltShift = 5, AltCtrl = 6, AltCtrlShift = 7, Meta = 8, -- Expand to have Meta combinations if needed } local function get(shift, ctrl, alt, meta) -- returns a key suitable for a table that represents the combination of shift/etc -- Roblox's ModifierKey has shift at 0, ctrl at 1, alt at 2, meta at 3 return (shift and 1 or 0) + (ctrl and 2 or 0) + (alt and 4 or 0) + (meta and 8 or 0) end Combination.Get = get function Combination.Contains(combination, modifierKey) return bit32.btest(combination, 2^modifierKey.Value) end local Shift = Enum.ModifierKey.Shift local Ctrl = Enum.ModifierKey.Ctrl local Alt = Enum.ModifierKey.Alt local Meta = Enum.ModifierKey.Meta function Combination.FromInput(input, ignoreShift) return get( not ignoreShift and input:IsModifierKeyDown(Shift), input:IsModifierKeyDown(Ctrl), input:IsModifierKeyDown(Alt), input:IsModifierKeyDown(Meta)) end return Combination
class "LazyUtility" Callback.Add("Load", function() LazyUtility:OnLoad() end) function LazyUtility:OnLoad() self.Nudes = { Sexy = "https://i.imgur.com/swMci7o.png", Rainbows = "https://i.imgur.com/oeDGue7.png", bilgewaterCutlass = "https://i.imgur.com/IREFNf6.png", Botrk = "https://i.imgur.com/tVOUUBN.png", ironSolari = "", edgeOfNight = "https://i.imgur.com/SgvqT35.png", faceOfTheMountain = "", frostQueensClaim = "https://i.imgur.com/TRFkMUw.png", hextechGLP = "https://i.imgur.com/U2jXNJB.png", hextechGunblade = "https://i.imgur.com/ekvQhjS.png", hextechProtobelt = "https://i.imgur.com/NreXohf.png", mercurialScimitar = "", mikaelsCrucible = "", ohmwrecker = "", ravenousHydra = "", redemption = "https://i.imgur.com/d5zD5FJ.png", tiamat = "", youmuusGhostblade = "", zhonyas = "https://i.imgur.com/QcqvC9F.png", titanicHydra = "", wayPoints = "https://i.imgur.com/IXT5RNn.png", minimap = "https://i.imgur.com/rLmHEPg.png", activator = "https://i.imgur.com/YVSSNsL.png" } self:LoadMenu() self:CreateHeroTable() self.RecallData = {} Callback.Add("Draw", function() self:OnDraw() end) Callback.Add("ProcessRecall", function(unit, proc) self:OnRecall(unit, proc) end) Callback.Add("Tick", function() self:OnTick() end) end function LazyUtility:LoadMenu() self.Menu = Menu({id = "MainMenu", name = "Lazy Utility", type = MENU, leftIcon = self.Nudes.Sexy }) self.Menu:Menu({ id = "mMtracker", name = "Minimap Tracker", type = MENU, leftIcon = self.Nudes.minimap }) self.Menu.mMtracker:MenuElement({ id = "show", name = "MiniMap tracker", value = true, tooltip = "tracks last seen position on MiniMap" }) --Activator self.Menu:MenuElement({ id = "Activator", name = "Activator", type = MENU, leftIcon = self.Nudes.activator }) --bilgewaterCutlass self.Menu.Activator:MenuElement({ id = "bilgewaterCutlass", name = "Bilgewater Cutlass", type = MENU, leftIcon = self.Nudes.bilgewaterCutlass}) self.Menu.Activator.bilgewaterCutlass:MenuElement({ id = "useBilgewaterCutlass", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.bilgewaterCutlass:MenuElement({ id = "bilgewaterCutlassTHP", name = "Enemy HP %", value = 40, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.bilgewaterCutlass:MenuElement({ id = "bilgewaterCutlassHP", name = "my Hero HP %", value = 40, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.bilgewaterCutlass:MenuElement({ id = "bilgewaterCutlassRange", name = "Range", value = 550, min = 0, max = 550 , step = 10, tooltip = "Target in x Range" }) --botrk self.Menu.Activator:MenuElement({ id = "botrk", name = "BotRK", type = MENU , leftIcon = self.Nudes.Botrk}) self.Menu.Activator.botrk:MenuElement({ id = "useBotrk", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.botrk:MenuElement({ id = "botrkTHP", name = "Enemy HP %", value = 40, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.botrk:MenuElement({ id = "botrkHP", name = "my Hero HP %", value = 40, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.botrk:MenuElement({ id = "botrkRange", name = "Range", value = 550, min = 0, max = 550, step = 10, tooltip = "Target in x Range" }) --edgeOfNight self.Menu.Activator:MenuElement({ id = "edgeOfNight", name = "Edge Of Night", type = MENU, leftIcon = self.Nudes.edgeOfNight }) self.Menu.Activator.edgeOfNight:MenuElement({ id = "useEdgeOfNight", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.edgeOfNight:MenuElement({ id = "edgeOfNightRange", name = "Range", value = 2000, min = 0, max = 2000, step = 100, tooltip = "Target in x Range" }) --frostQueensClaim self.Menu.Activator:MenuElement({ id = "frostQueensClaim", name = "Frost Queens Claim", type = MENU, leftIcon = self.Nudes.frostQueensClaim }) self.Menu.Activator.frostQueensClaim:MenuElement({ id = "useFrostQueensClaim", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.frostQueensClaim:MenuElement({ id = "frostQueensClaimTHP", name = "Enemy HP %", value = 75, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.frostQueensClaim:MenuElement({ id = "frostQueensClaimHP", name = "my Hero HP %", value = 101, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.frostQueensClaim:MenuElement({ id = "frostQueensClaimRange", name = "Range", value = 4000, min = 0, max = 4500, step = 100, tooltip = "Target in x Range" }) --hextechGLP self.Menu.Activator:MenuElement({ id = "hextechGLP", name = "Hextech GLP-800", type = MENU, leftIcon = self.Nudes.hextechGLP }) self.Menu.Activator.hextechGLP:MenuElement({ id = "useHextechGLP", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.hextechGLP:MenuElement({ id = "hextechGLPTHP", name = "Enemy HP %", value = 60, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.hextechGLP:MenuElement({ id = "hextechGLPHP", name = "my Hero HP %", value = 30, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.hextechGLP:MenuElement({ id = "hextechGLPRange", name = "Range", value = 400, min = 0, max = 400, step = 10, tooltip = "Target in x Range" }) --hextechGunblade self.Menu.Activator:MenuElement({ id = "hextechGunblade", name = "Hextech Gunblade", type = MENU, leftIcon = self.Nudes.hextechGunblade }) self.Menu.Activator.hextechGunblade:MenuElement({ id = "useHextechGunblade", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.hextechGunblade:MenuElement({ id = "hextechGunbladeTHP", name = "Enemy HP %", value = 35, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.hextechGunblade:MenuElement({ id = "hextechGunbladeHP", name = "my Hero HP %", value = 35, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.hextechGunblade:MenuElement({ id = "hextechGunbladeRange", name = "Range", value = 700, min = 0, max = 700, step = 10, tooltip = "Target in x Range" }) --hextechProtobelt self.Menu.Activator:MenuElement({ id = "hextechProtobelt", name = "Hextech Protobelt", type = MENU, leftIcon = self.Nudes.hextechProtobelt }) self.Menu.Activator.hextechProtobelt:MenuElement({ id = "useHextechProtobelt", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.hextechProtobelt:MenuElement({ id = "hextechProtobeltTHP", name = "Enemy HP %", value = 25, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.hextechProtobelt:MenuElement({ id = "hextechProtobeltRange", name = "Range", value = 500, min = 0, max = 600, step = 10, tooltip = "Target in x Range" }) --redemption self.Menu.Activator:MenuElement({ id = "redemption", name = "Redemption", type = MENU, leftIcon = self.Nudes.redemption }) self.Menu.Activator.redemption:MenuElement({ id = "useRedemption", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.redemption:MenuElement({ id = "redemptionTHP", name = "Enemy HP %", value = 11, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.redemption:MenuElement({ id = "redemptionHP", name = "my Hero HP %", value = 11, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.redemption:MenuElement({ id = "redemptionRange", name = "Range", value = 5500, min = 0, max = 5500, step = 10, tooltip = "Target in x Range" }) --zhonyas self.Menu.Activator:MenuElement({ id = "zhonyasHourglass", name = "Zhonyas Hourglass", type = MENU, leftIcon = self.Nudes.zhonyas }) self.Menu.Activator.zhonyasHourglass:MenuElement({ id = "useZhonyasHourglass", name = "Use", value = true, tooltip = "general ON/OFF switch" }) self.Menu.Activator.zhonyasHourglass:MenuElement({ id = "zhonyasHourglassTHP", name = "Enemy HP %", value = 101, min = 0, max = 101, step = 1, tooltip = "if Target HP% < x" }) self.Menu.Activator.zhonyasHourglass:MenuElement({ id = "zhonyasHourglassHP", name = "my Hero HP %", value = 10, min = 0, max = 101, step = 1, tooltip = "My HP% < x" }) self.Menu.Activator.zhonyasHourglass:MenuElement({ id = "zhonyasHourglassRange", name = "Range", value = 500, min = 0, max = 600, step = 10, tooltip = "Target in x Range" }) end function LazyUtility:OnTick() self:GetOrbMode() self:UseItems() end function LazyUtility:GetDistanceSqr(p1, p2) return (p1.x - p2.x) ^ 2 + ((p1.z or p1.y) - (p2.z or p2.y)) ^ 2 end function LazyUtility:GetDistance(p1, p2) return math.sqrt(self:GetDistanceSqr(p1, p2)) end function LazyUtility:GetHpPercent(unit) return unit.health / unit.maxHealth * 100 end function LazyUtility:GetManaPercent(unit) return unit.mana / unit.maxMana * 100 end function LazyUtility:GetPathLength(pArray) local length = 0 for i = 1, #pArray -1 do length = length + self:GetDistance(pArray[i], pArray[i + 1]) end return length end function LazyUtility:CalcETA(unit) local wayPoints = self:GetWayPoints(unit) local pathLength = self:GetPathLength(wayPoints) local moveSpeed = unit.ms local timer = pathLength / moveSpeed local rounded = tonumber(string.format("%.1f", timer)) return rounded end function LazyUtility:GetWayPoints(unit) local points = {} if unit.pathing.hasMovePath then table.insert(points, Vector(unit.pos.x, unit.pos.y, unit.pos.z)) for i = unit.pathing.pathIndex, unit.pathing.pathCount do path = unit:GetPath(i) table.insert(points, Vector(path.x, path.y, path.z)) end end return points end function LazyUtility:DrawWayPoints() for h = 1, Game.HeroCount() do local currentHero = Game.Hero(h) local heroPos2D = currentHero.pos:To2D() local wayPoints = self:GetWayPoints(currentHero) local ETA = self:CalcETA(currentHero) for i = 1, #wayPoints do if currentHero.pathing.hasMovePath then if currentHero.isAlly and self.Menu.wPtracker.showAllies:Value() then if self.Menu.wPtracker.eta:Value() then Draw.Text(ETA, 10, wayPoints[#wayPoints]:To2D().x + 10, wayPoints[#wayPoints]:To2D().y + 10, Draw.Color(self.Menu.wPtracker.allyColors.opacity:Value(), self.Menu.wPtracker.allyColors.red:Value(), self.Menu.wPtracker.allyColors.green:Value(), self.Menu.wPtracker.allyColors.blue:Value())) -- Maybe fix those 200 lines long names by using a local? *cough end if i <= #wayPoints - 1 then Draw.Line(wayPoints[i]:To2D().x, wayPoints[i]:To2D().y, wayPoints[i + 1]:To2D().x, wayPoints[i + 1]:To2D().y, 1, Draw.Color(self.Menu.wPtracker.allyColors.opacity:Value(), self.Menu.wPtracker.allyColors.red:Value(), self.Menu.wPtracker.allyColors.green:Value(), self.Menu.wPtracker.allyColors.blue:Value())) end elseif currentHero.isEnemy and self.Menu.wPtracker.showEnemies:Value() then if self.Menu.wPtracker.eta:Value() then Draw.Text(ETA, 10, wayPoints[#wayPoints]:To2D().x + 10, wayPoints[#wayPoints]:To2D().y + 10, Draw.Color(self.Menu.wPtracker.enemyColors.opacity:Value(), self.Menu.wPtracker.enemyColors.red:Value(), self.Menu.wPtracker.enemyColors.green:Value(), self.Menu.wPtracker.enemyColors.blue:Value())) end if i <= #wayPoints - 1 then Draw.Line(wayPoints[i]:To2D().x, wayPoints[i]:To2D().y, wayPoints[i + 1]:To2D().x, wayPoints[i + 1]:To2D().y, 1, Draw.Color(self.Menu.wPtracker.enemyColors.opacity:Value(), self.Menu.wPtracker.enemyColors.red:Value(), self.Menu.wPtracker.enemyColors.green:Value(), self.Menu.wPtracker.enemyColors.blue:Value())) end end end end end end local heroTable = {} function LazyUtility:CreateHeroTable() for h = 1, Game.HeroCount() do local currentHero = Game.Hero(h) if currentHero.isEnemy then table.insert( heroTable, { hero = currentHero, lastSeen = GetTickCount() } ) end end end function LazyUtility:TrackHeroes() for i, v in pairs(heroTable) do local shortTime = tonumber(string.format("%.1f", (GetTickCount()*0.001 - v.lastSeen*0.001))) local shortName = string.sub(v.hero.charName, 0, 4) if self:IsRecalling(v.hero) then local recall = 0 for i, rc in pairs(self.RecallData) do if rc.object.networkID == v.hero.networkID then recall = tonumber(string.format("%.1f",(rc.start + rc.duration - GetTickCount()) * 0.001)) end end Draw.CircleMinimap(v.hero.pos, 900, 2, Draw.Color(255, 100, 150, 255)) -- Blue for recalls #lazy Draw.Text(shortName.. " RECALL", 6, v.hero.pos:ToMM().x - 20, v.hero.pos:ToMM().y, Draw.Color(255, 50, 150, 255)) -- on MM Draw.Text(v.hero.charName.. " Recalling ( "..recall.." )", 12, v.hero.pos:To2D(), Draw.Color(255, 50, 150, 255)) -- on ground return end if v.hero.visible then heroTable[i].lastSeen = GetTickCount() elseif not v.hero.visible and not v.hero.dead then if not self:IsRecalling(v.hero) then Draw.CircleMinimap(v.hero.pos, 900, 2, Draw.Color(255, 255, 0, 0)) -- Circle on MM end Draw.Text(shortName.. ": " ..shortTime, 9, v.hero.pos:ToMM().x - 20, v.hero.pos:ToMM().y, Draw.Color(255, 255, 255, 255)) -- Text on MM Draw.Text(v.hero.charName.. " MISSING: : " ..shortTime, 12, v.hero.pos:To2D(), Draw.Color(255, 50, 255, 255)) -- draw on ground aswell end end end function LazyUtility:OnDraw() if self.Menu.wPtracker.toggle:Value() then self:DrawWayPoints() end if self.Menu.mMtracker.show:Value() then self:TrackHeroes() end end function LazyUtility:OnRecall(unit, proc) if proc.isStart then table.insert(self.RecallData, { object = unit, start = GetTickCount(), duration = proc.totalTime }) else for i, rc in pairs(self.RecallData) do if rc.object.networkID == unit.networkID then table.remove(self.RecallData, i) end end end end function LazyUtility:IsRecalling(unit) for i, recall in pairs(self.RecallData) do if unit ~= nil then if recall.object.networkID == unit.networkID then return true end else return false end end end function LazyUtility:GetTarget(range) if _G.EOWLoaded then return EOW:GetTarget(range, EOW.ap_dec, myHero.pos) elseif _G.SDK and _G.SDK.TargetSelector then return _G.SDK.TargetSelector:GetTarget(range, _G.SDK.DAMAGE_TYPE_MAGICAL) elseif _G.GOS then return GOS:GetTarget(range, "AP") end end function LazyUtility:GetInventoryItem(itemID) for _, i in pairs({ ITEM_1, ITEM_2, ITEM_3, ITEM_4, ITEM_5, ITEM_6 }) do if myHero:GetItemData(i).itemID == itemID and myHero:GetSpellData(i).currentCd == 0 then return i end end return nil end local items = { [ITEM_1] = HK_ITEM_1, [ITEM_2] = HK_ITEM_2, [ITEM_3] = HK_ITEM_3, [ITEM_4] = HK_ITEM_4, [ITEM_5] = HK_ITEM_5, [ITEM_6] = HK_ITEM_6 } function LazyUtility:UseItems() local target = self:GetTarget(5500) if target ~= nil and self.combo then local bilgewaterCutlass = self:GetInventoryItem(3144) local botrk = self:GetInventoryItem(3153) local ironSolari = self:GetInventoryItem(3383) local edgeOfNight = self:GetInventoryItem(3814) local faceOfTheMountain = self:GetInventoryItem(3401) local frostQueensClaim = self:GetInventoryItem(3092) local hextechGLP = self:GetInventoryItem(3030) local hextechGunblade = self:GetInventoryItem(3146) local hextechProtobelt = self:GetInventoryItem(3152) local mercurialScimitar = self:GetInventoryItem(3139) local mikaelsCrucible = self:GetInventoryItem(3222) local ohmwrecker = self:GetInventoryItem(3056) local ravenousHydra = self:GetInventoryItem(3074) local redemption = self:GetInventoryItem(3107) local tiamat = self:GetInventoryItem(3077) local youmuusGhostblade = self:GetInventoryItem(3142) local zhonyasHourglass = self:GetInventoryItem(3157) local titanicHydra = self:GetInventoryItem(3748) --bilgewaterCutlass if bilgewaterCutlass and self.Menu.Activator.bilgewaterCutlass.useBilgewaterCutlass:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.bilgewaterCutlass.bilgewaterCutlassRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.bilgewaterCutlass.bilgewaterCutlassTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.bilgewaterCutlass.bilgewaterCutlassHP:Value() then Control.CastSpell(items[bilgewaterCutlass], target.pos) end return end --botrk if botrk and self.Menu.Activator.botrk.useBotrk:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.botrk.botrkRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.botrk.botrkTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.botrk.botrkHP:Value() then Control.CastSpell(items[botrk], target.pos) end end --edgeOfNight if edgeOfNight and self.Menu.Activator.edgeOfNight.useEdgeOfNight:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.edgeOfNight.edgeOfNightRange:Value() then Control.CastSpell(items[edgeOfNight], myHero.pos) end --frostQueensClaim if frostQueensClaim and self.Menu.Activator.frostQueensClaim.useFrostQueensClaim:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.frostQueensClaim.frostQueensClaimRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.frostQueensClaim.frostQueensClaimTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.frostQueensClaim.frostQueensClaimHP:Value() then Control.CastSpell(items[frostQueensClaim], myHero.pos) end end --hextechGLP if hextechGLP and self.Menu.Activator.hextechGLP.useHextechGLP:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.hextechGLP.hextechGLPRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.hextechGLP.hextechGLPTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.hextechGLP.hextechGLPHP:Value() then Control.CastSpell(items[hextechGLP], target.pos) end end --hextechGunblade if hextechGunblade and self.Menu.Activator.hextechGunblade.useHextechGunblade:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.hextechGunblade.hextechGunbladeRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.hextechGunblade.hextechGunbladeTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.hextechGunblade.hextechGunbladeHP:Value() then Control.CastSpell(items[hextechGunblade], target.pos) end end --hextechProtobelt if hextechProtobelt and self.Menu.Activator.hextechProtobelt.useHextechProtobelt:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.hextechProtobelt.hextechProtobeltRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.hextechProtobelt.hextechProtobeltTHP:Value() then Control.CastSpell(items[hextechProtobelt], target.pos) end end --redemption if redemption and self.Menu.Activator.redemption.useRedemption:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.redemption.redemptionRange:Value() and target.pos.onScreen then if self:GetHpPercent(myHero) < self.Menu.Activator.redemption.redemptionHP:Value() and not myHero.dead then Control.CastSpell(items[redemption], myHero.pos) elseif self:GetHpPercent(target) < self.Menu.Activator.redemption.redemptionTHP:Value() then Control.CastSpell(items[redemption], target:GetPrediction(target.ms, 100):ToMM()) end end end --zhonyas if zhonyas and self.Menu.Activator.zhonyas.useZhonyas:Value() and self:GetDistance(myHero.pos, target.pos) < self.Menu.Activator.zhonyas.zhonyasRange:Value() then if self:GetHpPercent(target) < self.Menu.Activator.zhonyas.zhonyasTHP:Value() or self:GetHpPercent(myHero) < self.Menu.Activator.zhonyas.zhonyasHP:Value() then Control.CastSpell(items[hextechProtobelt], myHero.pos) end end end function LazyUtility:GetOrbMode() self.combo, self.harass, self.lastHit, self.laneClear, self.jungleClear, self.canMove, self.canAttack = nil,nil,nil,nil,nil,nil,nil if _G.EOWLoaded then local mode = EOW:Mode() self.combo = mode == 1 self.harass = mode == 2 self.lastHit = mode == 3 self.laneClear = mode == 4 self.jungleClear = mode == 4 self.canmove = EOW:CanMove() self.canattack = EOW:CanAttack() elseif _G.SDK then self.combo = _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_COMBO] self.harass = _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_HARASS] self.lastHit = _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_LASTHIT] self.laneClear = _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_LANECLEAR] self.jungleClear = _G.SDK.Orbwalker.Modes[_G.SDK.ORBWALKER_MODE_JUNGLECLEAR] self.canmove = _G.SDK.Orbwalker:CanMove(myHero) self.canattack = _G.SDK.Orbwalker:CanAttack(myHero) elseif _G.GOS then local mode = GOS:GetMode() self.combo = mode == "Combo" self.harass = mode == "Harass" self.lastHit = mode == "Lasthit" self.laneClear = mode == "Clear" self.jungleClear = mode == "Clear" self.canMove = GOS:CanMove() self.canAttack = GOS:CanAttack() end end
XYZBadges.Config.Badges = {} -- Whitelisted badges --XYZBadges.Config.Badges["police"] = {name = "Police Officer", desc = "Has been whitelisted for PD", icon = "police"} --XYZBadges.Config.Badges["ems"] = {name = "EMS", desc = "Has been whitelisted for EMS", icon = "ems"} --XYZBadges.Config.Badges["fbi"] = {name = "FBI", desc = "Has been whitelisted for FBI", icon = "fbi"} --XYZBadges.Config.Badges["mafia"] = {name = "Mafia", desc = "Has been whitelisted for Mafia", icon = "mafia"} --XYZBadges.Config.Badges["pmc"] = {name = "PMC", desc = "Has been whitelisted for PMC", icon = "pmc"} --XYZBadges.Config.Badges["sheriff"] = {name = "Sheriff's Dep", desc = "Has been whitelisted for Sheriff's Department", icon = "sheriff"} --XYZBadges.Config.Badges["ss"] = {name = "Secret Service", desc = "Has been whitelisted for Secret Service", icon = "ss"} --XYZBadges.Config.Badges["swat"] = {name = "SWAT", desc = "Has been whitelisted for SWAT", icon = "swat"} --XYZBadges.Config.Badges["terrorist"] = {name = "Terrorist", desc = "Has been whitelisted for Terrorist", icon = "terrorist"} -- Store based -- Staff -- Automatic XYZBadges.Config.Badges["nolifer"] = {name = "No lifer", desc = "Has shown great dedication to the server", icon = "nolifer"} XYZBadges.Config.Badges["connoisseur"] = {name = "Connoisseur", desc = "Has a strong passion for collecting cars", icon = "connoisseur"} XYZBadges.Config.Badges["baller"] = {name = "Baller", desc = "Has purchased something from the store", icon = "baller"} XYZBadges.Config.Badges["steam"] = {name = "Steam", desc = "Has joined the steam group", icon = "steam"} XYZBadges.Config.Badges["nitroboost"] = {name = "Nitro Boost", desc = "Has Nitro Boosted the discord at some point", icon = "nitroboost"} XYZBadges.Config.Badges["quest"] = {name = "Quest", desc = "Has completed the main storyline", icon = "quest"} -- Manually given XYZBadges.Config.Badges["event"] = {name = "Event winner", desc = "Has won an event", icon = "event"} XYZBadges.Config.Badges["ideas"] = {name = "Ideas!", desc = "Has suggested an idea that was approved", icon = "ideas"} XYZBadges.Config.Badges["staff"] = {name = "Staff", desc = "Was staff at some point", icon = "staff"} XYZBadges.Config.Badges["contentcreator"] = {name = "Content Creator", desc = "Has contributed to a project's development in some way", icon = "contentcreator"} -- Other XYZBadges.Config.Badges["wiper"] = {name = "Wiper", desc = "Was present during an eco wipe", icon = "wiper"} XYZBadges.Config.Badges["veteran"] = {name = "Veteran", desc = "Has been here since the start", icon = "veteran"} XYZBadges.Config.Badges["christmas2019"] = {name = "Christmas 2019", desc = "Purchased during the Christmas 2019 event", icon = "christmas2019"} XYZBadges.Config.Badges["easter2020"] = {name = "Easter 2020", desc = "Played during Easter Sunday 2020", icon = "easter2020"} XYZBadges.Config.Badges["halloween2020"] = {name = "Halloween 2020", desc = "Was around during Halloween 2020", icon = "halloween2020"} XYZBadges.Config.Badges["christmas2020"] = {name = "Christmas 2020", desc = "Purchased during the Christmas 2020 event", icon = "christmas2020"} XYZBadges.Config.Badges["nominee2020"] = {name = "Nomination Awards 2020 Nominee", desc = "Was a finalist in the Nomination Awards 2020", icon = "nominee2020"} XYZBadges.Config.Badges["easter2021"] = {name = "Easter 2021", desc = "Was around during Easter 2021", icon = "easter2021"} XYZBadges.Config.Badges["betatester"] = {name = "Beta Tester", desc = "Has beta tested a project", icon = "betatester"} XYZBadges.Config.Badges["bughunter"] = {name = "Bug Hunter", desc = "Has had a bug report approved.", icon = "bughunter"} ---- Possible (unconfirmed) --XYZBadges.Config.Badges["halloween2018"] = {name = "Spookstical", desc = "Was around during Halloween 2018", icon = "halloween2018"} --XYZBadges.Config.Badges["contributer"] = {name = "Contributer", desc = "Has contributed to a server's development", icon = "contributer"} --XYZBadges.Config.Badges["banned"] = {name = "Naughty", desc = "Has been banned", icon = "banned"} --XYZBadges.Config.Badges["discord"] = {name = "Discord", desc = "Has verified on the main discord", icon = "discord"}
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") ENT.WireDebugName = "Door Controller" function ENT:Initialize() self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self.Inputs = WireLib.CreateSpecialInputs(self, { "Open", "Toggle", "Lock", "Speed", "ReturnDelay", "ForceClosed", "FullOpenSound", "FullCloseSound", "MoveSound", "LockedSound", "UnlockedSound" }, { "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "NORMAL", "STRING", "STRING", "STRING", "STRING", "STRING" }) self.Outputs = WireLib.CreateSpecialOutputs(self, {"Blocker", "Activator", "IsOpened", "IsLocked", "DoorState"}, {"ENTITY", "ENTITY", "NORMAL", "NORMAL", "NORMAL"}) self:SetOverlayText("Door Controller\n(Not linked)") end function ENT:SetOverlayText(txt) self:SetNetworkedBeamString("GModOverlayText", txt) end // Unlink if door removed hook.Add("EntityRemoved", "WireDoorController.linkRemoved", function(ent) for k,v in pairs(ents.FindByClass("gmod_wire_door_controller")) do if v.Door == ent then v:Unlink() end end end) // Inputs function ENT:TriggerInput(iname, value) local ent = self.Door if not ent or not IsValid(ent) then return end if iname == "Open" then self:OpenDoor(value) elseif iname == "Toggle" then if value > 0 then self:ToggleDoor() end elseif iname == "Lock" then self:LockDoor(value) elseif iname == "Speed" then self:SetSpeedDoor(value) elseif iname == "ReturnDelay" then ent:SetSaveValue("returndelay", value) elseif iname == "ForceClosed" then ent:SetSaveValue("forceclosed", tobool(value)) elseif iname == "FullOpenSound" then ent:SetSaveValue("soundopenoverride", value) elseif iname == "FullCloseSound" then ent:SetSaveValue("soundcloseoverride", value) elseif iname == "MoveSound" then ent:SetSaveValue("soundmoveoverride", value) elseif iname == "LockedSound" then ent:SetSaveValue("soundlockedoverride", value) elseif iname == "UnlockedSound" then ent:SetSaveValue("soundunlockedoverride", value) end end function ENT:Link(Door) self.Door = Door self:SetOverlayText("Door Controller\nLinked - "..self.Door:GetModel()) end function ENT:Unlink() self.Door = nil self:SetOverlayText("Door Controller\n(Not linked)") end function ENT:OpenDoor(value) local ent = self.Door if not ent or not IsValid(ent) then return end if value > 0 then ent:Fire("open") else ent:Fire("close") end end function ENT:ToggleDoor() local ent = self.Door if not ent or not IsValid(ent) then return end ent:Fire("Toggle") end function ENT:LockDoor(value) local ent = self.Door if not ent or not IsValid(ent) then return end if value > 0 then ent:Fire("lock") else ent:Fire("unlock") end end function ENT:SetSpeedDoor(value) local ent = self.Door if not ent or not IsValid(ent) then return end if value > 0 then ent:Fire("SetSpeed", value) end end // Outputs function ENT:Think() local ent = self.Door if not ent or not IsValid(ent) then return end local EntTable = ent:GetSaveTable() // Blocker if IsValid(EntTable.m_hBlocker) then WireLib.TriggerOutput(self, "Blocker", EntTable.m_hBlocker) end // Activator if IsValid(EntTable.m_hActivator) then WireLib.TriggerOutput(self, "Activator", EntTable.m_hActivator) end // IsOpened local IsOpened = 0 if EntTable.m_eDoorState == 2 then IsOpened = 1 end WireLib.TriggerOutput(self, "IsOpened", IsOpened) // IsLocked local IsLocked = 0 if EntTable.m_bLocked then IsLocked = 1 end WireLib.TriggerOutput(self, "IsLocked", IsLocked) // DoorState WireLib.TriggerOutput(self, "DoorState", EntTable.m_eDoorState) self:NextThink(CurTime() + 1) return true end
---------------------- -- Author : Deediezi -- Version 4.5 -- -- Contributors : No contributors at the moment. -- -- Github link : https://github.com/Deediezi/FiveM_LockSystem -- You can contribute to the project. All the information is on Github. -- Main algorithm with all functions and events - Client side ---- -- @var vehicles[plate_number] = newVehicle Object local vehicles = {} ESX = nil localVehId = 0 savedVehicle = 0 isTheCarOwner = false ---- Retrieve the keys of a player when he reconnects. -- The keys are synchronized with the server. If you restart the server, all keys disappear. AddEventHandler("playerSpawned", function() TriggerServerEvent("esx_locksystem:retrieveVehiclesOnconnect") end) ---- Main thread -- The logic of the script is here Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end while true do Wait(0) -- If the defined key is pressed if(IsControlJustPressed(1, 42))then doLockSystemToggleLocks() end end end) function doLockSystemToggleLocks() -- Init player infos local ply = GetPlayerPed(-1) local pos = GetEntityCoords(ply) local vehicle = GetClosestVehicle(pos['x'], pos['y'], pos['z'], 5.001, 0, 70) isInside = false -- Retrieve the local ID of the targeted vehicle if(IsPedInAnyVehicle(ply, true))then -- by sitting inside him localVehId = GetVehiclePedIsIn(GetPlayerPed(-1), false) isInside = true else if (vehicle ~= 0) then localVehId = vehicle savedVehicle = vehicle elseif (vehicle ~= 0) and (savedVehicle == vehicle) then localVehId = vehicle elseif (vehicle == 0) then localVehId = savedVehicle end end -- Get targeted vehicle infos if(localVehId and localVehId ~= 0)then local localVehPlateTest = GetVehicleNumberPlateText(localVehId) if localVehPlateTest ~= nil then local localVehPlate = string.lower(localVehPlateTest) local newVehPlate = string.gsub(tostring(localVehPlate), "%s", "") local localVehLockStatus = GetVehicleDoorLockStatus(localVehId) local hasKey = false local myID = GetPlayerServerId(PlayerId()) TriggerServerEvent("esx_locksystem:haveKeys", myID, newVehPlate) if isTheCarOwner then if(time > timer)then if(IsPedInAnyVehicle(ply, true))then if localVehLockStatus <= 2 then SetVehicleDoorsLocked(localVehId, 4) SetVehicleDoorsLockedForAllPlayers(localVehId, 1) TriggerEvent("esx_locksystem:notify", _U("vehicle_locked")) TriggerServerEvent("InteractSound_SV:PlayWithinDistance", 10, "lock", 0.5) time = 0 elseif localVehLockStatus > 2 then SetVehicleDoorsLocked(localVehId, 1) SetVehicleDoorsLockedForAllPlayers(localVehId, false) TriggerEvent("esx_locksystem:notify", _U("vehicle_unlocked")) TriggerServerEvent("InteractSound_SV:PlayWithinDistance", 10, "unlock", 0.5) time = 0 end else if localVehLockStatus <= 2 then local lib = "anim@mp_player_intmenu@key_fob@" local anim = "fob_click" ESX.Streaming.RequestAnimDict(lib, function() TaskPlayAnim(ply, lib, anim, 8.0, -8.0, -1, 0, 0, false, false, false) end) Wait(250) SetVehicleDoorsLocked(localVehId, 4) SetVehicleDoorsLockedForAllPlayers(localVehId, 1) TriggerEvent("esx_locksystem:notify", _U("vehicle_locked")) TriggerServerEvent("InteractSound_SV:PlayWithinDistance", 10, "lock2", 0.5) time = 0 elseif localVehLockStatus > 2 then local lib = "anim@mp_player_intmenu@key_fob@" local anim = "fob_click" ESX.Streaming.RequestAnimDict(lib, function() TaskPlayAnim(ply, lib, anim, 8.0, -8.0, -1, 0, 0, false, false, false) end) Wait(250) SetVehicleDoorsLocked(localVehId, 1) SetVehicleDoorsLockedForAllPlayers(localVehId, false) TriggerEvent("esx_locksystem:notify", _U("vehicle_unlocked")) TriggerServerEvent("InteractSound_SV:PlayWithinDistance", 10, "lock2", 0.5) time = 0 end end else TriggerEvent("esx_locksystem:notify", _U("lock_cooldown", (timer / 1000))) end else -- If the vehicle appear in the table (if this is the player's vehicle or a locked vehicle) for plate, vehicle in pairs(vehicles) do if(string.lower(plate) == localVehPlate)then -- If the vehicle is not locked (this is the player's vehicle) if(vehicle ~= "locked")then hasKey = true if(time > timer)then -- update the vehicle infos (Useful for hydrating instances created by the /givekey command) vehicle.update(localVehId, localVehLockStatus) -- Lock or unlock the vehicle if(IsPedInAnyVehicle(ply, true))then vehicle.lock() time = 0 else local lib = "anim@mp_player_intmenu@key_fob@" local anim = "fob_click" ESX.Streaming.RequestAnimDict(lib, function() TaskPlayAnim(ply, lib, anim, 8.0, -8.0, -1, 0, 0, false, false, false) end) Wait(250) vehicle.lock() time = 0 end else TriggerEvent("esx_locksystem:notify", _U("lock_cooldown", (timer / 1000))) end else TriggerEvent("esx_locksystem:notify", _U("keys_not_inside")) end end end -- If the player doesn't have the keys if(not hasKey)then -- If the player is inside the vehicle if(isInside)then -- If the player find the keys if(canSteal())then -- Check if the vehicle is already owned. -- And send the parameters to create the vehicle object if this is not the case. TriggerServerEvent('esx_locksystem:checkOwner', localVehId, localVehPlate, localVehLockStatus) else -- If the player doesn't find the keys -- Lock the vehicle (players can't try to find the keys again) vehicles[localVehPlate] = "locked" TriggerServerEvent("esx_locksystem:lockTheVehicle", localVehPlate) TriggerEvent("esx_locksystem:notify", _U("keys_not_inside")) end end end end else TriggerEvent("esx_locksystem:notify", _U("could_not_find_plate")) end end end ---- Timer Citizen.CreateThread(function() timer = Config.lockTimer * 1000 time = 0 while true do Wait(1000) time = time + 1000 end end) ---- Prevents the player from breaking the window if the vehicle is locked -- (fixing a bug in the previous version) Citizen.CreateThread(function() while true do Wait(0) local ped = GetPlayerPed(-1) if DoesEntityExist(GetVehiclePedIsTryingToEnter(PlayerPedId(ped))) then local veh = GetVehiclePedIsTryingToEnter(PlayerPedId(ped)) local lock = GetVehicleDoorLockStatus(veh) if lock == 4 then ClearPedTasks(ped) end end end end) ---- Locks vehicles if non-playable characters are in them -- Can be disabled in "config/shared.lua" if(Config.disableCar_NPC)then Citizen.CreateThread(function() while true do Wait(0) local ped = GetPlayerPed(-1) if DoesEntityExist(GetVehiclePedIsTryingToEnter(PlayerPedId(ped))) then local veh = GetVehiclePedIsTryingToEnter(PlayerPedId(ped)) local lock = GetVehicleDoorLockStatus(veh) if lock == 7 then SetVehicleDoorsLocked(veh, 2) end local pedd = GetPedInVehicleSeat(veh, -1) if pedd then SetPedCanBeDraggedOut(pedd, false) end end end end) end ------------------------ EVENTS ------------------------ ------------------------ :) ------------------------ RegisterNetEvent("esx_locksystem:setIsOwner") AddEventHandler("esx_locksystem:setIsOwner", function(callback) if callback == true then isTheCarOwner = true else isTheCarOwner = false end end) ---- Update a vehicle plate (for developers) -- @param string oldPlate -- @param string newPlate RegisterNetEvent("esx_locksystem:updateVehiclePlate") AddEventHandler("esx_locksystem:updateVehiclePlate", function(oldPlate, newPlate) local oldPlate = string.lower(oldPlate) local newPlate = string.lower(newPlate) if(vehicles[oldPlate])then vehicles[newPlate] = vehicles[oldPlate] vehicles[oldPlate] = nil TriggerServerEvent("esx_locksystem:updateServerVehiclePlate", oldPlate, newPlate) end end) ---- Event called from the server -- Get the keys and create the vehicle Object if the vehicle has no owner -- @param boolean hasOwner -- @param int localVehId -- @param string localVehPlate -- @param int localVehLockStatus RegisterNetEvent("esx_locksystem:getHasOwner") AddEventHandler("esx_locksystem:getHasOwner", function(hasOwner, localVehId, localVehPlate, localVehLockStatus) if(not hasOwner)then TriggerEvent("esx_locksystem:newVehicle", localVehPlate, localVehId, localVehLockStatus) TriggerServerEvent("esx_locksystem:addOwner", localVehPlate) TriggerEvent("esx_locksystem:notify", getRandomMsg()) else TriggerEvent("esx_locksystem:notify", _U("vehicle_not_owned")) end end) ---- Create a new vehicle object -- @param int id [opt] -- @param string plate -- @param string lockStatus [opt] RegisterNetEvent("esx_locksystem:newVehicle") AddEventHandler("esx_locksystem:newVehicle", function(plate, id, lockStatus) if(plate)then local plate = string.lower(plate) if(not id)then id = nil end if(not lockStatus)then lockStatus = nil end vehicles[plate] = newVehicle() vehicles[plate].__construct(plate, id, lockStatus) else print("Can't create the vehicle instance. Missing argument PLATE") end end) ---- Event called from server when a player execute the /givekey command -- Create a new vehicle object with its plate -- @param string plate RegisterNetEvent("esx_locksystem:giveKeys") AddEventHandler("esx_locksystem:giveKeys", function(plate) local plate = string.lower(plate) TriggerEvent("esx_locksystem:newVehicle", plate, nil, nil) end) ---- Piece of code from Scott's InteractSound script : https://forum.fivem.net/t/release-play-custom-sounds-for-interactions/8282 -- I've decided to use only one part of its script so that administrators don't have to download more scripts. I hope you won't forget to thank him! RegisterNetEvent('InteractSound_CL:PlayWithinDistance') AddEventHandler('InteractSound_CL:PlayWithinDistance', function(playerNetId, maxDistance, soundFile, soundVolume) local lCoords = GetEntityCoords(localVehId, false) local eCoords = GetEntityCoords(GetPlayerPed(GetPlayerFromServerId(playerNetId))) local distIs = Vdist(lCoords.x, lCoords.y, lCoords.z, eCoords.x, eCoords.y, eCoords.z) local farSound if(distIs < maxDistance) then SendNUIMessage({ transactionType = 'playSound', transactionFile = soundFile, transactionVolume = soundVolume }) elseif distIs >= maxDistance and distIs < 15.0 then SendNUIMessage({ transactionType = 'playSound', transactionFile = soundFile, transactionVolume = 0.25 }) elseif distIs >= 15.0 and distIs < 30.0 then SendNUIMessage({ transactionType = 'playSound', transactionFile = soundFile, transactionVolume = 0.15 }) elseif distIs >= 30.0 and distIs < 50.0 then SendNUIMessage({ transactionType = 'playSound', transactionFile = soundFile, transactionVolume = 0.05 }) end end) RegisterNetEvent('esx_locksystem:notify') AddEventHandler('esx_locksystem:notify', function(text, duration) Notify(text, duration) end) ------------------------ FUNCTIONS ------------------------ ------------------------ :O ------------------------ ---- A simple algorithm that checks if the player finds the keys or not. -- @return boolean function canSteal() nb = math.random(1, 100) percentage = Config.percentage if(nb < percentage)then return true else return false end end ---- Return a random message -- @return string function getRandomMsg() msgNb = math.random(1, #Config.randomMsg) return Config.randomMsg[msgNb] end ---- Get a vehicle in direction -- @param array coordFrom -- @param array coordTo -- @return int function GetVehicleInDirection(coordFrom, coordTo) local rayHandle = CastRayPointToPoint(coordFrom.x, coordFrom.y, coordFrom.z, coordTo.x, coordTo.y, coordTo.z, 10, GetPlayerPed(-1), 0) local a, b, c, d, vehicle = GetRaycastResult(rayHandle) return vehicle end ---- Get the vehicle in front of the player -- @param array pCoords -- @param int ply -- @return int function GetTargetedVehicle(pCoords, ply) for i = 1, 200 do coordB = GetOffsetFromEntityInWorldCoords(ply, 0.0, (6.281)/i, 0.0) targetedVehicle = GetVehicleInDirection(pCoords, coordB) if(targetedVehicle ~= nil and targetedVehicle ~= 0)then return targetedVehicle end end return end ---- Notify the player -- Can be configured in "config/shared.lua" -- @param string text -- @param float duration [opt] function Notify(text, duration) if(Config.notification)then if(Config.notification == 1)then if(not duration)then duration = 0.080 end SetNotificationTextEntry("STRING") AddTextComponentString(text) Citizen.InvokeNative(0x1E6611149DB3DB6B, "CHAR_LIFEINVADER", "CHAR_LIFEINVADER", true, 1, "ESX LockSystem" .. _VERSION, "\"Lock All Your Doors\"", duration) DrawNotification_4(false, true) elseif(Config.notification == 2)then TriggerEvent('chatMessage', '^1ESX LockSystem' .. _VERSION, {255, 255, 255}, text) else return end else return end end RegisterNetEvent('esx_aiomenu:sendProximityMessageID') AddEventHandler('esx_aiomenu:sendProximityMessageID', function(id, message) local myId = PlayerId() local pid = GetPlayerFromServerId(id) if pid == myId then TriggerEvent('chatMessage', "[ID]" .. "", {0, 153, 204}, "^7 " .. message) elseif GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(myId)), GetEntityCoords(GetPlayerPed(pid)), true) < 19.999 then TriggerEvent('chatMessage', "[ID]" .. "", {0, 153, 204}, "^7 " .. message) end end)
RPGM.Classes.RegisterExtra("team", "salary", true) RPGM.RegisterNotificationType("MONEY", gmodI18n.getAddon("rpgm"):getString("notifyTypeMoney"), "5Y76zSd") if CLIENT then RPGM.Config.NotificationSounds[NOTIFY_MONEY] = RPGM.Config.MoneyNotificationSound end local tostring = tostring local find = string.find local abs = math.abs local config = RPGM.Config local function addCurrency(str) return config.CurrencyLeft and config.CurrencySymbol .. str or str .. config.CurrencySymbol end function RPGM.FormatMoney(n) if not n then return addCurrency("0") end if n >= 1e14 then return addCurrency(tostring(n)) end if n <= -1e14 then return "-" .. addCurrency(tostring(abs(n))) end local negative = n < 0 n = tostring(abs(n)) local dp = find(n, "%.") or #n + 1 for i = dp - 4, 1, -3 do n = n:sub(1, i) .. "," .. n:sub(i + 1) end if n[#n - 1] == "." then n = n .. "0" end return (negative and "-" or "") .. addCurrency(n) end
object_tangible_collection_rare_heavy_oppressor_flame_thrower = object_tangible_collection_shared_rare_heavy_oppressor_flame_thrower:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_rare_heavy_oppressor_flame_thrower, "object/tangible/collection/rare_heavy_oppressor_flame_thrower.iff")
Phonemes ={ names = { "eee", "ihh", "ehh", "aaa", "ahh", "aww", "ohh", "uhh", "uuu", "ooo", "rrr", "lll", "mmm", "nnn", "nng", "ngg", "fff", "sss", "thh", "shh", "xxx", "hee", "hoo", "hah", "bbb", "ddd", "jjj", "ggg", "vvv", "zzz", "thz", "zhh" }, gains = { {1.0, 0.0}, -- eee {1.0, 0.0}, -- ihh {1.0, 0.0}, -- ehh {1.0, 0.0}, -- aaa {1.0, 0.0}, -- ahh {1.0, 0.0}, -- aww {1.0, 0.0}, -- ohh {1.0, 0.0}, -- uhh {1.0, 0.0}, -- uuu {1.0, 0.0}, -- ooo {1.0, 0.0}, -- rrr {1.0, 0.0}, -- lll {1.0, 0.0}, -- mmm {1.0, 0.0}, -- nnn {1.0, 0.0}, -- nng {1.0, 0.0}, -- ngg {0.0, 0.7}, -- fff {0.0, 0.7}, -- sss {0.0, 0.7}, -- thh {0.0, 0.7}, -- shh {0.0, 0.7}, -- xxx {0.0, 0.1}, -- hee {0.0, 0.1}, -- hoo {0.0, 0.1}, -- hah {1.0, 0.1}, -- bbb {1.0, 0.1}, -- ddd {1.0, 0.1}, -- jjj {1.0, 0.1}, -- ggg {1.0, 1.0}, -- vvv {1.0, 1.0}, -- zzz {1.0, 1.0}, -- thz {1.0, 1.0} -- zhh }, parameters = { { { 273, 0.996, 10}, -- eee (beet) {2086, 0.945, -16}, {2754, 0.979, -12}, {3270, 0.440, -17} }, { { 385, 0.987, 10}, -- ihh (bit) {2056, 0.930, -20}, {2587, 0.890, -20}, {3150, 0.400, -20} }, { { 515, 0.977, 10}, -- ehh (bet) {1805, 0.810, -10}, {2526, 0.875, -10}, {3103, 0.400, -13} }, { { 773, 0.950, 10}, -- aaa (bat) {1676, 0.830, -6}, {2380, 0.880, -20}, {3027, 0.600, -20} }, { { 770, 0.950, 0}, -- ahh (father) {1153, 0.970, -9}, {2450, 0.780, -29}, {3140, 0.800, -39} }, { { 637, 0.910, 0}, -- aww (bought) { 895, 0.900, -3}, {2556, 0.950, -17}, {3070, 0.910, -20} }, { { 637, 0.910, 0}, -- ohh (bone) NOTE:: same as aww (bought) { 895, 0.900, -3}, {2556, 0.950, -17}, {3070, 0.910, -20} }, { { 561, 0.965, 0}, -- uhh (but) {1084, 0.930, -10}, {2541, 0.930, -15}, {3345, 0.900, -20} }, { { 515, 0.976, 0}, -- uuu (foot) {1031, 0.950, -3}, {2572, 0.960, -11}, {3345, 0.960, -20} }, { { 349, 0.986, 10}, -- ooo (boot) { 918, 0.940, -20}, {2350, 0.960, -27}, {2731, 0.950, -33} }, { { 394, 0.959, -10}, -- rrr (bird) {1297, 0.780, -16}, {1441, 0.980, -16}, {2754, 0.950, -40} }, { { 462, 0.990, 5}, -- lll (lull) {1200, 0.640, -10}, {2500, 0.200, -20}, {3000, 0.100, -30} }, { { 265, 0.987, -10}, -- mmm (mom) {1176, 0.940, -22}, {2352, 0.970, -20}, {3277, 0.940, -31} }, { { 204, 0.980, -10}, -- nnn (nun) {1570, 0.940, -15}, {2481, 0.980, -12}, {3133, 0.800, -30} }, { { 204, 0.980, -10}, -- nng (sang) NOTE:: same as nnn {1570, 0.940, -15}, {2481, 0.980, -12}, {3133, 0.800, -30} }, { { 204, 0.980, -10}, -- ngg (bong) NOTE:: same as nnn {1570, 0.940, -15}, {2481, 0.980, -12}, {3133, 0.800, -30} }, { {1000, 0.300, 0}, -- fff {2800, 0.860, -10}, {7425, 0.740, 0}, {8140, 0.860, 0} }, { {2000, 0.700, -200}, -- sss {2000, 0.700, -15}, {5257, 0.750, -3}, {7171, 0.840, 0} }, { { 100, 0.900, 0}, -- thh {4000, 0.500, -20}, {5500, 0.500, -15}, {8000, 0.400, -20} }, { {2693, 0.940, 0}, -- shh {4000, 0.720, -10}, {6123, 0.870, -10}, {7755, 0.750, -18} }, { {1000, 0.300, -10}, -- xxx NOTE:: Not Really Done Yet {2800, 0.860, -10}, {7425, 0.740, 0}, {8140, 0.860, 0} }, { { 273, 0.996, -40}, -- hee (beet) (noisy eee) {2086, 0.945, -16}, {2754, 0.979, -12}, {3270, 0.440, -17} }, { { 349, 0.986, -40}, -- hoo (boot) (noisy ooo) { 918, 0.940, -10}, {2350, 0.960, -17}, {2731, 0.950, -23} }, { { 770, 0.950, -40}, -- hah (father) (noisy ahh) {1153, 0.970, -3}, {2450, 0.780, -20}, {3140, 0.800, -32} }, { {2000, 0.700, -20}, -- bbb NOTE:: Not Really Done Yet {5257, 0.750, -15}, {7171, 0.840, -3}, {9000, 0.900, 0} }, { { 100, 0.900, 0}, -- ddd NOTE:: Not Really Done Yet {4000, 0.500, -20}, {5500, 0.500, -15}, {8000, 0.400, -20} }, { {2693, 0.940, 0}, -- jjj NOTE:: Not Really Done Yet {4000, 0.720, -10}, {6123, 0.870, -10}, {7755, 0.750, -18} }, { {2693, 0.940, 0}, -- ggg NOTE:: Not Really Done Yet {4000, 0.720, -10}, {6123, 0.870, -10}, {7755, 0.750, -18} }, { {2000, 0.700, -20}, -- vvv NOTE:: Not Really Done Yet {5257, 0.750, -15}, {7171, 0.840, -3}, {9000, 0.900, 0} }, { { 100, 0.900, 0}, -- zzz NOTE:: Not Really Done Yet {4000, 0.500, -20}, {5500, 0.500, -15}, {8000, 0.400, -20} }, { {2693, 0.940, 0}, -- thz NOTE:: Not Really Done Yet {4000, 0.720, -10}, {6123, 0.870, -10}, {7755, 0.750, -18} }, { {2693, 0.940, 0}, -- zhh NOTE:: Not Really Done Yet {4000, 0.720, -10}, {6123, 0.870, -10}, {7755, 0.750, -18} } } } Phonemes._namesindex = swapkeyvalue(Phonemes.names) function Phonemes:namesindex(name) return self._namesindex[name] end function unomenosa(a) return 1-a end function dbamp(db) return 10^(db/20) end function Phonemes:paramsind(ind) local par= flop(self.parameters[ind]) --a[1]=(1-a[1])*a[0]; for i,v in ipairs(par[2]) do par[2][i]= -44100*math.log(v)/(math.pi*par[1][i]) --par[2][i]=(1-v) --*par[1][i] end par[3]= functabla(par[3],dbamp) par[4]=self.gains[ind][1] par[5]=self.gains[ind][2] ---------- par[1] = {par[1]} par[2] = {par[2]} par[3] = {par[3]} return par end function Phonemes:params(name) local ind=self:namesindex(name) local par= flop(self.parameters[ind]) --a[1]=(1-a[1])*a[0]; for i,v in ipairs(par[2]) do par[2][i]= -44100*math.log(v)/(math.pi*par[1][i])--(1-v) --*par[1][i] --par[2][i] = 1-v end par[3]= functabla(par[3],dbamp) par[4]=self.gains[ind][1] par[5]=self.gains[ind][2] ---------- par[1] = {par[1]} par[2],par[3] = {par[3]},{par[2]} --------------- return par end function Phonemes:paramsD(name) local ind=self:namesindex(name) local par= flop(self.parameters[ind]) par[3]= functabla(par[3],dbamp) par[4]=self.gains[ind][1] par[5]=self.gains[ind][2] ---------- --par[1] = {par[1]} local temp = par[2] par[2] = par[3] par[3] = temp --------------- return par end function Phonemes:paramsPalabra(t) local res={} for i,v in ipairs(t) do res[i]=self:params(v) end return res end ----------------------------------------------------------------- Formants={ counterTenorA={ { 660, 1120, 2750, 3000, 3350 }, { 1, 0.50118723362727, 0.070794578438414, 0.063095734448019, 0.012589254117942 }, { 0.12121212121212, 0.080357142857143, 0.043636363636364, 0.043333333333333, 0.041791044776119 } }, altoE={ { 400, 1600, 2700, 3300, 4950 }, { 1, 0.063095734448019, 0.031622776601684, 0.017782794100389, 0.001 }, { 0.15, 0.05, 0.044444444444444, 0.045454545454545, 0.04040404040404 } }, bassA={ { 600, 1040, 2250, 2450, 2750 }, { 1, 0.44668359215096, 0.35481338923358, 0.35481338923358, 0.1 }, { 0.1, 0.067307692307692, 0.048888888888889, 0.048979591836735, 0.047272727272727 } }, bassI={ { 250, 1750, 2600, 3050, 3340 }, { 1, 0.031622776601684, 0.15848931924611, 0.079432823472428, 0.03981071705535 }, { 0.24, 0.051428571428571, 0.038461538461538, 0.039344262295082, 0.035928143712575 } }, altoI={ { 350, 1700, 2700, 3700, 4950 }, { 1, 0.1, 0.031622776601684, 0.015848931924611, 0.001 }, { 0.14285714285714, 0.058823529411765, 0.044444444444444, 0.040540540540541, 0.04040404040404 } }, altoA={ { 800, 1150, 2800, 3500, 4950 }, { 1, 0.63095734448019, 0.1, 0.015848931924611, 0.001 }, { 0.1, 0.078260869565217, 0.042857142857143, 0.037142857142857, 0.028282828282828 } }, tenorA={ { 650, 1080, 2650, 2900, 3250 }, { 1, 0.50118723362727, 0.44668359215096, 0.3981071705535, 0.079432823472428 }, { 0.12307692307692, 0.083333333333333, 0.045283018867925, 0.044827586206897, 0.043076923076923 } }, tenorO={ { 400, 800, 2600, 2800, 3000 }, { 1, 0.31622776601684, 0.25118864315096, 0.25118864315096, 0.050118723362727 }, { 0.1, 0.1, 0.038461538461538, 0.042857142857143, 0.04 } }, --sopranoA={ { 800, 1150, 2900, 3900, 4950 }, { 1, 0.50118723362727, 0.025118864315096, 0.1, 0.0031622776601684 }, { 0.1, 0.078260869565217, 0.041379310344828, 0.033333333333333, 0.028282828282828 } }, sopranoA={ { 600,800, 1150, 3900, 4950 }, {1, 1, 0.50118723362727, 0.1, 0.0031622776601684 }, {0.1, 0.1, 0.078260869565217, 0.033333333333333, 0.028282828282828 } }, --sopranoE={ { 350, 2000, 2800, 3600, 4950 }, { 1, 0.1, 0.17782794100389, 0.01, 0.0015848931924611 }, { 0.17142857142857, 0.05, 0.042857142857143, 0.041666666666667, 0.04040404040404 } }, sopranoE={ { 500, 1850, 2475, 3600, 4950 }, { 1, 0.5, 0.17782794100389, 0.01, 0.0015848931924611 }, { 0.05, 0.05, 0.042857142857143, 0.041666666666667, 0.04040404040404 } }, tenorI={ { 290, 1870, 2800, 3250, 3540 }, { 1, 0.17782794100389, 0.12589254117942, 0.1, 0.031622776601684 }, { 0.13793103448276, 0.048128342245989, 0.035714285714286, 0.036923076923077, 0.033898305084746 } }, tenorU={ { 350, 600, 2700, 2900, 3300 }, { 1, 0.1, 0.14125375446228, 0.19952623149689, 0.050118723362727 }, { 0.11428571428571, 0.1, 0.037037037037037, 0.041379310344828, 0.036363636363636 } }, --sopranoU={ { 325, 700, 2700, 3800, 4950 }, { 1, 0.15848931924611, 0.017782794100389, 0.01, 0.001 }, { 0.15384615384615, 0.085714285714286, 0.062962962962963, 0.047368421052632, 0.04040404040404 } }, sopranoU={ { 325, 700, 2700, 3800, 4950 }, { 1, 0.7848931924611, 0.17782794100389, 0.01, 0.001 }, { 0.15384615384615, 0.085714285714286, 0.062962962962963, 0.047368421052632, 0.04040404040404 } }, counterTenorE={ { 440, 1800, 2700, 3000, 3300 }, { 1, 0.19952623149689, 0.12589254117942, 0.1, 0.1 }, { 0.15909090909091, 0.044444444444444, 0.037037037037037, 0.04, 0.036363636363636 } }, altoO={ { 450, 800, 2830, 3500, 4950 }, { 1, 0.35481338923358, 0.15848931924611, 0.03981071705535, 0.0017782794100389 }, { 0.15555555555556, 0.1, 0.035335689045936, 0.037142857142857, 0.027272727272727 } }, counterTenorU={ { 370, 630, 2750, 3000, 3400 }, { 1, 0.1, 0.070794578438414, 0.031622776601684, 0.019952623149689 }, { 0.10810810810811, 0.095238095238095, 0.036363636363636, 0.04, 0.035294117647059 } }, --sopranoI={ { 270, 2140, 2950, 3900, 4950 }, { 1, 0.25118864315096, 0.050118723362727, 0.050118723362727, 0.0063095734448019 }, { 0.22222222222222, 0.042056074766355, 0.033898305084746, 0.030769230769231, 0.024242424242424 } }, sopranoI={ { 333, 2332, 2986, 3900, 4950 }, { 1, 0.65118864315096, 0.050118723362727, 0.050118723362727, 0.0063095734448019 }, { 0.05, 0.042056074766355, 0.033898305084746, 0.030769230769231, 0.024242424242424 } }, counterTenorO={ { 430, 820, 2700, 3000, 3300 }, { 1, 0.31622776601684, 0.050118723362727, 0.079432823472428, 0.019952623149689 }, { 0.093023255813953, 0.097560975609756, 0.037037037037037, 0.04, 0.036363636363636 } }, bassE={ { 400, 1620, 2400, 2800, 3100 }, { 1, 0.25118864315096, 0.35481338923358, 0.25118864315096, 0.12589254117942 }, { 0.1, 0.049382716049383, 0.041666666666667, 0.042857142857143, 0.038709677419355 } }, counterTenorI={ { 270, 1850, 2900, 3350, 3590 }, { 1, 0.063095734448019, 0.063095734448019, 0.015848931924611, 0.015848931924611 }, { 0.14814814814815, 0.048648648648649, 0.03448275862069, 0.035820895522388, 0.033426183844011 } }, bassO={ { 400, 750, 2400, 2600, 2900 }, { 1, 0.28183829312645, 0.089125093813375, 0.1, 0.01 }, { 0.1, 0.10666666666667, 0.041666666666667, 0.046153846153846, 0.041379310344828 } }, bassU={ { 350, 600, 2400, 2675, 2950 }, { 1, 0.1, 0.025118864315096, 0.03981071705535, 0.015848931924611 }, { 0.11428571428571, 0.13333333333333, 0.041666666666667, 0.044859813084112, 0.040677966101695 } }, altoU={ { 325, 700, 2530, 3500, 4950 }, { 1, 0.25118864315096, 0.031622776601684, 0.01, 0.00063095734448019 }, { 0.15384615384615, 0.085714285714286, 0.067193675889328, 0.051428571428571, 0.04040404040404 } }, tenorE={ { 400, 1700, 2600, 3200, 3580 }, { 1, 0.19952623149689, 0.25118864315096, 0.19952623149689, 0.1 }, { 0.175, 0.047058823529412, 0.038461538461538, 0.0375, 0.033519553072626 } }, --sopranoO={ { 450, 800, 2830, 3800, 4950 }, { 1, 0.28183829312645, 0.079432823472428, 0.079432823472428, 0.0031622776601684 }, { 0.15555555555556, 0.1, 0.035335689045936, 0.034210526315789, 0.027272727272727 } } sopranoO={ { 450, 800, 2830, 3800, 4950 }, { 1, 0.7183829312645, 0.39432823472428, 0.079432823472428, 0.0031622776601684 }, { 0.15555555555556, 0.1, 0.035335689045936, 0.034210526315789, 0.027272727272727 } } } FormantsD = deepcopy(Formants) --to avoid multiexpand for k,v in pairs(Formants) do for i,v2 in ipairs(v) do v[i] = {v2} end end function Formants:params(k) return flop(Formants[k]) --return Formants[k] end function Formants:paramsPalabra(t,voz) voz = voz or "" local res={} for i,v in ipairs(t) do res[i]=Formants[voz..v]--self:params(v) end return res end
--[[ 编写作者: Author: CandyMi[https://github.com/candymi] 编写日期: 2020-11-06 ]] local cf = require "cf" local cself = cf.self local cfork = cf.fork local cwait = cf.wait local cwakeup = cf.wakeup local ctimeout = cf.timeout local lz = require"lz" local uncompress = lz.uncompress local gzuncompress = lz.gzuncompress local protocol = require "lua-http2.protocol" local TYPE_TAB = protocol.TYPE_TAB local ERRNO_TAB = protocol.ERRNO_TAB local SETTINGS_TAB = protocol.SETTINGS_TAB local FLAG_TO_TABLE = protocol.flag_to_table local read_head = protocol.read_head local read_data = protocol.read_data local send_data = protocol.send_data local send_ping = protocol.send_ping local read_ping = protocol.read_ping local send_magic = protocol.send_magic local read_promise = protocol.read_promise local send_rstframe = protocol.send_rstframe local read_rstframe = protocol.read_rstframe local send_settings = protocol.send_settings local read_settings = protocol.read_settings local send_settings_ack = protocol.send_settings_ack local send_window_update = protocol.send_window_update local read_window_update = protocol.read_window_update local read_headers = protocol.read_headers local send_headers = protocol.send_headers local send_goaway = protocol.send_goaway local read_goaway = protocol.read_goaway local sys = require "sys" local new_tab = sys.new_tab local type = type local pairs = pairs local assert = assert local tonumber = tonumber local find = string.find local fmt = string.format local match = string.match local toint = math.tointeger local concat = table.concat local pattern = string.rep(".", 65535) -- 必须遵守此stream id递增规则 local function new_stream_id(num) if not toint(num) or num < 1 then return 1 end return (num + 2) & 2147483647 end -- 分割domain local function split_domain(domain) if type(domain) ~= 'string' or domain == '' or #domain < 8 then return nil, "Invalid http[s] domain." end local scheme, domain_port = match(domain, "^(http[s]?)://([^/]+)") if not scheme or not domain_port then return nil, "Invalid `scheme` : http/https." end local port = scheme == "https" and 443 or 80 local domain = domain_port if find(domain_port, ':') then local host, p local _, Bracket_Pos = find(domain_port, '[%[%]]') if Bracket_Pos then host, p = match(domain_port, '%[(.+)%][:]?(%d*)') else host, p = match(domain_port, '([^:]+)[:](%d*)') end if not host then return nil, "4. invalide host or port: " .. domain_port end domain = host port = toint(p) or port end assert(port >= 1 and port <= 65535, "Invalid Port :" .. port) return { scheme = scheme, domain = domain, port = port } end local function h2_handshake(sock, opt) -- SEND MAGIC BYTES send_magic(sock) -- SEND SETTINS send_settings(sock, nil, { -- SET TABLE SISZE -- {0x01, opt.SETTINGS_HEADER_TABLE_SIZE or SETTINGS_TAB["SETTINGS_HEADER_TABLE_SIZE"]}, -- DISABLE PUSH {0x02, opt.SETTINGS_ENABLE_PUSH or 0x00}, -- SET CONCURRENT STREAM {0x03, opt.SETTINGS_MAX_CONCURRENT_STREAMS or SETTINGS_TAB["SETTINGS_MAX_CONCURRENT_STREAMS"]}, -- SET WINDOWS SIZE {0x04, opt.SETTINGS_INITIAL_WINDOW_SIZE or SETTINGS_TAB["SETTINGS_INITIAL_WINDOW_SIZE"]}, -- SET MAX FRAME SIZE {0x05, opt.SETTINGS_MAX_FRAME_SIZE or SETTINGS_TAB["SETTINGS_MAX_FRAME_SIZE"]}, -- SET SETTINGS MAX HEADER LIST SIZE {0x06, opt.SETTINGS_MAX_HEADER_LIST_SIZE or SETTINGS_TAB["SETTINGS_MAX_HEADER_LIST_SIZE"]}, }) send_window_update(sock, 2 ^ 24 - 1) local settings = {} for _ = 1, 2 do local head = read_head(sock) if not head then return nil, "Handshake timeout." end if head.version == 1.1 then return nil, "The server does not yet support the http2 protocol." end local tname = TYPE_TAB[head.type] if tname == "SETTINGS" then if head.length == 0 then send_settings_ack(sock) break end local s, errno = read_settings(sock, head) if not s then send_goaway(sock, ERRNO_TAB[errno]) return nil, "recv Invalid `SETTINGS` header." end settings = s elseif tname == "WINDOW_UPDATE" then local window = read_window_update(sock, head) if not window then return nil, "Invalid handshake in `WINDOW_UPDATE` frame." end settings["SETTINGS_INITIAL_WINDOW_SIZE"] = window.window_size else return nil, "Invalid `frame type` in handshake." end end for key, value in pairs(SETTINGS_TAB) do if type(key) == 'string' and not settings[key] then settings[key] = value end end if type(settings) ~= 'table' then return nil, "Invalid handshake." end settings['head'] = nil settings['ack'] = nil return settings end local function read_response(self, sid, timeout) local waits = self.waits if tonumber(timeout) and tonumber(timeout) > 0.1 then waits[sid].timer = ctimeout(timeout, function( ) waits[sid].cancel = true cwakeup(waits[sid].co, nil, "request timeout.") self:send(function() return send_rstframe(self.sock, sid, 0x00) end) end) end if not self.read_co then local head, err local sock = self.sock self.read_co = cfork(function () while 1 do head, err = read_head(sock) if not head then break end local tname = head.type_name if tname == "GOAWAY" then local info = read_goaway(sock, head) err = fmt("{errcode = %d, errinfo = '%s'%s}", info.errcode, info.errinfo, info.trace and ', trace = ' .. info.trace or '') break elseif tname == "RST_STREAM" then local info = read_rstframe(sock, head) local ctx = waits[head.stream_id] if ctx then cwakeup(ctx.co, nil, fmt("{ errcode = %d, errinfo = '%s'}", info.errcode, info.errinfo)) if ctx.timer then ctx.timer:stop() ctx.timer = nil end waits[head.stream_id] = nil end -- 应该忽略PUSH_PROMISE帧 elseif tname == "PUSH_PROMISE" then local pid, hds = read_promise(sock, head) if pid and hds then -- 实现虽然拒绝推送流, 但是流推的头部需要被解码 self:send(function() return send_rstframe(sock, pid, 0x00) end) local ok, errinfo = self.hpack:decode(hds) if not ok then err = errinfo break end -- var_dump(h) end elseif tname == "PING" then local payload = read_ping(sock, head) local tab = FLAG_TO_TABLE(tname, head.flags) if not tab.ack then -- 回应PING self:send(function() return send_ping(sock, 0x01, payload) end) end elseif tname == "SETTINGS" then if head.length > 0 then local _ = read_settings(sock, head) self:send(function() return send_settings_ack(sock) end ) end elseif tname == "WINDOW_UPDATE" then local window = read_window_update(sock, head) if not window then err = "Invalid handshake in `WINDOW_UPDATE` frame." break end self:send(function() return send_window_update(sock, window.window_size) end) elseif tname == "HEADERS" or tname == "DATA" then -- print(tname, head.stream_id) local ctx = waits[head.stream_id] if not ctx then self:send(function () send_goaway(sock, ERRNO_TAB[1]) end) break end local headers, body = ctx["headers"], ctx["body"] if tname == "HEADERS" and head.length > 0 then if not headers then self:send(function () send_goaway(sock, ERRNO_TAB[1]) end) break end headers[#headers+1] = read_headers(sock, head) elseif tname == "DATA" and head.length > 0 then if not body then self:send(function () send_goaway(sock, ERRNO_TAB[1]) end) break end body[#body+1] = read_data(sock, head) end local tab = FLAG_TO_TABLE(tname, head.flags) if tab.end_stream then -- 当前流数据接收完毕. if ctx.cancel then break end ctx.headers = self.hpack:decode(concat(headers)) if not ctx.headers then self:send(function () send_goaway(sock, ERRNO_TAB[1]) end) break end if #body > 0 then ctx.body = concat(body) else ctx.body = nil end cwakeup(ctx.co, ctx) if ctx.timer then ctx.timer:stop() ctx.timer = nil end waits[head.stream_id] = nil end else -- 无效的帧类型应该被直接忽略 err = "Unexpected frame type received." break end end -- 如果是意外关闭了连接, 则需要框架内部主动回收资源 if self.connected then -- 如果有等待的请求则直接唤醒并且提示失败. for _, ctx in pairs(self.waits) do -- 如果有定时器则需要关闭 if ctx.timer then ctx.timer:stop() ctx.timer = nil end cwakeup(ctx.co, false, err or "The http2 server unexpectedly closed the network connection.") end self.connected = false end -- 回收资源 self:close() end) end -- 阻塞协程 local ctx, err = cwait() if not ctx then return ctx, err end local body = ctx["body"] local headers = ctx["headers"] local compressed = headers["content-encoding"] if compressed == "gzip" then body = gzuncompress(body) elseif compressed == "deflate" then body = uncompress(body) else if type(body) == 'table' then body = concat(body) end end return { body = body, headers = headers } end local function send_request(self, headers, body, timeout) local sock = self.sock local sid = new_stream_id(self.sid) self.sid = sid self.waits[sid] = { co = cself(), headers = new_tab(8, 0), body = new_tab(16, 0) } -- 发送请求头部 self:send(function() return send_headers(sock, body and 0x04 or 0x05, sid, headers) end) -- 发送请求主体 if body then local total = #body local size = total local max_body_size = 16777205 if size < max_body_size then self:send(function() return send_data(sock, 0x01, sid, body) end) else -- 分割成小数据后发送 for line in body:gmatch(pattern) do size = size - #line self:send(function() return send_data(sock, size == 0 and 0x0 or 0x01, sid, line) end) end if size > 0 then self:send(function() return send_data(sock, 0x01, sid, body:sub(total - size + 1)) end) end end end return read_response(self, self.sid, timeout) end return { send_request = send_request, h2_handshake = h2_handshake, split_domain = split_domain }
-- OptimisticSide local ItemTrend = { Lowering = 0; Unstable = 1; Stable" = 2; Raising = 3; Fluctuating = 4; } return ItemTrend
return { data = { ephemeral = true }, dependencies = { "object", "container", "character", "vanishAfterDisconnect", }, methods = { onEnter = { function(self, args) return self.room:getDesc(self) end, function(self, args, ret) self:send(ret) end, -- TODO: move this to character class }, onLoad = { function(self, args) if not self.cmdset then self.cmdset = cmdsets.Default end self.cmdset = CommandSet:new(self.cmdset) self.cmdset = self.cmdset:union(cmdsets.Default) end }, send = { function(self, args, ret) if self.__puppeteer then return self.__puppeteer:call("send", args) end end }, setState = { function(self, args, ret) if self.__puppeteer then return self.__puppeteer:call("setState", args) end end }, setMenu = { function(self, args, ret) if self.__puppeteer then return self.__puppeteer:call("setMenu", args) end end }, pushMenu = { function(self, args, ret) if self.__puppeteer then return self.__puppeteer:call("pushMenu", args) end end }, popMenu = { function(self, args, ret) if self.__puppeteer then return self.__puppeteer:call("popMenu", args) end end }, } }
pkmn = require("pkmn") print(pkmn.paths.get_database_path())
require('busted.runner')() require('__stdlib__/spec/setup/defines') local Position = require('__stdlib__/stdlib/area/position') local P = Position describe('Position', function () local C = spy.on(Position, 'construct') local N = spy.on(Position, 'new') local L = spy.on(Position, 'load') local K = spy.on(Position, 'from_key') local S = spy.on(Position, 'from_string') local a, a1 local zero local ps, sq, co before_each(function() a = {x = 1, y = 1} a1 = {1, 1} zero = {x = 0, y = 0} ps = { a = Position(4, 8), b = Position(-12, 13), c = Position(8, -6), d = Position(-10, -11) } sq = { a = Position(12, 12), b = Position(-12, 12), c = Position(12, -12), d = Position(-12, -12) } co = { a = Position(-12, -12), b = Position(12, 12), c = Position(-12, 12), d = Position(12, -12), } C:clear() N:clear() L:clear() K:clear() S:clear() end) describe('Constructors', function () describe('.__index', function() it('should point to core', function() assert.is.truthy(getmetatable(Position)._VERSION) end) end) describe('.new', function() it('should create a new version from table', function() assert.not_same(a1, Position.new(a1)) assert.same(a1[1], Position.new(a1).x) end) it('should have the correct metatable', function() assert.same('position', getmetatable(Position.new(a1)).__class) end) end) describe('.construct', function() it('should construct from parameters', function() assert.same({x = -4, y = 21}, Position.construct(-4, 21)) assert.same(3, Position.construct(3).y) -- x copied to y assert.same(3, Position.construct(1, 3).y) -- x and y assert.same(0, Position.construct().y) -- empty params assert.same(0, Position.construct(nil, 4).x) assert.spy(C).was_called(5) end) it('should construct from params if self is passed as first argument', function() assert.same(3, Position.construct(Position.new(a1), 1, 3).y) assert.same(3, Position(1, 3).y) end) end) describe('.__call', function() it('should call the correct constructor', function() local str = spy.on(Position, 'from_string') Position(a1) Position(1) Position('1, 2') Position('{1, 2}') assert.spy(C).was_called(2) assert.spy(N).was_called(2) assert.spy(str).was_called(2) end) it('should create correctly', function() assert.same({x = 0, y = 0}, Position()) assert.same({x = 1, y = 1}, Position(1, 1)) assert.same({x = 1, y = 1}, Position(1)) assert.same({x = 1, y = 1}, Position(a1)) end) end) describe('.from_string', function() it('should construct from a string', function() assert.same(a, Position.from_string('{x = 1, y = 1}')) assert.spy(N).was_called(1) assert.same(a, Position.from_string('{1, 1}')) assert.spy(N).was_called(2) assert.same({x = 1, y = 2}, Position.from_string('1, 2')) assert.spy(C).was_called(1) end) end) describe('.from_key', function() it('should create correctly', function() assert.same({x = 1, y = 2}, Position.from_key('1,2')) assert.same({x = 12, y = -3}, Position.from_key('12,-3')) assert.same({x = -12, y = 3}, Position.from_key('-12,3')) assert.same({x = -12, y = -3}, Position.from_key('-12,-3')) end) end) describe('.load', function() it('should set the metatable to a valid table', function() assert.same('position', getmetatable(Position.load({x = 3, y = -2})).__class) assert.has_no_error(function() Position.load({x = 1, y = -2}) end) assert.spy(L).was.called(2) end) end) end) describe('Methods', function() before_each(function () end) --[[ add, subtract, multiply, divide, mod, unary, abs, center, ceil, floor, center, between, perpendicular, swap, offset_along_line, translate, trim, projection, reflection, average, min, mix, closest, farthest, mix_xy, max_xy ]] it('.add', function () assert.same(P(2, 2), P(1, 1):add(1)) assert.same(P(2, 3), P(1, 1):add(1, 2)) assert.same(P(3, -1), P(1, 1):add{2, -2}) assert.same(P(0, 0), P(1, 1):add(-1)) end) it('.subtract', function () assert.same(P(2, 2), P(3, 3):subtract(1)) assert.same(P(3, 3), P(5, 1):subtract{2, -2}) assert.same(P(0, 0), P(-1, -1):subtract(-1)) end) it('.divide', function () assert.same(P(2, 4), P(4, 8):divide(2)) assert.same(P(2, 2), P(4, 8):divide{2, 4}) assert.same(P(2, -2), P(4, 8):divide{2, -4}) end) it('.multiply', function () assert.same(P(2, 2), P(4, 4):multiply(.5)) assert.same(P(2, -2), P(4, 4):multiply{.5, -.5}) end) it('.mod', function () assert.same(P(0, 0), P(4, 4):mod(2)) assert.same(P(0, 0), P(4, 4):mod{2, -2}) end) it('.closest', function () assert.same(ps.a, P():closest({ps.b, ps.c, ps.d, ps.a})) assert.same(ps.a, P.closest(P(zero)(), {ps.b, ps.c, ps.d, ps.a})) end) it('.farthest', function () assert.same(ps.b, P():farthest({ps.b, ps.c, ps.d, ps.a})) assert.same(ps.b, P.farthest(P(zero)(), {ps.b, ps.c, ps.d, ps.a})) end) it('.unary', function () assert.same(P(2, 2), P(-2, -2):unary()) end) it('.normalize', function () assert.same({x = 2.46, y = 4.72}, P(2.4563787, 4.723444432):normalize()) end) it('.abs', function () assert.same(P(2, 2), P(-2, 2):abs()) end) it('.ceil', function () assert.same(P(2, 3), P(2.4, 2.8):round()) assert.same(P(-2, -3), P(-2.4, -2.8):round()) end) it('.ceil', function () assert.same(P(2, -2), P(1.24, -2.34):ceil()) end) it('.floor', function () assert.same(P(1, -3), P(1.24, -2.34):floor()) end) it('.center', function () assert.same(P(1.5, -1.5), P(1.23, -1.65):center()) end) it('.between', function () assert.same(P(-6, -6), P(0, 0):between(P(-12, -12))) assert.same(P(6, -6), P(0, 0):between(P(12, -12))) assert.same(P(6, 6), P(0, 0):between(P(12, 12))) assert.same(P(-6, 6), P(0, 0):between(P(-12, 12))) end) it('.perpendicular', function () assert.same(P(-12, 12), P(12, 12):perpendicular()) end) it('.swap', function () assert.same(P(1.25, -2.55), P(-2.55, 1.25):swap()) end) it('.trim', function () local max = P(10, 10) assert.same(P(3.5355339059327378, 3.5355339059327378), max:trim(5)) max = P(10, 0) assert.same(P(5, 0), max:trim(5)) end) it('.lerp', function () local from, to = P(), P(-10, 0) assert.same(P(-8, 0), from:lerp(to, .8)) end) it('.offset_along_line', function () assert.same(P(4.59, 4.59), P():offset_along_line(P(6,6), 2)) end) it('.translate', function () local pos = P{1, -4}:store() assert.same({x = 1, y = -5}, pos:translate(defines.direction.north, 1):store()) assert.same({x = 1, y = -3}, pos:recall():translate(defines.direction.south, 2):store()) assert.same({x = 2, y = -3}, pos:recall():translate(defines.direction.east, 1):store()) assert.same({x = -1, y = -3}, pos:recall():translate(defines.direction.west, 3):store()) assert.same({x = 0, y = -2}, pos:recall():translate(defines.direction.southeast, 1):store()) assert.same({x = -1, y = -1}, pos:recall():translate(defines.direction.southwest, 1):store()) assert.same({x = 0, y = -2}, pos:recall():translate(defines.direction.northeast, 1):store()) assert.same({x = -1, y = -3}, pos:recall():translate(defines.direction.northwest, 1):store()) assert.same({x = -1, y = 0}, pos:recall():translate(defines.direction.north, -3):store()) end) it('projection', function () local b, c = P(5, 10), P(10, 10) assert.same(P(7.5, 7.5), b:projection(c)) end) it('reflection', function () local b, c = P(5, 10), P(10, 10) assert.same(P(10, 5), b:reflection(c)) end) end) describe('New Position Methods', function () it('.average', function () assert.same(zero, P.average({sq.a, sq.b, sq.c, sq.d})) assert.same(zero, sq.a:average({sq.b, sq.c, sq.d})) end) it('.min', function () local m = P(4, 8) assert.same(m, P.min({ps.a, ps.b, ps.c, ps.d})) assert.same(m, ps.a:min({ps.b, ps.c, ps.d})) end) it('.max', function () local m = P(-12, 13) assert.same(m, P.max({ps.a, ps.b, ps.c, ps.d})) assert.same(m, ps.a:max({ps.b, ps.c, ps.d})) end) it('.min_xy', function () local m = P(-12, -11) assert.same(m, P.min_xy({ps.a, ps.b, ps.c, ps.d})) assert.same(m, ps.a:min_xy({ps.b, ps.c, ps.d})) end) it('.max_xy', function () local m = P(8, 13) assert.same(m, P.max_xy({ps.a, ps.b, ps.c, ps.d})) assert.same(m, ps.a:max_xy({ps.b, ps.c, ps.d})) end) it('.intersection', function () assert.same(P(), P.intersection(co.a, co.b, co.c, co.d)) assert.not_same(P(), P.intersection(co.a, co.c, co.b, co.d)) end) end) describe('Position Conversion Functions', function () --[[ from_pixels, to_pixels, to_chunk_position, from_chunk_position, ]] it('.from_pixels', function () assert.same(P(2), P(64):from_pixels()) end) it('.to_pixels', function () assert.same(P(64), P(2):to_pixels()) end) it('.to_chunk_position', function () assert.same(P(0, -1), P(16.5, -16.42):to_chunk_position()) end) it('.from_chunk_position', function () assert.same(P(0, -32), P(0, -1):from_chunk_position()) end) end) describe('Functions', function() --[[ increment, atan2, angle, cross, dot, inside, len, len_squared, to_string, to_key, unpack, pack, equals, less_than, less_than_eq, distance_squared, distance, manhattan_distance, is_position, is_zero, is_set, direction_to, simple_direction_to ]] describe('.increment', function() local pos = Position() it('should error with no position argument', function() assert.has_error(function() return Position.incremement() end) end) it('should return a function closure', function() local f = Position.increment(pos) assert.is_true(type(f)=='function') end) it('should not increment on the first call by default', function() local f = Position.increment(pos, 1) assert.same(Position(), f()) end) it('should increment the first call when requested', function() local f = Position.increment(pos, 1, nil, true) assert.same({x=1, y=0}, f()) assert.same({x=2, y=0}, f()) end) it('should return the same position', function() local f = Position.increment(pos) assert.same({x=0, y=0}, f()) assert.same({x=0, y=0}, f()) local g = Position():increment(nil, nil, true) assert.same({x=0, y=0}, g()) assert.same({x=0, y=0}, g()) end) it('should increment using the defaults', function() local f = Position.increment(pos, 0, -1) assert.same({x=0, y=0}, f()) assert.same({x=0, y=-1}, f()) end) it('should increment using passed values', function() local f = Position.increment(pos) assert.same({x=0, y=0}, f(0, -1)) assert.same({x=0, y=-1}, f(0, -1)) assert.same({x=0, y=-3}, f(0, -2)) end) it('should increment using passed values with defaults set', function() local f = Position.increment(pos, -1, -1) assert.same({x=0, y=0}, f()) assert.same({x=-1, y=-1}, f()) assert.same({x=0, y=1}, f(1, 2)) assert.same({x=1, y=4}, f(1, 3)) end) end) it('.atan2', function () assert.same(-1.5707963267948966, P(10, 0):atan2(P(5,0))) end) it('.angle', function () assert.same(90, P(10, 0):angle(P(0, 10))) end) it('.cross', function () assert.same(50, P(10, 0):cross(P(5, 5))) end) it('.dot', function () assert.same(50, P(10, 0):dot(P(5, 5))) end) it('.len', function () assert.same(10, P(10, 0):len()) end) it('.len_squared', function () assert.same(100, P(10, 0):len_squared()) end) it('.to_string', function () local pos = P{1, -4} assert.same('{x = 1, y = -4}', Position.to_string(pos)) assert.has_error(function() Position.to_string() end) end) it('.to_key', function () assert.same('3,-5', P(3, -5):to_key()) assert.same('2,0', P('2,0'):to_key()) assert.spy(S).was_called(1) end) it('.unpack', function () local x, y = Position(1, 2):unpack() assert.same(x, 1) assert.same(y, 2) end) it('.pack', function () assert.same({3, 4}, P(3, 4):pack()) end) describe('.equals', function() it('compares shallow equality in positions', function() local pos1 = P{1, -4} local pos2 = pos1 assert.is_true(Position.equals(pos1, pos2)) assert.is_false(Position.equals(pos1, nil)) assert.is_false(Position.equals(nil, pos2)) assert.is_false(Position.equals(nil, nil)) end) it('compares positions', function() local pos1 = P{1, -4} local pos2 = P{ x = 3, y = -2} local pos3 = P{-1, -4} local pos4 = P{ x = 1, y = -4} assert.is_true(Position.equals(pos1, pos1)) assert.is_false(Position.equals(pos1, pos2)) assert.is_false(Position.equals(pos1, pos3)) assert.is_true(Position.equals(pos1, pos4)) end) end) it('.distance_squared', function () local pos_a = P{1, -4} local pos_b = P{3, -2} assert.same(8, Position.distance_squared(pos_a, pos_b)) assert.same(8, Position.distance_squared(pos_b, pos_a)) end) it('.distance', function () local pos_a = P{5, -5} local pos_b = P{10, 0} assert.same(math.sqrt(50), Position.distance(pos_a, pos_b)) assert.same(math.sqrt(50), Position.distance(pos_b, pos_a)) end) it('.manhattan_distance', function () local pos_a = P{5, -5} local pos_b = P{10, 0} assert.same(10, Position.manhattan_distance(pos_a, pos_b)) assert.same(10, Position.manhattan_distance(pos_b, pos_a)) pos_a = P{1, -4} pos_b = P{3, -2} assert.same(4, Position.manhattan_distance(pos_a, pos_b)) assert.same(4, Position.manhattan_distance(pos_b, pos_a)) end) it('.is_position', function () local p = P() assert.is_true(P.is_position(zero)) assert.is_true(p:is_position()) assert.is_true(P.is_position(a1)) end) it('.is_zero', function () assert.is_true(Position():is_zero()) assert.is_not_true(Position(1, 0):is_zero()) assert.is_true(Position.is_zero({x = 0, y = 0})) end) it('.is_Position', function () local p = P() assert.is_true(p.is_Position(p)) assert.is_true(P.is_Position(p)) assert.is_true(p:is_Position()) assert.is_false(P.is_Position(zero)) end) it('.direction_to', function () local mid = P() local b, c, d, e = P(0, -1), P(1, 0), P(0, 1), P(-1, 0) assert.same(0, mid:direction_to(b)) assert.same(2, mid:direction_to(c)) assert.same(4, mid:direction_to(d)) assert.same(6, mid:direction_to(e)) local f, g, h, i = P(1, -1), P(1, -1), P(-1, 1), P(-1, -1) assert.same(6, mid:direction_to(f)) assert.same(6, mid:direction_to(g)) assert.same(2, mid:direction_to(h)) assert.same(6, mid:direction_to(i)) end) it('.less_than', function () local b, c, d = P(5, 10), P(10, 10), P(10, 10) assert.is_true(b:less_than(c)) assert.is_false(c:less_than(d)) end) it('.less_than_eq', function () local b, c, d = P(5, 10), P(10, 10), P(10, 10) assert.is_true(b:less_than_eq(c)) assert.is_true(c:less_than_eq(d)) end) it('.complex_direction_to', function () local mid = P() local n, ne, e, se, s, sw, w, nw = P(0, -1), P(1, -1), P(1, 0), P(1, 1), P(0, 1), P(-1, 1), P(-1, 0), P(-1, -1) assert.same(0, mid:complex_direction_to(n, true)) assert.same(1, mid:complex_direction_to(ne, true)) assert.same(2, mid:complex_direction_to(e, true)) assert.same(3, mid:complex_direction_to(se, true)) assert.same(4, mid:complex_direction_to(s, true)) assert.same(5, mid:complex_direction_to(sw, true)) assert.same(6, mid:complex_direction_to(w, true)) assert.same(7, mid:complex_direction_to(nw, true)) assert.same(2, mid:complex_direction_to(ne, false)) assert.same(4, mid:complex_direction_to(se, false)) assert.same(6, mid:complex_direction_to(sw, false)) assert.same(0, mid:complex_direction_to(nw, false)) end) it('.inside', function () local area = {left_top = {x = -1, y = -1}, right_bottom = {x = 0, y = 0}} assert.is_true(P(-0.5, -0.7):inside(area)) assert.is_false(P(0.5, -0.7):inside(area)) end) end) describe('Area Conversion Functions', function() --[[ expand_to_area, to_area, to_chunk_area, to_tile_area ]] it('.to_tile_area', function() local area = {left_top = {x = -1, y = -1}, right_bottom = {x = 0, y = 0}} assert.same(area, P(-0.34, -0.75):to_tile_area()) end) it('.to_chunk_area', function() local area = {left_top = {x = -32, y = -32}, right_bottom = {x = 0, y = 0}} assert.same(area, P(-1, -1):to_chunk_area()) end) it('.expand_to_area', function() local pos = { x = 1, y = -4} assert.same(pos, Position.expand_to_area(pos, 0).left_top) assert.same(pos, Position.expand_to_area(pos, 0).right_bottom) local expanded_area = {left_top = { x = -1, y = -6}, right_bottom = { x = 3, y = -2 }} assert.same(expanded_area, Position.expand_to_area(pos, 2)) end) it('.to_area', function () local area = {left_top = {x = 1, y = -4}, right_bottom = {x = 6, y = 2}} assert.same(area, P(1, -4):to_area(5, 6)) end) end) describe('object metamethods', function() --[[ __class, __index. __add, __sub, __mul, __div, __mod, __unm, __len, __eq, __lt, __le, __tostring, __concat, __call, ]] local mta, mtb, mtc before_each(function() mta = Position() --0, 0 mtb = Position(1,1) mtc = Position(3, 3) end) it('.__class', function () assert.same('Position', getmetatable(P).__class) assert.same('position', getmetatable(mta).__class) end) it('__index', function() assert.same(getmetatable(mta).__index, Position) end) it('.__call should trigger a constructor()', function() local b2 = mta() local c2 = b2 assert.same(mta, b2) assert.is_false(rawequal(mta, b2)) assert.is_true(rawequal(b2, c2)) end) it('.__add', function() assert.same(Position(1, 1), mta + mtb) assert.same(Position(2, 2), mta + 2) assert.same(Position(2, -2), mta + {2, -2}) assert.same(Position(3, 3), 2 + mtb) assert.same(Position(3, -1), {2, -2} + mtb) end) it('.__sub', function() assert.same(Position(-1, -1), mta - mtb) assert.same(Position(-2, -2), mta - 2) assert.same(Position(-2, 2), mta - {2, -2}) assert.same(Position(1, 1), 2 - mtb) assert.same(Position(1, -3), {2, -2} - mtb) end) it('.__mul', function() assert.same(Position(9, 9), mtc * mtc) assert.same(Position(0, 0), mta * 2) assert.same(Position(2, -2), mtb * {2, -2}) assert.same(Position(6, 6), 2 * mtc) assert.same(Position(6, -6), {2, -2} * mtc) end) it('.__div', function() assert.same(Position(1, 1), mtc / mtc) assert.same(Position(0, 0), mta / 2) assert.same(Position(.5, -.5), mtb / {2, -2}) assert.same(Position(.66666666666666663, .66666666666666663), 2 / mtc) assert.same(Position(.66666666666666663, -.66666666666666663), {2, -2} / mtc) end) it('.__mod', function() assert.same(Position(1, 1), mtb % mtc) assert.same(Position(0, 0), mtc % mtb) end) it('.__unm', function() assert.same(Position(-1, -1), -mtb) assert.same(Position(1, -3), -Position(-1, 3)) end) it('__eq', function() local mtd = mta local mte = Position() local mtf = Position(2,2) assert.is_true(mta == mtd) assert.is_true(mta == mte) assert.not_true(mta == mtf) assert.not_true(mta == 0) end) it('__lt', function() local mte = Position(2,2) local mtf = Position(-2,-2) assert.is_true(mta < mte) assert.is_true(mte > mta) assert.is_false(mtf < mtb) end) it('__le', function() local mte = Position(2,2) local mtf = Position(-2,-2) local mtg = Position(2,2) assert.is_true(mta <= mte) assert.is_true(mte >= mta) assert.is_true(mtf <= mte) assert.is_true(mta <= mtg) assert.is_true(P(-10, -10) <= P(-100, -100)) end) it('__tostring', function() local b1 = Position(1,1) local b2 = Position(1, 1) local c1 = Position(2,2) assert.same(tostring(b1), tostring(b2)) assert.not_same(tostring(mta), tostring(c1)) end) it('__concat', function() local q = Position() local r = mta() assert.same(50, #(q .. ' is concatenated with ' .. r)) end) it('__len ', function() assert.same(50, #Position(50, 0)) assert.same(50, #Position(0, -50)) assert.same(35.355339059327378, #Position(25, -25)) end) end) end)
function dump(s) io.stderr:write(require("scripts.inspect").inspect(s) .. "\n") -- io.stderr:write(pandoc.utils.stringify(s) .. "\n") end local pandoc = _G.pandoc function P(s) print(require("scripts.inspect").inspect(s)) end local COMMENT = false local List = require("pandoc.List") function Blocks(blocks) for i = #blocks - 1, 1, -1 do if blocks[i].t == "Null" then blocks:remove(i) end end return blocks end function string.starts_with(str, starts) return str:sub(1, #starts) == starts end function string.ends_with(str, ends) return ends == "" or str:sub(-#ends) == ends end function RawBlock(el) local str = el.c[2] if str == "<!-- panvimdoc-ignore-start -->" then COMMENT = true return pandoc.Null() elseif str == "<!-- panvimdoc-ignore-end -->" then COMMENT = false return pandoc.Null() end if string.starts_with(str, "<!--") then return pandoc.Null() elseif str == "<p>" or str == "</p>" then return pandoc.Null() elseif str == "<details>" or str == "</details>" then return pandoc.Null() elseif str == "<summary>" or str == "</summary>" then return pandoc.Null() elseif COMMENT == true then return pandoc.Null() else return el end end function Header(el) if COMMENT == true then return pandoc.Null() end return el end function Para(el) if COMMENT == true then return pandoc.Null() end return el end function BlockQuote(el) if COMMENT == true then return pandoc.Null() end return el end function Table(el) if COMMENT == true then return pandoc.Null() end return el end function Plain(el) if COMMENT == true then return pandoc.Null() end return el end function OrderedList(el) if COMMENT == true then return pandoc.Null() end return el end function BulletList(el) if COMMENT == true then return pandoc.Null() end return el end function LineBlock(el) if COMMENT == true then return pandoc.Null() end return el end function HorizontalRule(el) if COMMENT == true then return pandoc.Null() end return el end function Div(el) if COMMENT == true then return pandoc.Null() end return el end function DefinitionList(el) if COMMENT == true then return pandoc.Null() end return el end function CodeBlock(el) if COMMENT == true then return pandoc.Null() end return el end function Str(el) if COMMENT == true then return pandoc.Str("") end return el end function Cite(el) if COMMENT == true then return pandoc.Str("") end return el end function Code(el) if COMMENT == true then return pandoc.Str("") end return el end function Emph(el) if COMMENT == true then return pandoc.Str("") end return el end function Image(el) if COMMENT == true then return pandoc.Str("") end return el end function LineBreak(el) if COMMENT == true then return pandoc.Str("") end return el end function Link(el) if COMMENT == true then return pandoc.Str("") end return el end function Math(el) if COMMENT == true then return pandoc.Str("") end return el end function Note(el) if COMMENT == true then return pandoc.Str("") end return el end function Quoted(el) if COMMENT == true then return pandoc.Str("") end return el end function RawInline(el) if COMMENT == true then return pandoc.Str("") end return el end function SmallCaps(el) if COMMENT == true then return pandoc.Str("") end return el end function SoftBreak(el) if COMMENT == true then return pandoc.Str("") end return el end function Space(el) if COMMENT == true then return pandoc.Str("") end return el end function Span(el) if COMMENT == true then return pandoc.Str("") end return el end function Text(el) if COMMENT == true then return pandoc.Str("") end return el end function Strikeout(el) if COMMENT == true then return pandoc.Str("") end return el end function Strong(el) if COMMENT == true then return pandoc.Str("") end return el end function Subscript(el) if COMMENT == true then return pandoc.Str("") end return el end function Superscript(el) if COMMENT == true then return pandoc.Str("") end return el end function Underline(el) if COMMENT == true then return pandoc.Str("") end return el end
-- const { utils, consts } = require('../lora-lib'); -- const BluebirdPromise = require('bluebird'); -- const TXParamSetupReq_PARAM = consts.TXPARAMSETUPREQ; -- module.exports = function (devAddr, DownlinkDwellTime, UplinkDwellTime, MaxEIRP) { -- let _this = this; -- return new BluebirdPromise((resolve, reject) => { -- let MaxDwellTime = DownlinkDwellTime * TXParamSetupReq_PARAM.DOWNLINKDWELLTIME_BASE + -- UplinkDwellTime * TXParamSetupReq_PARAM.UPLINKDWELLTIME_BASE + MaxEIRP * TXParamSetupReq_PARAM.MAXEIRP_BASE; -- let outputObj = { -- [Buffer.from([consts.TXPARAMSETUP_CID], 'hex').toString('hex')]: { -- DwellTime: utils.numToHexBuf(MaxDwellTime, TXParamSetupReq_PARAM.EIRP_DWELLTIME_LEN), -- }, -- }; -- // push cmd req into queue -- const mqKey = consts.MACCMDQUEREQ_PREFIX + devAddr; -- _this.redisConn.DownlinkCmdQueue.produce(mqKey, outputObj).then(() => { -- _this.log.debug({ -- label: 'MAC Command Req', -- message: { -- TXParamSetupReq: mqKey, -- payload: outputObj, -- }, -- }); -- resolve(outputObj); -- }); -- }); -- }
-- Copyright (c) 2015 Corona Labs, Inc. -- -- 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 Library = require "CoronaLibrary" -- Create library local lib = Library:new{ name='plugin.playfab.client', publisherId='com.playfab' } ------------------------------------------------------------------------------- -- BEGIN (Insert your implementation starting here) ------------------------------------------------------------------------------- local json = require("plugin.playfab.client.json") local defaults = require("plugin.playfab.client.defaults") local _directories = defaults.directories local _isDirWriteable = defaults.writePermissions local _isDirReadable = defaults.readPermissions function lib.loadTable( filename, baseDir ) local result = nil baseDir = baseDir or _directories.loadDir -- Validate params assert( type(filename) == "string", "'loadTable' invalid filename" ) assert( _isDirReadable[baseDir], "'loadTable' invalid baseDir" ) local path = system.pathForFile( filename, baseDir ) local file = io.open( path, "r" ) if file then -- read all contents of file into a string local contents = file:read( "*a" ) result = json.decode( contents ) io.close( file ) end return result end function lib.saveTable( t, filename, baseDir ) local result = false baseDir = baseDir or _directories.saveDir -- Validate params assert( type(t) == "table", "'saveTable' invalid table" ) assert( type(filename) == "string", "'saveTable' invalid filename" ) assert( _isDirWriteable[baseDir], "'saveTable' invalid baseDir" ) local path = system.pathForFile( filename, baseDir ) local file = io.open( path, "w" ) if file then local contents = json.encode( t ) file:write( contents ) io.close( file ) result = true end return result end -- printTable( t [, label [, level ]] ) function lib.printTable( t, label, level ) -- Validate params assert( "table" == type(t), "Bad argument 1 to 'printTable' (table expected, got " .. type(t) .. ")" ) if label then print( label ) end level = level or 1 for k,v in pairs( t ) do -- Indent according to nesting 'level' local prefix = "" for i=1,level do prefix = prefix .. "\t" end -- Print key/value pair print( prefix .. "[" .. tostring(k) .. "] = " .. tostring(v) ) -- Recurse on tables if type( v ) == "table" then print( prefix .. "{" ) printTable( v, nil, level + 1 ) print( prefix .. "}" ) end end end lib.IPlayFabHttps = require("plugin.playfab.client.IPlayFabHttps") lib.json = require("plugin.playfab.client.json") lib.PlayFabClientApi = require("plugin.playfab.client.PlayFabClientApi") lib.PlayFabSettings = require("plugin.playfab.client.PlayFabSettings") local PlayFabHttpsCorona = require("plugin.playfab.client.PlayFabHttpsCorona") lib.IPlayFabHttps.SetHttp(PlayFabHttpsCorona) -- Assign the Corona-specific IHttps wrapper ------------------------------------------------------------------------------- -- END ------------------------------------------------------------------------------- -- Return library instance return lib
--- ---This example definition of a class file is a guideline. The class system is ---left intentionally vague so as to not be too opinionated. Class files are ---assumed to be js files instead of blank yaml files just to future proof the ---bundle-loading of class files in case someone wants extra functionality in ---their classes. --- return { name = "Warrior", description = "Warriors relish being face-to-face with their enemy. Whether it be wielding axes, maces, swords, or a nearby log, Warriors focus on dealing strong physical damage to their opponent. What they lack in the raw magical damage of a Mage, or the healing prowess of a Cleric, Warriors make up for in their tenacity. Those choosing the more defensive path of the shield can outlast otherwise deadly attacks.", abilityTable = { [3] = { skills = { "rend" } }, [5] = { skills = { "lunge" } }, [7] = { skills = { "shieldblock" } }, [10] = { skills = { "secondwind" } }, }, setupPlayer = function(state, player) local energy = state.AttributeFactory:create("energy", 100); player:addAttribute(energy); player.prompt = "[ %health.current%/%health.max% <bold>hp %energy.current%/%energy.max% <bold>energy ]"; end, };
-- This file is auto-generated by shipwright.nvim local common_fg = "#4C554D" local inactive_bg = "#D5E7D8" local inactive_fg = "#4B663C" return { normal = { a = { bg = "#A3B5A6", fg = common_fg, gui = "bold" }, b = { bg = "#B8CCBA", fg = common_fg }, c = { bg = "#CAE0CD", fg = "#202E18" }, }, insert = { a = { bg = "#B0C3D4", fg = common_fg, gui = "bold" }, }, command = { a = { bg = "#E1BFD9", fg = common_fg, gui = "bold" }, }, visual = { a = { bg = "#B4ED92", fg = common_fg, gui = "bold" }, }, replace = { a = { bg = "#EEDFE0", fg = common_fg, gui = "bold" }, }, inactive = { a = { bg = inactive_bg, fg = inactive_fg, gui = "bold" }, b = { bg = inactive_bg, fg = inactive_fg }, c = { bg = inactive_bg, fg = inactive_fg }, }, }
package.path = ".\\?.lua;" .. package.path package.cpath = ".\\?.dll;" .. package.cpath crvmgr = require("test_c") require("init") el_test_num_table = { {"1000000000000000000000000000000000000000000000000000000000000000000000000", "#3", "1000000000000000000000000000000000000000000000000000000000000000000000000"}, {"100000000000000000000000000000000000000000000000000000000000000000000000", "#3", "一千無量大数"}, {"10000000000000000000000000000000000000000000000000000000000000000000000", "#3", "百無量大数"}, {"1000000000000000000000000000000000000000000000000000000000000000000000", "#3", "十無量大数"}, {"100000000000000000000000000000000000000000000000000000000000000000000", "#3", "一無量大数"}, {"10000000000000000000000000000000000000000000000000000000000000000000", "#3", "一千不可思議"}, {"1000000000000000000000000000000000000000000000000000000000000000000", "#3", "百不可思議"}, {"100000000000000000000000000000000000000000000000000000000000000000", "#3", "十不可思議"}, {"10000000000000000000000000000000000000000000000000000000000000000", "#3", "一不可思議"}, {"1000000000000000000000000000000000000000000000000000000000000000", "#3", "一千那由他"}, {"100000000000000000000000000000000000000000000000000000000000000", "#3", "百那由他"}, {"10000000000000000000000000000000000000000000000000000000000000", "#3", "十那由他"}, {"1000000000000000000000000000000000000000000000000000000000000", "#3", "一那由他"}, {"100000000000000000000000000000000000000000000000000000000000", "#3", "一千阿僧祇"}, {"10000000000000000000000000000000000000000000000000000000000", "#3", "百阿僧祇"}, {"1000000000000000000000000000000000000000000000000000000000", "#3", "十阿僧祇"}, {"100000000000000000000000000000000000000000000000000000000", "#3", "一阿僧祇"}, {"10000000000000000000000000000000000000000000000000000000", "#3", "一千恒河沙"}, {"1000000000000000000000000000000000000000000000000000000", "#3", "百恒河沙"}, {"100000000000000000000000000000000000000000000000000000", "#3", "十恒河沙"}, {"10000000000000000000000000000000000000000000000000000", "#3", "一恒河沙"}, {"1000000000000000000000000000000000000000000000000000", "#3", "一千極"}, {"100000000000000000000000000000000000000000000000000", "#3", "百極"}, {"10000000000000000000000000000000000000000000000000", "#3", "十極"}, {"1000000000000000000000000000000000000000000000000", "#3", "一極"}, {"100000000000000000000000000000000000000000000000", "#3", "一千載"}, {"10000000000000000000000000000000000000000000000", "#3", "百載"}, {"1000000000000000000000000000000000000000000000", "#3", "十載"}, {"100000000000000000000000000000000000000000000", "#3", "一載"}, {"10000000000000000000000000000000000000000000", "#3", "一千正"}, {"1000000000000000000000000000000000000000000", "#3", "百正"}, {"100000000000000000000000000000000000000000", "#3", "十正"}, {"10000000000000000000000000000000000000000", "#3", "一正"}, {"1000000000000000000000000000000000000000", "#3", "一千澗"}, {"100000000000000000000000000000000000000", "#3", "百澗"}, {"10000000000000000000000000000000000000", "#3", "十澗"}, {"1000000000000000000000000000000000000", "#3", "一澗"}, {"100000000000000000000000000000000000", "#3", "一千溝"}, {"10000000000000000000000000000000000", "#3", "百溝"}, {"1000000000000000000000000000000000", "#3", "十溝"}, {"100000000000000000000000000000000", "#3", "一溝"}, {"10000000000000000000000000000000", "#3", "一千穣"}, {"1000000000000000000000000000000", "#3", "百穣"}, {"100000000000000000000000000000", "#3", "十穣"}, {"10000000000000000000000000000", "#3", "一穣"}, {"1000000000000000000000000000", "#3", "一千𥝱"}, {"100000000000000000000000000", "#3", "百𥝱"}, {"10000000000000000000000000", "#3", "十𥝱"}, {"1000000000000000000000000", "#3", "一𥝱"}, {"100000000000000000000000", "#3", "一千垓"}, {"10000000000000000000000", "#3", "百垓"}, {"1000000000000000000000", "#3", "十垓"}, {"100000000000000000000", "#3", "一垓"}, {"10000000000000000000", "#3", "一千京"}, {"1000000000000000000", "#3", "百京"}, {"100000000000000000", "#3", "十京"}, {"10000000000000000", "#3", "一京"}, {"1000000000000000", "#3", "一千兆"}, {"100000000000000", "#3", "百兆"}, {"10000000000000", "#3", "十兆"}, {"1000000000000", "#3", "一兆"}, {"100000000000", "#3", "一千億"}, {"10000000000", "#3", "百億"}, {"1000000000", "#3", "十億"}, {"100000000", "#3", "一億"}, {"10000000", "#3", "一千万"}, {"1000000", "#3", "百万"}, {"100000", "#3", "十万"}, {"10000", "#3", "一万"}, {"1000", "#3", "一千"}, {"100", "#3", "百"}, {"10", "#3", "十"}, {"1", "#3", "一"}, {"123456789012345678901234", "#3", "一千二百三十四垓五千六百七十八京九千十二兆三千四百五十六億七千八百九十万一千二百三十四"}, {"12345678901234567890123", "#3", "百二十三垓四千五百六十七京八千九百一兆二千三百四十五億六千七百八十九万百二十三"}, {"1234567890123456789012", "#3", "十二垓三千四百五十六京七千八百九十兆一千二百三十四億五千六百七十八万九千十二"}, {"123456789012345678901", "#3", "一垓二千三百四十五京六千七百八十九兆百二十三億四千五百六十七万八千九百一"}, {"12345678901234567890", "#3", "一千二百三十四京五千六百七十八兆九千十二億三千四百五十六万七千八百九十"}, {"1234567890123456789", "#3", "百二十三京四千五百六十七兆八千九百一億二千三百四十五万六千七百八十九"}, {"123456789012345678", "#3", "十二京三千四百五十六兆七千八百九十億一千二百三十四万五千六百七十八"}, {"12345678901234567", "#3", "一京二千三百四十五兆六千七百八十九億百二十三万四千五百六十七"}, {"1234567890123456", "#3", "一千二百三十四兆五千六百七十八億九千十二万三千四百五十六"}, {"123456789012345", "#3", "百二十三兆四千五百六十七億八千九百一万二千三百四十五"}, {"12345678901234", "#3", "十二兆三千四百五十六億七千八百九十万一千二百三十四"}, {"1234567890123", "#3", "一兆二千三百四十五億六千七百八十九万百二十三"}, {"123456789012", "#3", "一千二百三十四億五千六百七十八万九千十二"}, {"12345678901", "#3", "百二十三億四千五百六十七万八千九百一"}, {"123456789", "#3", "一億二千三百四十五万六千七百八十九"}, {"12345678", "#3", "一千二百三十四万五千六百七十八"}, {"1234567", "#3", "百二十三万四千五百六十七"}, {"123456", "#3", "十二万三千四百五十六"}, {"12345", "#3", "一万二千三百四十五"}, {"1234", "#3", "一千二百三十四"}, {"123", "#3", "百二十三"}, {"12", "#3", "十二"}, {"1", "#3", "一"}, {"0", "#3", "〇"}, {"1000000000000000000000000000000000000000000000000000000000000000000000000", "#5", "1000000000000000000000000000000000000000000000000000000000000000000000000"}, {"100000000000000000000000000000000000000000000000000000000000000000000000", "#5", "壱千無量大数"}, {"10000000000000000000000000000000000000000000000000000000000000000000000", "#5", "百無量大数"}, {"1000000000000000000000000000000000000000000000000000000000000000000000", "#5", "拾無量大数"}, {"100000000000000000000000000000000000000000000000000000000000000000000", "#5", "壱無量大数"}, {"10000000000000000000000000000000000000000000000000000000000000000000", "#5", "壱千不可思議"}, {"1000000000000000000000000000000000000000000000000000000000000000000", "#5", "百不可思議"}, {"100000000000000000000000000000000000000000000000000000000000000000", "#5", "拾不可思議"}, {"10000000000000000000000000000000000000000000000000000000000000000", "#5", "壱不可思議"}, {"1000000000000000000000000000000000000000000000000000000000000000", "#5", "壱千那由他"}, {"100000000000000000000000000000000000000000000000000000000000000", "#5", "百那由他"}, {"10000000000000000000000000000000000000000000000000000000000000", "#5", "拾那由他"}, {"1000000000000000000000000000000000000000000000000000000000000", "#5", "壱那由他"}, {"100000000000000000000000000000000000000000000000000000000000", "#5", "壱千阿僧祇"}, {"10000000000000000000000000000000000000000000000000000000000", "#5", "百阿僧祇"}, {"1000000000000000000000000000000000000000000000000000000000", "#5", "拾阿僧祇"}, {"100000000000000000000000000000000000000000000000000000000", "#5", "壱阿僧祇"}, {"10000000000000000000000000000000000000000000000000000000", "#5", "壱千恒河沙"}, {"1000000000000000000000000000000000000000000000000000000", "#5", "百恒河沙"}, {"100000000000000000000000000000000000000000000000000000", "#5", "拾恒河沙"}, {"10000000000000000000000000000000000000000000000000000", "#5", "壱恒河沙"}, {"1000000000000000000000000000000000000000000000000000", "#5", "壱千極"}, {"100000000000000000000000000000000000000000000000000", "#5", "百極"}, {"10000000000000000000000000000000000000000000000000", "#5", "拾極"}, {"1000000000000000000000000000000000000000000000000", "#5", "壱極"}, {"100000000000000000000000000000000000000000000000", "#5", "壱千載"}, {"10000000000000000000000000000000000000000000000", "#5", "百載"}, {"1000000000000000000000000000000000000000000000", "#5", "拾載"}, {"100000000000000000000000000000000000000000000", "#5", "壱載"}, {"10000000000000000000000000000000000000000000", "#5", "壱千正"}, {"1000000000000000000000000000000000000000000", "#5", "百正"}, {"100000000000000000000000000000000000000000", "#5", "拾正"}, {"10000000000000000000000000000000000000000", "#5", "壱正"}, {"1000000000000000000000000000000000000000", "#5", "壱千澗"}, {"100000000000000000000000000000000000000", "#5", "百澗"}, {"10000000000000000000000000000000000000", "#5", "拾澗"}, {"1000000000000000000000000000000000000", "#5", "壱澗"}, {"100000000000000000000000000000000000", "#5", "壱千溝"}, {"10000000000000000000000000000000000", "#5", "百溝"}, {"1000000000000000000000000000000000", "#5", "拾溝"}, {"100000000000000000000000000000000", "#5", "壱溝"}, {"10000000000000000000000000000000", "#5", "壱千穣"}, {"1000000000000000000000000000000", "#5", "百穣"}, {"100000000000000000000000000000", "#5", "拾穣"}, {"10000000000000000000000000000", "#5", "壱穣"}, {"1000000000000000000000000000", "#5", "壱千𥝱"}, {"100000000000000000000000000", "#5", "百𥝱"}, {"10000000000000000000000000", "#5", "拾𥝱"}, {"1000000000000000000000000", "#5", "壱𥝱"}, {"100000000000000000000000", "#5", "壱千垓"}, {"10000000000000000000000", "#5", "百垓"}, {"1000000000000000000000", "#5", "拾垓"}, {"100000000000000000000", "#5", "壱垓"}, {"10000000000000000000", "#5", "壱千京"}, {"1000000000000000000", "#5", "百京"}, {"100000000000000000", "#5", "拾京"}, {"10000000000000000", "#5", "壱京"}, {"1000000000000000", "#5", "壱千兆"}, {"100000000000000", "#5", "百兆"}, {"10000000000000", "#5", "拾兆"}, {"1000000000000", "#5", "壱兆"}, {"100000000000", "#5", "壱千億"}, {"10000000000", "#5", "百億"}, {"1000000000", "#5", "拾億"}, {"100000000", "#5", "壱億"}, {"10000000", "#5", "壱千万"}, {"1000000", "#5", "百万"}, {"100000", "#5", "拾万"}, {"10000", "#5", "壱万"}, {"1000", "#5", "壱千"}, {"100", "#5", "百"}, {"10", "#5", "拾"}, {"1", "#5", "壱"}, {"125456789012345678901234", "#5", "壱千弐百五拾四垓五千六百七拾八京九千拾弐兆参千四百五拾六億七千八百九拾万壱千弐百参拾四"}, {"12345678901234567890123", "#5", "百弐拾参垓四千五百六拾七京八千九百壱兆弐千参百四拾五億六千七百八拾九万百弐拾参"}, {"1234567890123456789012", "#5", "拾弐垓参千四百五拾六京七千八百九拾兆壱千弐百参拾四億五千六百七拾八万九千拾弐"}, {"123456789012345678901", "#5", "壱垓弐千参百四拾五京六千七百八拾九兆百弐拾参億四千五百六拾七万八千九百壱"}, {"12345678901234567890", "#5", "壱千弐百参拾四京五千六百七拾八兆九千拾弐億参千四百五拾六万七千八百九拾"}, {"1234567890123456789", "#5", "百弐拾参京四千五百六拾七兆八千九百壱億弐千参百四拾五万六千七百八拾九"}, {"123456789012345678", "#5", "拾弐京参千四百五拾六兆七千八百九拾億壱千弐百参拾四万五千六百七拾八"}, {"12345678901234567", "#5", "壱京弐千参百四拾五兆六千七百八拾九億百弐拾参万四千五百六拾七"}, {"1234567890123456", "#5", "壱千弐百参拾四兆五千六百七拾八億九千拾弐万参千四百五拾六"}, {"123456789012345", "#5", "百弐拾参兆四千五百六拾七億八千九百壱万弐千参百四拾五"}, {"12345678901234", "#5", "拾弐兆参千四百五拾六億七千八百九拾万壱千弐百参拾四"}, {"1234567890123", "#5", "壱兆弐千参百四拾五億六千七百八拾九万百弐拾参"}, {"123456789012", "#5", "壱千弐百参拾四億五千六百七拾八万九千拾弐"}, {"12345678901", "#5", "百弐拾参億四千五百六拾七万八千九百壱"}, {"123456789", "#5", "壱億弐千参百四拾五万六千七百八拾九"}, {"12345678", "#5", "壱千弐百参拾四万五千六百七拾八"}, {"1234567", "#5", "百弐拾参万四千五百六拾七"}, {"123456", "#5", "拾弐万参千四百五拾六"}, {"12345", "#5", "壱万弐千参百四拾五"}, {"1234", "#5", "壱千弐百参拾四"}, {"123", "#5", "百弐拾参"}, {"12", "#5", "拾弐"}, {"1", "#5", "壱"}, {"0", "#5", "零"}, {"9876543210", "#0", "9876543210"}, {"9876543210", "#1", "9876543210"}, {"9876543210", "#2", "九八七六五四三二一〇"}, {"9", "#8", "9"}, {"98", "#8", "98"}, {"987", "#8", "987"}, {"9876", "#8", "9,876"}, {"98765", "#8", "98,765"}, {"987654", "#8", "987,654"}, {"9876543", "#8", "9,876,543"}, {"98765432", "#8", "98,765,432"}, {"987654321", "#8", "987,654,321"}, {"9876543210", "#8", "9,876,543,210"}, {"98765432109", "#8", "98,765,432,109"}, {"987654321098", "#8", "987,654,321,098"}, {"9876543210987", "#8", "9,876,543,210,987"}, {"98765432109876", "#8", "98,765,432,109,876"}, {"98", "#9", "9八"}, {"141", "#9", "141"}, {"1000000000001", "#3", "一兆一"}, {"10000000000001", "#3", "十兆一"}, {"100000000000001", "#3", "百兆一"}, {"1000000000000001", "#3", "一千兆一"}, {"24", "#6", "XXIV"}, {"48", "#6", "XLVIII"}, {"495", "#6", "CDXCV"}, {"1888", "#6", "MDCCCLXXXVIII"}, {"2444", "#6", "MMCDXLIV"}, {"3999", "#6", "MMMCMXCIX"}, } local result = "OK" for i, v in ipairs(el_test_num_table) do print("<= \"" .. v[1] .. "\" \"".. v[2] .. "\"") local s = lua_skk_convert_candidate(v[1], v[2], "") if (s) then if (s == "") then s = v[2] end print("=> \"" .. s .. "\"") else print("=> nil") end if (v[3]) then if (type(v[3]) == "function") then v[3] = v[3](s) end if (tostring(s) == v[3]) then print "OK\n" else result = "NG" print("== " .. v[3] .. "\n" .. result) break end else print("\n") end end if (result == "OK") then print("\nAll OK.") end
music = "mountains.ogg" function start() portal_up = Portal:new{x=1, y=4} portal_down = Portal:new{x=5, y=4} end function stop() end function update(step) portal_up:update() portal_down:update() if (portal_up.go_time) then change_areas("mountain_descent1", 1, 4, DIRECTION_EAST) elseif (portal_down.go_time) then change_areas("mountain_descent3", 5, 4, DIRECTION_WEST) end end function activate(activator, activated) end function collide(id1, id2) end
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") SWEP.magType = "pistolMag" CustomizableWeaponry:registerAmmo(".30 Carbine", ".30 Caliber Rounds", 7.62, 33) SWEP.PrintName = "M1 Carbine" if CLIENT then SWEP.DrawCrosshair = false SWEP.CSMuzzleFlashes = true SWEP.IconLetter = "w" killicon.Add( "khr_m1carbine", "icons/killicons/khr_m1carbine", Color(255, 80, 0, 150)) SWEP.SelectIcon = surface.GetTextureID("icons/killicons/khr_m1carbine") SWEP.MuzzleEffect = "muzzleflash_6" SWEP.PosBasedMuz = true SWEP.ShellScale = 0.3 SWEP.FireMoveMod = 1 SWEP.ShellOffsetMul = 1 SWEP.ShellPosOffset = {x = 1, y = 0, z = 0} SWEP.ForeGripOffsetCycle_Draw = 0 SWEP.SightWithRail = true SWEP.DisableSprintViewSimulation = false SWEP.SnapToIdlePostReload = true SWEP.EffectiveRange_Orig = 68.4 * 39.37 SWEP.DamageFallOff_Orig = .34 SWEP.BoltBone = "Bolt" SWEP.BoltBonePositionRecoverySpeed = 40 SWEP.BoltShootOffset = Vector(0, 2, 0) SWEP.IronsightPos = Vector(-3.108, -3, 0.98) SWEP.IronsightAng = Vector(0.92, 0.03, 0) SWEP.EoTech553Pos = Vector(-3.108, -4.5, .15) SWEP.EoTech553Ang = Vector(.92, 0, 0) SWEP.CSGOACOGPos = Vector(0, 0, 0) SWEP.CSGOACOGAng = Vector(0, 0, 0) SWEP.MicroT1Pos = Vector(0, 0, 0) SWEP.MicroT1Ang = Vector(0, 0, 0) SWEP.KR_CMOREPos = Vector(-3.0885, -4.5, .159) SWEP.KR_CMOREAng = Vector(.92, 0, 0) SWEP.ShortDotPos = Vector(-3.0885, -5.5, .159) SWEP.ShortDotAng = Vector(.92, 0, 0) SWEP.FAS2AimpointPos = Vector(-3.05, -5, .585) SWEP.FAS2AimpointAng = Vector(-.5, 0, 0) SWEP.SprintPos = Vector(0.079, 0, -1.68) SWEP.SprintAng = Vector(-20.403, 30.25, -26.031) SWEP.CustomizePos = Vector(2.839, -1.407, -0.561) SWEP.CustomizeAng = Vector(12.663, 22.513, 14.774) SWEP.AlternativePos = Vector(-1, -1.6667, 0) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.CustomizationMenuScale = 0.023 SWEP.ViewModelMovementScale = 1 SWEP.AttachmentModelsVM = { ["md_saker222"] = { type = "Model", model = "models/cw2/attachments/556suppressor.mdl", bone = "receiver", rel = "", pos = Vector(0, 6.752, -1.15), angle = Angle(0, 0, 0), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_foregrip"] = { type = "Model", model = "models/wystan/attachments/foregrip1.mdl", bone = "receiver", rel = "", pos = Vector(-0.24, -3.636, -2.201), angle = Angle(0, 0, 0), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_rail"] = { type = "Model", model = "models/wystan/attachments/rail.mdl", bone = "receiver", rel = "", pos = Vector(0.28, 3, 0.15), angle = Angle(0, 90, 0), size = Vector(0.5, 1, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_eotech"] = { type = "Model", model = "models/c_fas2_eotech.mdl", bone = "receiver", rel = "", pos = Vector(0.039, 5, 0.689), angle = Angle(0, -90, 0), size = Vector(0.8, 0.8, 0.8), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_aimpoint"] = { type = "Model", model = "models/c_fas2_aimpoint.mdl", bone = "receiver", rel = "", pos = Vector(0.1, 4.5, 0.55), angle = Angle(0, -90, 0), size = Vector(0.819, 0.819, 0.819), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_schmidt_shortdot"] = { type = "Model", model = "models/cw2/attachments/schmidt.mdl", bone = "receiver", rel = "", pos = Vector(-0.171, -1, -2.61), angle = Angle(0, -90, 0), size = Vector(0.649, 0.649, 0.649), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["odec3d_cmore_kry"] = { type = "Model", model = "models/weapons/krycek/sights/odec3d_cmore_reddot.mdl", bone = "receiver", rel = "", pos = Vector(0, 2.7, 1.149), angle = Angle(0, -90, 0), size = Vector(0.219, 0.219, 0.219), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.ForeGripHoldPos = { ["l_wrist"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(12.222, -3.333, -10) }, ["l_upperarm"] = { scale = Vector(1, 1, 1), pos = Vector(0.185, -0.186, 0.185), angle = Angle(0, 0, 0) }, ["l_index_low"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(0, 0, 16.666) }, ["l_armtwist_1"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(3.332, 0, 0) }, ["l_forearm"] = { scale = Vector(1, 1, 1), pos = Vector(-0.186, 0.185, -1.297), angle = Angle(63.333, 0, 7.777) }} SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0, forward = 0} end SWEP.MuzzleVelocity = 700 -- in meter/s SWEP.LuaViewmodelRecoil = false SWEP.CanRestOnObjects = true SWEP.Attachments = {[1] = {header = "Sight", offset = {400, -150}, atts = {"odec3d_cmore_kry", "md_fas2_eotech", "md_fas2_aimpoint"}}, [3] = {header = "Conversion", offset = {1000, 100}, atts = {"md_m2carbine"}}, [2] = {header = "Barrel", offset = {-380, -200}, atts = {"md_saker222"}}, ["+reload"] = {header = "Ammo", offset = {-300, 250}, atts = {"am_magnum", "am_matchgrade"}}} SWEP.Animations = {fire = {"shoot1","shoot2","shoot3"}, reload = "reload", idle = "idle", draw = "draw2"} SWEP.Sounds = { draw2 = {{time = 0, sound = "KSKS.Deploy"}}, reload = {[1] = {time = .5, sound = "M1C.CLIPOUT"}, [2] = {time = 2.15, sound = "KRISS_Magin"}, [3] = {time = 2.55, sound = "KRISS_Maghit"}, [4] = {time = 3.5, sound = "M1C.BOLT"}}} SWEP.HoldBoltWhileEmpty = false SWEP.DontHoldWhenReloading = true SWEP.LuaVMRecoilAxisMod = {vert = 1.25, hor = .5, roll = .25, forward = .5, pitch = 1.5} SWEP.SpeedDec = 30 SWEP.OverallMouseSens = .9 SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "passive" SWEP.FireModes = {"semi"} SWEP.Base = "cw_base" SWEP.Category = "CW 2.0 - Rifles" SWEP.Author = "Khris" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 75 SWEP.AimViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/khrcw2/v_khri_m1car.mdl" SWEP.WorldModel = "models/khrcw2/w_khri_m1car.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 15 SWEP.Primary.DefaultClip = 15 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = ".30 Carbine" SWEP.FireDelay = 60/600 SWEP.FireSound = "M1C.Fire" SWEP.FireSoundSuppressed = "M1C.SupFire" SWEP.Recoil = 1 SWEP.HipSpread = 0.040 SWEP.AimSpread = 0.0046 SWEP.VelocitySensitivity = 1 SWEP.MaxSpreadInc = 0.04 SWEP.SpreadPerShot = 0.006 SWEP.SpreadCooldown = .1 SWEP.Shots = 1 SWEP.Damage = 30 SWEP.DeployTime = 0.6 SWEP.ReloadSpeed = 1.1 SWEP.ReloadTime = 4.4 SWEP.ReloadTime_Empty = 4.4 SWEP.ReloadHalt = 4.4 SWEP.ReloadHalt_Empty = 4.4 SWEP.Offset = { Pos = { Up = 2, Right = 1, Forward = -3, }, Ang = { Up = 1, Right = -10, Forward = 180, } } function SWEP:DrawWorldModel( ) local hand, offset, rotate local pl = self:GetOwner() if IsValid( pl ) then local boneIndex = pl:LookupBone( "ValveBiped.Bip01_R_Hand" ) if boneIndex then local pos, ang = pl:GetBonePosition( boneIndex ) pos = pos + ang:Forward() * self.Offset.Pos.Forward + ang:Right() * self.Offset.Pos.Right + ang:Up() * self.Offset.Pos.Up ang:RotateAroundAxis( ang:Up(), self.Offset.Ang.Up) ang:RotateAroundAxis( ang:Right(), self.Offset.Ang.Right ) ang:RotateAroundAxis( ang:Forward(), self.Offset.Ang.Forward ) self:SetRenderOrigin( pos ) self:SetRenderAngles( ang ) self:DrawModel() end else self:SetRenderOrigin( nil ) self:SetRenderAngles( nil ) self:DrawModel() end end function SWEP:IndividualThink() self.EffectiveRange = 68.4 * 39.37 self.DamageFallOff = .34 if self.ActiveAttachments.am_matchgrade then self.EffectiveRange = ((self.EffectiveRange + 10.26 * 39.37)) self.DamageFallOff = ((self.DamageFallOff - .051)) end if self.ActiveAttachments.md_saker222 then self.EffectiveRange = ((self.EffectiveRange - 17.1 * 39.37)) self.DamageFallOff = ((self.DamageFallOff + .085)) end end
-- https://github.com/ImagicTheCat/vRP -- MIT license (see LICENSE or vrp/vRPShared.lua) if not vRP.modules.map then return end -- BLIPS: see https://wiki.gtanet.work/index.php?title=Blips for blip id/color local IDManager = module("vrp", "lib/IDManager") local Map = class("Map", vRP.Extension) -- SUBCLASS Map.Entity = class("Map.Entity") -- Entity.command for command methods function Map.Entity:__construct(id,cfg) self.id = id self.cfg = cfg end -- called when the entity is loaded function Map.Entity:load() end -- called when the entity is unloaded function Map.Entity:unload() end -- called to check if the entity is active -- px, py, pz: player position -- should return true if active function Map.Entity:active(px, py, pz) return false end -- called at each render frame if the entity is active -- time: seconds since last frame function Map.Entity:frame(time) end -- basic entities local PosEntity = class("PosEntity", Map.Entity) Map.PosEntity = PosEntity function PosEntity:load() self.active_distance = self.cfg.active_distance or 250 self.pos = self.cfg.pos end function PosEntity:active(px,py,pz) local dist = GetDistanceBetweenCoords(self.pos[1],self.pos[2],self.pos[3],px,py,pz,true) return (dist <= self.active_distance) end -- PoI local PoI = class("PoI", Map.PosEntity) function PoI:load() PosEntity.load(self) -- blip if self.cfg.blip_id and self.cfg.blip_color then self.blip = AddBlipForCoord(self.cfg.pos[1],self.cfg.pos[2],self.cfg.pos[3]) SetBlipSprite(self.blip, self.cfg.blip_id) SetBlipAsShortRange(self.blip, true) SetBlipColour(self.blip, self.cfg.blip_color) if self.cfg.blip_scale then SetBlipScale(self.blip, self.cfg.blip_scale) end if self.cfg.blip_flashes then if self.cfg.blip_flashes == 2 then SetBlipFlashesAlternate(self.blip, true) else SetBlipFlashes(self.blip, true) end end if self.cfg.title then BeginTextCommandSetBlipName("STRING") AddTextComponentString(self.cfg.title) EndTextCommandSetBlipName(self.blip) end end -- prepare marker self.scale = self.cfg.scale or {0.7,0.7,0.5} self.color = self.cfg.color or {0,255,125,125} self.marker_id = self.cfg.marker_id self.height = self.cfg.height or 0 self.rotate_speed = self.cfg.rotate_speed self.rz = 0 end function PoI:unload() if self.blip then RemoveBlip(self.blip) end end function PoI:active(px,py,pz) return (PosEntity.active(self, px,py,pz) and self.marker_id) end function PoI:frame(time) if self.rotate_speed then self.rz = (self.rz+360*self.rotate_speed*time)%360 end DrawMarker(self.marker_id,self.pos[1],self.pos[2],self.pos[3]+self.height,0,0,0,0,0,self.rz,self.scale[1],self.scale[2],self.scale[3],self.color[1],self.color[2],self.color[3],self.color[4],0) end PoI.command = {} function PoI.command:setBlipRoute() if self.blip then SetBlipRoute(self.blip,true) end end -- PlayerMark local PlayerMark = class("PlayerMark", Map.Entity) function PlayerMark:setup() -- get target ped local player = GetPlayerFromServerId(self.cfg.player) if player and NetworkIsPlayerConnected(player) then self.ped = GetPlayerPed(player) end -- blip if self.ped and self.cfg.blip_id and self.cfg.blip_color then self.blip = AddBlipForEntity(self.ped) SetBlipSprite(self.blip, self.cfg.blip_id) SetBlipAsShortRange(self.blip, true) SetBlipColour(self.blip, self.cfg.blip_color) if self.cfg.blip_scale then SetBlipScale(self.blip, self.cfg.blip_scale) end if self.cfg.blip_flashes then if self.cfg.blip_flashes == 2 then SetBlipFlashesAlternate(self.blip, true) else SetBlipFlashes(self.blip, true) end end if self.cfg.title then BeginTextCommandSetBlipName("STRING") AddTextComponentString(self.cfg.title) EndTextCommandSetBlipName(self.blip) end end end function PlayerMark:load() self:setup() end function PlayerMark:unload() if self.blip then RemoveBlip(self.blip) end end function PlayerMark:active() if not DoesBlipExist(self.blip) then self:setup() end return false end -- METHODS function Map:__construct() vRP.Extension.__construct(self) self.entities = {} -- map of id (number or name) => entity self.entities_ids = IDManager() self.def_entities = {} -- defined entities self.frame_entities = {} -- active entities for the next frames self.areas = {} -- basic entities self:registerEntity(PoI) self:registerEntity(PlayerMark) -- task: entities active check Citizen.CreateThread(function() while true do Citizen.Wait(100) local px,py,pz = vRP.EXT.Base:getPosition() self.frame_entities = {} for id,entity in pairs(self.entities) do if entity:active(px,py,pz) then self.frame_entities[entity] = true end end end end) -- task: entities frame Citizen.CreateThread(function() local last_time = GetGameTimer() while true do Citizen.Wait(0) local time = GetGameTimer() local elapsed = (last_time-time)*0.001 last_time = time for entity in pairs(self.frame_entities) do entity:frame(elapsed) end end end) -- task: areas triggers detections Citizen.CreateThread(function() while true do Citizen.Wait(250) local px,py,pz = vRP.EXT.Base:getPosition() for k,v in pairs(self.areas) do -- detect enter/leave local player_in = (GetDistanceBetweenCoords(v.x,v.y,v.z,px,py,pz,true) <= v.radius and math.abs(pz-v.z) <= v.height) if v.player_in and not player_in then -- was in: leave self.remote._leaveArea(k) elseif not v.player_in and player_in then -- wasn't in: enter self.remote._enterArea(k) end v.player_in = player_in -- update area player_in end end end) end -- ent: Map.Entity class function Map:registerEntity(ent) if class.is(ent, Map.Entity) then local id = class.name(ent) if self.def_entities[id] then self:log("WARNING: re-registered entity \""..id.."\"") end self.def_entities[id] = ent else self:error("Not an Entity class.") end end -- add entity -- ent: registered entity name -- cfg: entity config -- return id (number) or nil on failure function Map:addEntity(ent, cfg) local cent = self.def_entities[ent] local id if cent then id = self.entities_ids:gen() local nent = cent(id, cfg) self.entities[id] = nent nent:load() end return id end -- id: number or string function Map:removeEntity(id) local ent = self.entities[id] if ent then ent:unload() self.frame_entities[ent] = nil self.entities[id] = nil if type(id) == "number" then self.entities_ids:free(id) end end end -- id: number (update added entity) or string (create/update named entity) -- ent: registered entity name -- cfg: entity config function Map:setEntity(id, ent, cfg) local cent = self.def_entities[ent] if cent then -- unload previous entity local pent = self.entities[id] if pent then pent:unload() self.frame_entities[pent] = nil end -- load new entity local nent = cent(id, cfg) self.entities[id] = nent nent:load() end end -- entity command -- id: number or string -- command: command name -- ...: arguments function Map:commandEntity(id, command, ...) local ent = self.entities[id] if ent then local f = ent.command[command] if f then return f(ent, ...) end end end -- GPS -- set the GPS destination marker coordinates function Map:setGPS(x,y) SetNewWaypoint(x,y) end -- AREA -- create/update a cylinder area function Map:setArea(name,x,y,z,radius,height) local area = {x=x,y=y,z=z,radius=radius,height=height} -- default values if area.height == nil then area.height = 6 end self.areas[name] = area end -- remove area function Map:removeArea(name) self.areas[name] = nil end -- DOOR -- set the closest door state -- doordef: .model or .modelhash -- locked: boolean -- doorswing: -1 to 1 function Map:setStateOfClosestDoor(doordef, locked, doorswing) local x,y,z = vRP.EXT.Base:getPosition() local hash = doordef.modelhash if hash == nil then hash = GetHashKey(doordef.model) end SetStateOfClosestDoorOfType(hash,x,y,z,locked,doorswing) end -- TUNNEL Map.tunnel = {} Map.tunnel.addEntity = Map.addEntity Map.tunnel.setEntity = Map.setEntity Map.tunnel.removeEntity = Map.removeEntity Map.tunnel.commandEntity = Map.commandEntity Map.tunnel.setGPS = Map.setGPS Map.tunnel.setArea = Map.setArea Map.tunnel.removeArea = Map.removeArea Map.tunnel.setStateOfClosestDoor = Map.setStateOfClosestDoor vRP:registerExtension(Map)
function ExtractResources(sourceDir, destDir) SetDataType("S06") -- TODO: Finish this end function Load(dataDir, cacheDir, stageID) SetDataType("S06") local dir, type = dataDir, "xenon" -- TODO: Make an IOPathCombine function please you beautiful moron if IODirExists(dir .. "/xenon") then type = "xenon" elseif IODirExists(dir .. "/ps3") then type = "ps3" else LogError("ERROR: Invalid Data Directory") return end dir = dir .. "/" .. type -- Set Data (E.G. xenon/archives/scripts.arc) UIChangeStatus("Extracting Scripts ARC...") Extract(dir .. "/archives/scripts.arc", "{0}/scripts", "Scripts") local setDir = "{0}/scripts/" .. type .. "/placement/{1}" local files = IOGetFilesInDir(setDir, "*.set", false) if files ~= nil and #files > 0 then UIShowProgress() for i = 1, #files do UIChangeProgress(((i - 1) / #files) * 100) UIChangeLoadStatus(string.format( "Set Data %02d/%02d", i, #files)) LoadSetLayer(files[i]) -- TODO: Load Object Models end UIHideProgress() end UIToggleSetsSaving(true) -- TODO: Finish This end function SaveSets(dataDir, cacheDir, stageID) -- Set Data (E.G. xenon/archives/scripts.arc) SetDataType("S06") local dir, type = cacheDir .. "/scripts", "xenon" if IODirExists(dir .. "/xenon") then type = "xenon" elseif IODirExists(dir .. "/ps3") then type = "ps3" else LogError("ERROR: Invalid Data Directory") return end dir = dir .. "/" .. type local setDir = "{0}/scripts/" .. type .. "/placement/{1}" SaveSetLayers(setDir, "", ".set", true) -- TODO: Repack end function SaveAll(dataDir, cacheDir, stageID) -- TODO end
object_tangible_loot_undead_decal_smear_01 = object_tangible_loot_undead_shared_decal_smear_01:new { } ObjectTemplates:addTemplate(object_tangible_loot_undead_decal_smear_01, "object/tangible/loot/undead/decal_smear_01.iff")
local os = require('ffi').os local env = require('env') local tmpdir = os == 'Windows' and env.get('TMP') or '/tmp' local db = require("./lus/db").DB:new("sqlite3", tmpdir.."/test.sqlite3") local User = require("./lus/db").Model:extend():new(db) local app = require("./lus/websocket").WebSocket:new() -- prepare db User.db:run"DROP TABLE user" User.db:run[[ CREATE TABLE user( id INT PRIMARY KEY, name VARCHAR(50), email VARCHAR(50) ) ]] local list = { { id=1, name="Jose das Couves", email="jose@couves.com", }, { id=2, name="Jack", email="manoel.joaquim@cafundo.com", }, { id=3, name="Jack", email="maria@dores.com", }, } print("------------------------ User:save") for i, p in pairs (list) do User:save({id=p.id, name=p.name, email=p.email}) end print("------------------------ User:all") p(User:all()) print("------------------------ User:find(1)") p(User:find(1)) print("------------------------ User:find(4)") p(User:find(4)) print("------------------------ User:where({name='Jack'})") p(User:where({name='Jack'})) print("------------------------ User:where(where({name='Jack',email='maria@dores.com'})") p(User:where({name='Jack',email='maria@dores.com'})) print("------------------------ User:update({name='Jack2'},{email='maria@dores.com'})") p(User:update({name='Jack2'},{email='maria@dores.com'})) print("------------------------ User:where({name='Jack2'})") p(User:where({name='Jack2'})) print("------------------------ User:destroy({id=2})") p(User:destroy({id=2})) print("------------------------ User:destroy({name='Jack2'})") p(User:destroy({name='Jack2'})) print("------------------------ User:all") p(User:all()) app:listen({port=8002,enc='json'}, function(net) p("-- [Server]onListen", net:peeraddress().ip..":"..net:peeraddress().port) net:on('User', function(args) print("= [Server]on User", args.id) local user = User:find(args.id) net:Emit('User', {user=user}) end) end, function(net, data) p("-- [Server]onReceive", data, net:peeraddress().ip..":"..net:peeraddress().port) end, function(net) p("-- [Server]onClose") end) print("================= Server listen at", "websocket://"..app._ip..":"..app._port)
local rpc = require 'lua-lsp.rpc' local log = require 'lua-lsp.log' local method_handlers = require 'lua-lsp.methods' _G.Types = _G.Types or {} _G.Documents = _G.Documents or {} _G.Globals = _G.Globals -- defined in analyze.lua -- selfish default _G.Config = _G.Config or { language = "5.3", builtins = {"5_3"}, packagePath = {"./?.lua"}, debugMode = false, _useNativeLuacheck = false -- underscore means "experimental" here } _G.Shutdown = false _G.Initialized = _G.Initialized or false _G.print = function() error("illegal print, use log() instead:", 2) end local function reload_all() for name, _ in pairs(package.loaded) do if name:find("^lua%-lsp") and name ~= 'lua-lsp.log' then package.loaded[name] = nil end end log.verbose("===========================") method_handlers = require 'lua-lsp.methods' end local function main(_) while not Shutdown do -- header local data, err = rpc.decode() if _G.Config.debugMode then reload_all() end if data == nil then if err == "eof" then return os.exit(1) end error(err) elseif data.method then -- request if not method_handlers[data.method] then log.verbose("confused by %t", data) err = string.format("%q: Not found/NYI", tostring(data.method)) if data.id then rpc.respondError(data.id, err, "MethodNotFound") else log.warning("%s", err) end else local ok ok, err = xpcall(function() method_handlers[data.method](data.params, data.id) end, debug.traceback) if not ok then if data.id then rpc.respondError(data.id, err, "InternalError") else log.warning("%s", tostring(err)) end end end elseif data.result then rpc.finish(data) elseif data.error then log("client error:%s", data.error.message) end end end return main --https://code.visualstudio.com/blogs/2016/06/27/common-language-protocol
------------------------------------------------------------------------------- -- @author lilydjwg <lilydjwg@gmail.com> -- @copyright GPLv3 -- vim:se sw=2: ------------------------------------------------------------------------------- require "logging" local LEVEL_PREFIX = { [logging.DEBUG] = '\27[34m[D', [logging.INFO] = '\27[32m[I', [logging.WARN] = '\27[33m[W', [logging.ERROR] = '\27[31m[E', [logging.FATAL] = '\27[31m[F', } function logging.beautifullog(filename, funclevel) if type(filename) ~= "string" then filename = "/dev/stderr" end local f = io.open(filename, "a") if not f then return nil, string.format("file `%s' could not be opened for writing", filename) end f:setvbuf("line") return logging.new(function(self, level, message) local date = os.date("%m-%d %H:%M:%S") local frame = debug.getinfo(funclevel or 4) local s = string.format('%s %s %s:%d]\27[m %s\n', LEVEL_PREFIX[level], date, frame.short_src, frame.currentline, message ) f:write(s) return true end) end
--[[ Config provider module Copyright (c) 2020-2021 outsidepro-arts License: MIT License ]]-- -- Before use this module, please fill the config.section by your unique name which should set to ExtState local config = {} -- A few local functions local function toboolean(value) if type(value) == "string" then return ({["false"] = false, ["true"] = true})[value] else return (value > 0) end end function config.getboolean(key, defvalue) local state = reaper.GetExtState(config.section, "cfg_"..key) if state ~= "" then return toboolean(state) end if defvalue ~= nil then return defvalue end return nil end function config.getinteger(key, defvalue) local state = reaper.GetExtState(config.section, "cfg_"..key) if tonumber(state) then return tonumber(state) end if defvalue then return defvalue end return nil end function config.getstring(key, defvalue) local state = reaper.GetExtState(config.section, "cfg_"..key) if state ~= "" then return state end if defvalue then return defvalue end return nil end function config.setboolean(key, value) reaper.SetExtState(config.section, "cfg_"..key, ({[true] = "true", [false] = "false"})[value], true) end function config.setinteger(key, value) if tonumber(value) then reaper.SetExtState(config.section, "cfg_"..key, tonumber(value), true) else reaper.SetExtState(config.section, "cfg_"..key, 0, true) end end function config.setstring(key, value) reaper.SetExtState(config.section, "cfg_"..key, tostring(value), true) end return config
local responses = require "kong.tools.responses" local singletons = require "kong.singletons" local pl_stringx = require "pl.stringx" local _ = require "lodash" local function load_consumer_resources(consumer_id) local cache = singletons.cache local dao = singletons.dao local role_cache_key = dao.rbac_role_consumers:cache_key(consumer_id) local roles, err = cache:get(role_cache_key, nil, (function(id) return dao.rbac_role_consumers:find_all({ consumer_id = id }) end), consumer_id) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end if table.getn(roles) < 1 then return {} end local resources = {} _.forEach(roles, (function(role) local role_resource_cache_key = dao.rbac_role_resources:cache_key(role.role_id) local role_resources, role_resource_err = cache:get(role_resource_cache_key, nil, (function(role_id) return dao.rbac_role_resources:find_all({ role_id = role_id }) end), role.role_id) if role_resource_err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(role_resource_err) end resources = _.union(resources, role_resources) end)) return resources end local function get_root_consumers() local root_consumers = os.getenv('KONG_RBAC_ROOT_CONSUMERS') if root_consumers then return pl_stringx.split(root_consumers, ',') end return {} end return { load_consumer_resources = load_consumer_resources, get_root_consumers = get_root_consumers }
--[[ --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 file_exists = require("lib-tde.file").exists local split = require("lib-tde.function.common").split local function extract(line) local splitted = split(line, "=") if splitted[1] == nil or splitted[2] == nil then return nil end return splitted[1]:gsub("%s+", ""), splitted[2]:gsub("%s+", ""):gsub('"', ""):gsub("'", ""):gsub("`", "") end local function parse_file(file) local lines = {} for line in io.lines(file) do if not (line:sub(1, 1) == "#") then line = split(line, "#")[1] local data, payload = extract(line) if not (data == nil) then lines[data] = payload end end end return lines end return function(file) if not (type(file) == "string") then return {} end print("Parsing file: " .. file) if file_exists(file) then local result = parse_file(file) print("Finished parsing file: " .. file) return result end return {} end
require("lunatest.lunatest") function test_loads() require("help") assert_table(help) end function test_concat() require("help") local a = help.docstring[[This is an example]] .. function() return "function return value" end assert_function(a) assert_string(a()) end function test_concat_lookup() require("help") local a = help.docstring[[This is an example]] .. function() return "function return value" end assert_string(help.lookup(a)) end function test_concat_twice() require("help") local a = help.docstring[[This is an example]] .. help.docstring[[This is another example]] .. function() return "function return value" end assert_function(a) assert_string(a()) end function test_concat_twice_lookup() require("help") local a = help.docstring[[This is an example]] .. help.docstring[[This is another example]] .. function() return "function return value" end assert_table(help.lookup(a)) assert_len(2, help.lookup(a)) end function test_call() require("help") local function a() return "function return value" end help.docstring[[This is an example]](a) assert_function(a) assert_string(a()) end function test_call_chain() require("help") local function a() return "function return value" end local function b() return 5 end help.docstring[[This is an example]](a)(b) assert_function(a) assert_string(a()) assert_string(help.lookup(a)) assert_function(b) assert_number(b()) assert_string(help.lookup(b)) end function test_call_lookup() require("help") local function a() return "function return value" end help.docstring[[This is an example]](a) assert_string(help.lookup(a)) end function test_call_twice() require("help") local function a() return "function return value" end help.docstring[[This is an example]](a) help.docstring[[This is another example]](a) assert_function(a) assert_string(a()) end function test_call_twice_lookup() require("help") local function a() return "function return value" end help.docstring[[This is an example]](a) help.docstring[[This is another example]](a) assert_table(help.lookup(a)) assert_len(2, help.lookup(a)) end function test_applyto() require("help") local function a() return "function return value" end help.docstring[[This is an example]].applyTo(a) assert_function(a) assert_string(a()) end function test_applyto_chain() require("help") local function a() return "function return value" end local function b() return 5 end help.docstring[[This is an example]].applyTo(a).applyTo(b) assert_function(a) assert_string(a()) assert_string(help.lookup(a)) assert_function(b) assert_number(b()) assert_string(help.lookup(b)) end function test_applyto_lookup() require("help") local function a() return "function return value" end help.docstring[[This is an example]].applyTo(a) assert_string(help.lookup(a)) end function test_applyto_twice() require("help") local function a() return "function return value" end help.docstring[[This is an example]].applyTo(a) help.docstring[[This is another example]].applyTo(a) assert_function(a) assert_string(a()) end function test_applyto_twice_lookup() require("help") local function a() return "function return value" end help.docstring[[This is an example]].applyTo(a) help.docstring[[This is another example]].applyTo(a) assert_table(help.lookup(a)) assert_len(2, help.lookup(a)) end function test_selfdoc_list_of_functions() require("help") assert_gt(#help, 1) assert_not_nil(help.lookup(help), "The help table has no documentation!") local keys = {} local foundKeys = {} for k,v in pairs(help) do table.insert(keys, k) foundKeys[k] = false end for _,v in ipairs(help.lookup(help)["functions"]) do assert_not_nil(foundKeys[v], "Function listed in documentation does not exist: " .. v) assert_false(foundKeys[v], "Function is listed in documentation more than once: " .. v) foundKeys[v] = true end for _,v in ipairs(help.lookup(help)["additionalFeatures"]) do assert_not_nil(foundKeys[v], "additionalFeature listed in documentation does not exist: " .. v) assert_false(foundKeys[v], "additionalFeature is listed in documentation more than once: " .. v) foundKeys[v] = true end for k,v in pairs(foundKeys) do assert_true(v, "Functions/additionalFeatures not listed in documentation for help: " .. k) end end function test_selfdoc_complete() require("help") for k,v in pairs(help) do assert_not_nil(help.lookup(v), "Function help." ..k.. " is not documented") end end function test_selfdoc_gc() require("help") collectgarbage("collect") assert_gt(#help, 1) assert_not_nil(help.lookup(help), "The help table has no documentation following garbage collection!") end function test_nodoc_builtins() require("help") assert_nil(help.lookup(1), "Don't document generic numbers!") assert_nil(help.lookup({}), "Don't document generic tables!") assert_nil(help.lookup(nil), "Don't document nil!") assert_nil(help.lookup("blabla"), "Don't document generic strings!") assert_nil(help.lookup(function() end), "Don't document generic functions!") assert_nil(help.lookup(coroutine.create(function() end)), "Don't document generic coroutines!") end lunatest.run()
include("LensSupport") local LENS_NAME = "ML_WONDER" local ML_LENS_LAYER = LensLayers.HEX_COLORING_APPEAL_LEVEL -- =========================================================================== -- Wonder Lens Support -- =========================================================================== -- =========================================================================== -- Exported functions -- =========================================================================== local function OnGetColorPlotTable() local mapWidth, mapHeight = Map.GetGridSize(); local localPlayer :number = Game.GetLocalPlayer(); local localPlayerVis:table = PlayersVisibility[localPlayer]; local NaturalWonderColor :number = UI.GetColorValue("COLOR_NATURAL_WONDER_LENS"); local PlayerWonderColor :number = UI.GetColorValue("COLOR_PLAYER_WONDER_LENS"); local colorPlot:table = {}; colorPlot[NaturalWonderColor] = {} colorPlot[PlayerWonderColor] = {} for i = 0, (mapWidth * mapHeight) - 1, 1 do local pPlot:table = Map.GetPlotByIndex(i); if localPlayerVis:IsRevealed(pPlot:GetX(), pPlot:GetY()) then -- check for player wonder. if plotHasWonder(pPlot) then table.insert(colorPlot[PlayerWonderColor], i); else -- Check for natural wonder local featureInfo = GameInfo.Features[pPlot:GetFeatureType()]; if featureInfo ~= nil and featureInfo.NaturalWonder then table.insert(colorPlot[NaturalWonderColor], i) end end end end return colorPlot end --[[ local function ShowWonderLens() LuaEvents.MinimapPanel_SetActiveModLens(LENS_NAME) UILens.ToggleLayerOn(ML_LENS_LAYER) end local function ClearWonderLens() if UILens.IsLayerOn(ML_LENS_LAYER) then UILens.ToggleLayerOff(ML_LENS_LAYER); end LuaEvents.MinimapPanel_SetActiveModLens("NONE"); end local function OnInitialize() -- Nothing to do end ]] local WonderLensEntry = { LensButtonText = "LOC_HUD_WONDER_LENS", LensButtonTooltip = "LOC_HUD_WONDER_LENS_TOOLTIP", Initialize = nil, GetColorPlotTable = OnGetColorPlotTable } -- minimappanel.lua if g_ModLenses ~= nil then g_ModLenses[LENS_NAME] = WonderLensEntry end -- modallenspanel.lua if g_ModLensModalPanel ~= nil then g_ModLensModalPanel[LENS_NAME] = {} g_ModLensModalPanel[LENS_NAME].LensTextKey = "LOC_HUD_WONDER_LENS" g_ModLensModalPanel[LENS_NAME].Legend = { {"LOC_TOOLTIP_WONDER_LENS_NWONDER", UI.GetColorValue("COLOR_NATURAL_WONDER_LENS")}, {"LOC_TOOLTIP_RESOURCE_LENS_PWONDER", UI.GetColorValue("COLOR_PLAYER_WONDER_LENS")} } end
-- ============================================= -- -== TODO Comments ==- -- ============================================= local todo_comments = require("todo-comments") local colors = require("tokyonight.colors").setup({}) todo_comments.setup({ signs = true, sign_priority = 8, keywords = { FIX = { icon = " ", color = "error", alt = { "FIXME", "BUG", "FIXIT", "ISSUE" }, -- signs = false, }, TODO = { icon = " ", color = "info" }, NOTE = { icon = " ", color = "hint", alt = { "INFO" } }, }, merge_keywords = true, -- highlighting of the line containing the todo comment -- * before: highlights before the keyword (typically comment characters) -- * keyword: highlights of the keyword -- * after: highlights after the keyword (todo text) highlight = { before = "", -- "fg" or "bg" or empty keyword = "fg", -- "fg", "bg", "wide" or empty. after = "fg", -- "fg" or "bg" or empty pattern = [[.*<(KEYWORDS)\s*:]], -- Vim regex comments_only = true, max_line_len = 400, -- ignore lines longer than this exclude = {}, -- list of file types to exclude highlighting }, -- list of named colors where we try to extract the guifg from the -- list of hilight groups or use the hex color if hl not found as a fallback colors = { error = { "DiagnosticError", "ErrorMsg", colors.red }, info = { "DiagnosticInfo", colors.green }, hint = { "DiagnosticHint", colors.blue2 }, }, search = { command = "rg", args = { "--color=never", "--no-heading", "--with-filename", "--line-number", "--column", }, pattern = [[\b(KEYWORDS):]], }, })
-- Copyright (C) 2017-2020 DBotThePony -- 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 meta = DLib.FindMetaTable('HUDCommonsBase') local DLib = DLib local HUDCommons = HUDCommons local LocalPlayer = LocalPlayer local NULL = NULL local type = type local assert = assert local RealTimeL = RealTimeL local CurTimeL = CurTimeL local math = math local IsValid = FindMetaTable('Entity').IsValid --[[ @doc @fname HUDCommonsBase:MimicPlayer @args Player targetOrNil @client @desc Makes `HUDCommonsBase:SelectPlayer()` return different player @enddesc ]] function meta:MimicPlayer(playerTarget) if not playerTarget then if IsValid(self.mimic) then self:MimicEnd(self.mimic, LocalPlayer()) end self.mimic = NULL return end assert(type(playerTarget) == 'Player', 'MimicPlayer - input is not a target!') if self.mimic == playerTarget then return end self.mimic = playerTarget self.prevWeapon = self:GetWeapon() self.currWeaponTrack = self.prevWeapon self:MimicStart(IsValid(self.mimic) and self.mimic or LocalPlayer(), playerTarget) end --[[ @doc @fname HUDCommonsBase:MimicStart @args Player oldPlayer, Player newPlayer @client @desc that's a hook! override it if you want to. @enddesc ]] function meta:MimicStart(oldPlayer, newPlayer) end --[[ @doc @fname HUDCommonsBase:MimicEnd @args Player oldPlayer, Player newPlayer @client @desc that's a hook! override it if you want to. @enddesc ]] function meta:MimicEnd(oldPlayer, newPlayer) end --[[ @doc @fname HUDCommonsBase:SelectPlayer @client @returns Player ]] function meta:SelectPlayer() if IsValid(self.mimic) then return self.mimic end return HUDCommons.SelectPlayer() end meta.LocalPlayer = meta.SelectPlayer meta.GetPlayer = meta.SelectPlayer --[[ @doc @fname HUDCommonsBase:TickLogic @args Player ply @client @internal ]] function meta:TickLogic(lPly) local wep = self:GetWeapon() if self.currWeaponTrack ~= wep then self:CallOnWeaponChanged(self.currWeaponTrack, wep) self:OnWeaponChanged(self.currWeaponTrack, wep) self.prevWeapon = self.currWeaponTrack self.currWeaponTrack = wep end end --[[ @doc @fname HUDCommonsBase:ThinkLogic @args Player ply @client @internal ]] function meta:ThinkLogic(lPly) if self.glitching then local timeLeft = self:GlitchTimeRemaining() self.glitching = timeLeft ~= 0 if self.glitching then -- lets make it a big faster local vars = self.variables for i = 1, #vars do local entry = vars[i] local grab = entry.onGlitch(entry.self, self, lPly, timeLeft) end else self:CallOnGlitchEnd() self:OnGlitchEnd() end end end --[[ @doc @fname HUDCommonsBase:OnGlitchStart @args number timeLong @client @desc that's a hook! override it if you want to. @enddesc ]] function meta:OnGlitchStart(timeLong) end --[[ @doc @fname HUDCommonsBase:OnGlitchEnd @client @desc that's a hook! override it if you want to. @enddesc ]] function meta:OnGlitchEnd() end --[[ @doc @fname HUDCommonsBase:TriggerGlitch @args number timeLong @client @desc forces a HUD to glitch. does nothing if HUD does not support glitching. @enddesc ]] function meta:TriggerGlitch(timeLong) local old = self.glitchEnd self.glitchEnd = math.max(self.glitchEnd, CurTimeL() + timeLong) if not self.glitching then self.glitching = true self.glitchingSince = CurTimeL() self:CallOnGlitchStart(timeLong) self:OnGlitchStart(timeLong) end return old ~= self.glitchEnd end --[[ @doc @fname HUDCommonsBase:ExtendGlitch @args number timeLong @client @desc extends current glitch or starts a new one if not glitching. does nothing if HUD does not support glitching. @enddesc ]] function meta:ExtendGlitch(timeLong) self.glitchEnd = math.max(self.glitchEnd + timeLong, CurTimeL() + timeLong) if not self.glitching then self.glitching = true self.glitchingSince = CurTimeL() self:CallOnGlitchStart(timeLong) self:OnGlitchStart(timeLong) end return true end --[[ @doc @fname HUDCommonsBase:ClampGlitchTime @args number maximal @client @desc clamps current glitch time to given amount of seconds starting from now @enddesc ]] function meta:ClampGlitchTime(maximal) local old = self.glitchEnd self.glitchEnd = self.glitchEnd:min(CurTimeL() + maximal) return self.glitchEnd ~= old end --[[ @doc @fname HUDCommonsBase:GlitchTimeRemaining @client @returns number ]] function meta:GlitchTimeRemaining() return math.max(0, self.glitchEnd - CurTimeL()) end --[[ @doc @fname HUDCommonsBase:GlitchingSince @client @returns number ]] function meta:GlitchingSince() return self.glitchingSince end --[[ @doc @fname HUDCommonsBase:GlitchingFor @client @returns number ]] function meta:GlitchingFor() return CurTimeL() - self.glitchingSince end --[[ @doc @fname HUDCommonsBase:IsGlitching @client @returns boolean ]] function meta:IsGlitching() return self.glitching end --[[ @doc @fname HUDCommonsBase:OnWeaponChanged @args Weapon old, Weapon new @client @desc that's a hook! override it if you want to. @enddesc ]] function meta:OnWeaponChanged(old, new) end --[[ @doc @fname HUDCommonsBase:DrawWeaponSelection @args Weapon wep @client @internal ]] function meta:DrawWeaponSelection(wep) self.tryToSelectWeapon = wep if self.tryToSelectWeaponLast < RealTimeL() then self.tryToSelectWeaponFadeIn = RealTimeL() + 0.5 end self.tryToSelectWeaponLast = RealTimeL() + 0.75 self.tryToSelectWeaponLastEnd = RealTimeL() + 1.25 end
local playsession = { {"Gerkiz", {6962}}, {"sickmyduck90", {1828967}}, {"bugmum", {153268}}, {"fabilord98", {1308116}}, {"Ardordo", {86936}}, {"Zorzzz", {1766697}}, {"Nikkichu", {1246953}}, {"vad7ik", {842508}}, {"IamTzu", {319808}}, {"Skybreaker", {765517}}, {"3615-Motiok", {1251318}}, {"CommanderFrog", {280070}}, {"vvictor", {826784}}, {"Roboto_Slab", {14429}}, {"RedPandaRam", {346757}}, {"Xoxlohunter", {558}}, {"mewmew", {714493}}, {"1qazplm", {295548}}, {"Joost98", {679969}}, {"marrygrim", {1111183}}, {"DoubleDough", {21995}}, {"mzore", {857616}}, {"everLord", {648989}}, {"Olekplane1", {381851}}, {"helic99", {459429}}, {"autopss", {387626}}, {"wertter", {37490}}, {"MaxMM", {28398}}, {"chrisisthebe", {1049071}}, {"ksb4145", {151687}}, {"PhoenixwingzZ", {2335}}, {"salman0540", {3873}}, {"Guitoune", {38605}}, {"poofies", {54930}}, {"kevinma", {435474}}, {"Higgel", {2319}}, {"kaimix", {1261006}}, {"COOL-ITEM", {340834}}, {"mouriis", {397693}}, {"Datixo", {15930}}, {"Tamika", {129856}}, {"jagger23", {166109}}, {"J7cuxolor", {609443}}, {"Hunter20nov", {45341}}, {"flooxy", {162006}}, {"Lolo212003", {244942}}, {"settan", {557514}}, {"bdgray02", {259206}}, {"dog80", {358365}}, {"Scuideie-Guy", {251720}}, {"Hiero", {1362550}}, {"nik12111", {82876}}, {"Komoteh", {331051}}, {"rlidwka", {43455}}, {"EPO666", {104000}}, {"nudletje", {228050}}, {"spinxt", {567517}}, {"Glexanice", {7357}}, {"shadewolf", {24111}}, {"beranabus", {15543}}, {"Ethnik", {8843}}, {"ChinaNumba1", {740798}}, {"maxxcz", {390888}}, {"romsmano", {15669}}, {"lorrel", {166228}}, {"302180743", {5222}}, {"nankinanki", {2912}}, {"raskl", {29750}}, {"okan009", {586428}}, {"tundragrass", {68276}}, {"UTIDI", {1744}}, {"shorthair39", {9111}}, {"Gh0sty", {26730}}, {"jaja56", {94250}}, {"KanedaNLD", {471830}}, {"LazyStingray", {660359}}, {"Derwitze", {972303}}, {"sailorkid35", {22145}}, {"EarlOfLemongrab", {2381}}, {"arsindex", {12445}}, {"karl93", {30651}}, {"snoetje", {8271}}, {"sschippers", {34870}}, {"djclarky", {710217}}, {"Dofolo", {14037}}, {"Drlloyd1337", {1136}}, {"exabyte", {5691}}, {"Consult", {36919}}, {"Griffinplays", {560130}}, {"Bryce940", {40001}}, {"thederpyloco", {32860}}, {"mugscraft", {20819}}, {"Spad889", {265}}, {"Jaskarox", {291}}, {"moocat12", {23810}}, {"SuddenDeathMP", {605590}}, {"seirjgkemn", {2414}}, {"Darkmenik", {85533}}, {"Ubilaz", {121167}}, {"Pa450", {374260}}, {"Siphon098", {20801}}, {"ScubaSteveTM", {3281}}, {"Piewdennis", {263524}}, {"sukram72", {10910}}, {"alexbw", {130010}}, {"cawsey21", {99425}} } return playsession
local THNN = require 'nn.THNN' local SpatialConvolution, parent = torch.class('SpatialConvolution', 'nn.Module') function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH, magnitude) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.feedback = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) self.backprop = false self.mag = magnitude or 0 self:reset() end function SpatialConvolution:noBias() self.bias = nil self.gradBias = nil return self end function SpatialConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) if self.bias then self.bias:apply(function() return torch.uniform(-stdv, stdv) end) end else self.weight:uniform(-stdv, stdv) if self.bias then self.bias:uniform(-stdv, stdv) end end if self.mag == 0 then self.feedback:copy(self.weight) self.mag = stdv else self.feedback:uniform(-self.mag,self.mag) end end local function backCompatibility(self) self.finput = self.finput or self.weight.new() self.fgradInput = self.fgradInput or self.weight.new() if self.padding then self.padW = self.padding self.padH = self.padding self.padding = nil else self.padW = self.padW or 0 self.padH = self.padH or 0 end if self.weight:dim() == 2 then self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.feedback:dim() == 2 then self.feedback = self.feedback:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end if self.gradWeight and self.gradWeight:dim() == 2 then self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end function SpatialConvolution:updateOutput(input) assert(input.THNN, torch.type(input)..'.THNN backend not imported') backCompatibility(self) input.THNN.SpatialConvolutionMM_updateOutput( input:cdata(), self.output:cdata(), self.weight:cdata(), THNN.optionalTensor(self.bias), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH ) return self.output end function SpatialConvolution:updateGradInput(input, gradOutput) assert(input.THNN, torch.type(input)..'.THNN backend not imported') if self.gradInput then backCompatibility(self) if self.backprop==false then input.THNN.SpatialConvolutionMM_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.feedback:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH ) else input.THNN.SpatialConvolutionMM_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH ) end return self.gradInput end end function SpatialConvolution:accGradParameters(input, gradOutput, scale) assert(input.THNN, torch.type(input)..'.THNN backend not imported') scale = scale or 1 backCompatibility(self) input.THNN.SpatialConvolutionMM_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), THNN.optionalTensor(self.gradBias), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH, scale ) end function SpatialConvolution:type(type,tensorCache) self.finput = self.finput and torch.Tensor() self.fgradInput = self.fgradInput and torch.Tensor() return parent.type(self,type,tensorCache) end function SpatialConvolution:__tostring__() local s = string.format('%s(%d -> %d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end if self.bias then return s .. ')' else return s .. ') without bias' end end function SpatialConvolution:clearState() nn.utils.clear(self, 'finput', 'fgradInput', '_input', '_gradOutput') return parent.clearState(self) end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file archive.lua -- -- imports import("core.base.option") import("lib.detect.find_file") import("lib.detect.find_tool") import("extension", {alias = "get_archive_extension"}) -- archive archivefile using zip function _archive_using_zip(archivefile, inputfiles, extension, opt) -- find zip local zip = find_tool("zip") if not zip then return false end -- init argv local argv = {archivefile} if not option.get("verbose") then table.insert(argv, "-q") end if opt.excludes then table.insert(argv, "-x") for _, exclude in ipairs(opt.excludes) do table.insert(argv, exclude) end end local compress = opt.compress if compress then if compress == "faster" or compress == "fastest" then table.insert(argv, "-1") elseif compress == "better" or compress == "best" then table.insert(argv, "-9") end end if opt.recurse then table.insert(argv, "-r") end local inputlistfile = os.tmpfile() if type(inputfiles) == "table" then local file = io.open(inputlistfile, "w") for _, inputfile in ipairs(inputfiles) do file:print(inputfile) end file:close() table.insert(argv, "-@") table.insert(argv, "-") else table.insert(argv, inputfiles) end -- archive it os.vrunv(zip.program, argv, {curdir = opt.curdir, stdin = inputlistfile}) if inputlistfile then os.tryrm(inputlistfile) end return true end -- archive archivefile using 7z function _archive_using_7z(archivefile, inputfiles, extension, opt) -- find 7z local z7 = find_tool("7z") if not z7 then return false end -- init argv local argv = {"a", archivefile, "-y"} local excludesfile if opt.excludes then excludesfile = os.tmpfile() io.writefile(excludesfile, table.concat(table.wrap(opt.excludes), '\n')) table.insert(argv, "-xr@" .. excludesfile) end local compress = opt.compress if compress then if compress == "fastest" then table.insert(argv, "-mx1") elseif compress == "faster" then table.insert(argv, "-mx3") elseif compress == "better" then table.insert(argv, "-mx7") elseif compress == "best" then table.insert(argv, "-mx9") end end if opt.recurse then table.insert(argv, "-r") end local inputlistfile = os.tmpfile() if type(inputfiles) == "table" then local file = io.open(inputlistfile, "w") for _, inputfile in ipairs(inputfiles) do file:print(inputfile) end file:close() table.insert(argv, "-i@" .. inputlistfile) else table.insert(argv, inputfiles) end -- archive it os.vrunv(z7.program, argv, {curdir = opt.curdir}) -- remove the excludes files if excludesfile then os.tryrm(excludesfile) end if inputlistfile then os.tryrm(inputlistfile) end return true end -- archive archivefile using xz function _archive_using_xz(archivefile, inputfiles, extension, opt) -- find xz local xz = find_tool("xz") if not xz then return false end -- init argv local argv = {"-z", "-k", "-c", archivefile} if not option.get("verbose") then table.insert(argv, "-q") end local compress = opt.compress if compress then if compress == "fastest" then table.insert(argv, "-1") elseif compress == "faster" then table.insert(argv, "-3") elseif compress == "better" then table.insert(argv, "-7") elseif compress == "best" then table.insert(argv, "-9") end end if type(inputfiles) == "table" then for _, inputfile in ipairs(inputfiles) do table.insert(argv, inputfile) end else table.insert(argv, inputfiles) end -- archive it os.vrunv(xz.program, argv, {stdout = archivefile, curdir = opt.curdir}) return true end -- archive archivefile using gzip function _archive_using_gzip(archivefile, inputfiles, extension, opt) -- find gzip local gzip = find_tool("gzip") if not gzip then return false end -- init argv local argv = {"-k", "-c", archivefile} if not option.get("verbose") then table.insert(argv, "-q") end local compress = opt.compress if compress then if compress == "fastest" then table.insert(argv, "-1") elseif compress == "faster" then table.insert(argv, "-3") elseif compress == "better" then table.insert(argv, "-7") elseif compress == "best" then table.insert(argv, "-9") end end if opt.recurse then table.insert(argv, "-r") end if type(inputfiles) == "table" then for _, inputfile in ipairs(inputfiles) do table.insert(argv, inputfile) end else table.insert(argv, inputfiles) end -- archive it os.vrunv(gzip.program, argv, {stdout = archivefile, curdir = opt.curdir}) return true end -- archive archivefile using tar function _archive_using_tar(archivefile, inputfiles, extension, opt) -- find tar local tar = find_tool("tar") if not tar then return false end -- with compress? e.g. .tar.xz local compress = false local archivefile_tar if extension ~= ".tar" then if is_host("windows") then return false else compress = true archivefile_tar = path.join(path.directory(archivefile), path.basename(archivefile)) end end -- init argv local argv = {} if compress then table.insert(argv, "-a") end if option.get("verbose") then table.insert(argv, "-cvf") else table.insert(argv, "-cf") end table.insert(argv, archivefile_tar and archivefile_tar or archivefile) if opt.excludes then for _, exclude in ipairs(opt.excludes) do table.insert(argv, "--exclude=") table.insert(argv, exclude) end end if not opt.recurse then table.insert(argv, "-n") end local inputlistfile = os.tmpfile() if type(inputfiles) == "table" then local file = io.open(inputlistfile, "w") for _, inputfile in ipairs(inputfiles) do file:print(inputfile) end file:close() table.insert(argv, "-T") table.insert(argv, inputlistfile) else table.insert(argv, inputfiles) end -- archive it os.vrunv(tar.program, argv, {curdir = opt.curdir}) if inputlistfile then os.tryrm(inputlistfile) end if archivefile_tar and os.isfile(archivefile_tar) then _archive_tarfile(archivefile, archivefile_tar, opt) os.rm(archivefile_tar) end return true end -- archive archive file using archivers function _archive(archivefile, inputfiles, extension, archivers, opt) for _, archive in ipairs(archivers) do if archive(archivefile, inputfiles, extension, opt) then return true end end return false end -- only archive tar file function _archive_tarfile(archivefile, tarfile, opt) local archivers = { [".xz"] = {_archive_using_xz} , [".gz"] = {_archive_using_gzip} } local extension = opt.extension or path.extension(archivefile) return _archive(archivefile, tarfile, extension, archivers[extension], opt) end -- archive archive file -- -- @param archivefile the archive file. e.g. *.tar.gz, *.zip, *.7z, *.tar.bz2, .. -- @param inputfiles the input file or directory or list -- @param options the options, e.g.. {curdir = "/tmp", recurse = true, compress = "fastest|faster|default|better|best", excludes = {"*/dir/*", "dir/*"}} -- function main(archivefile, inputfiles, opt) -- init inputfiles inputfiles = inputfiles or os.curdir() -- init options opt = opt or {} if opt.recurse == nil then opt.recurse = true end -- init archivers local archivers = { [".zip"] = {_archive_using_zip, _archive_using_7z} , [".7z"] = {_archive_using_7z} , [".xz"] = {_archive_using_xz} , [".gz"] = {_archive_using_gzip} , [".tar"] = {_archive_using_tar} , [".tar.gz"] = {_archive_using_tar, _archive_using_gzip} , [".tar.xz"] = {_archive_using_tar, _archive_using_xz} } -- get extension local extension = opt.extension or get_archive_extension(archivefile) -- archive it return _archive(archivefile, inputfiles, extension, archivers[extension], opt) end
local presetsFolder = script.Parent local GenericWeatherPreset = require(presetsFolder:WaitForChild("GenericWeatherPreset")) local SnowstormDay = {} SnowstormDay.__index = SnowstormDay setmetatable(SnowstormDay, GenericWeatherPreset) function SnowstormDay.new() local self = GenericWeatherPreset.new() setmetatable(self, SnowstormDay) self._Services = { [game:GetService("Lighting")] = { Ambient = Color3.fromRGB(70, 70, 70); Brightness = 3; ColorShift_Bottom = Color3.fromRGB(0, 0, 0); ColorShift_Top = Color3.fromRGB(0, 0, 0); EnvironmentDiffuseScale = 1; EnvironmentSpecularScale = 1; OutdoorAmbient = Color3.fromRGB(70, 70, 70); ShadowSoftness = 1; ClockTime = 14.5; GeographicLatitude = 0; ExposureCompensation = 0; }; }; self._WeatherGlobals = { _Clouds = { Parent = workspace.Terrain; ClassName = "Clouds"; Cover = 1; Density = 0.369; Color = Color3.fromRGB(221, 221, 221) }; _Atmosphere = { Parent = game:GetService("Lighting"); ClassName = "Atmosphere"; Density = 0.462; Offset = 0; Color = Color3.fromRGB(124, 127, 130); Decay = Color3.fromRGB(207, 215, 220); Glare = 0.31; Haze = 10; }; _ColorCorrectionEffect = { Parent = game:GetService("Lighting"); ClassName = "ColorCorrectionEffect"; Brightness = 0; Contrast = 0.3; Saturation = 0; TintColor = Color3.fromRGB(195, 205, 218) } }; self._Sounds = { ["Snow"] = { Volume = 0.2; Looped = true; SoundId = "rbxassetid://6670282148"; } }; --Presets can include other presets self._PresetDependencies = {}; self._ActivePresets = {}; self._Connections = {}; return self end function SnowstormDay:_Initialize() GenericWeatherPreset._Initialize(self) local grid = self.AtmosphericParticleGrid.new(12, 11, 1, 75, self.ParticleLayers.SnowParticles) table.insert(self._ActiveParticleGrids, grid) end return SnowstormDay
local classes = { [0] = 'None', [1] = { -- Warrior [1] = 'Arms', [2] = 'Fury', [3] = 'Protection' }, [2] = { -- Paladin [1] = 'Holy', [2] = 'Protection', [3] = 'Retribution' }, [3] = { -- Hunter [1] = 'BeastMastery', [2] = 'Marksmanship', [3] = 'Survival' }, [4] = { -- Rogue [1] = 'Assassination', [2] = 'Outlaw', [3] = 'Subtlety' }, [5] = { -- Priest [1] = 'Discipline', [2] = 'Holy', [3] = 'Shadow' }, [6] = { -- Death Knight [1] = 'Blood', [2] = 'Frost', [3] = 'Unholy' }, [7] = { -- Shaman [1] = 'Elemental', [2] = 'Enhancement', [3] = 'Restoration' }, [8] = { -- Mage [1] = 'Arcane', [2] = 'Fire', [3] = 'Frost' }, [9] = { -- Warlock [1] = 'Affliction', [2] = 'Demonology', [3] = 'Destruction' }, [10] = { -- Monk [1] = 'Brewmaster', [2] = 'Mistweaver', [3] = 'Windwalker' }, [11] = { -- Druid [1] = 'Balance', [2] = 'Feral', [3] = 'Guardian', [4] = 'Restoration' }, [12] = { -- Demon Hunter [1] = 'Havoc', [2] = 'Vengeance' } } function ColoredCrit(percents) return CreateColor(unpack(aura_env.config.criticalColor)):WrapTextInColorCode(percents) end function ColoredHaste(percents) return CreateColor(unpack(aura_env.config.hasteColor)):WrapTextInColorCode(percents) end function ColoredMastery(percents) return CreateColor(unpack(aura_env.config.masteryColor)):WrapTextInColorCode(percents) end function ColoredVersality(percents) return CreateColor(unpack(aura_env.config.versalityColor)):WrapTextInColorCode(percents) end function ColoredLeech(percents) return CreateColor(unpack(aura_env.config.leechColor)):WrapTextInColorCode(percents) end function ColoredDodge(percents) return CreateColor(unpack(aura_env.config.dodgeColor)):WrapTextInColorCode(percents) end function ColoredParry(percents) return CreateColor(unpack(aura_env.config.parryColor)):WrapTextInColorCode(percents) end function ColoredAvoidance(percents) return CreateColor(unpack(aura_env.config.avoidanceColor)):WrapTextInColorCode(percents) end function ColoredBlock(percents) return CreateColor(unpack(aura_env.config.blockColor)):WrapTextInColorCode(percents) end function GetLeech() local leechPercent = 'Leech: '..string.format('%.2f%%', GetLifesteal()) return ColoredLeech(leechPercent) end function GetDodge() local dodgePercent = 'Dodge: '..string.format('%.2f%%', GetDodgeChance()) return ColoredDodge(dodgePercent) end function GetParry() local parryPercent = 'Parry: '..string.format('%.2f%%', GetParryChance()) return ColoredParry(parryPercent) end function GetAvoidance() local avoidancePercent = 'Avoid: '..string.format('%.2f%%', GetCombatRatingBonus(CR_AVOIDANCE)) return ColoredAvoidance(avoidancePercent) end function GetBlock() local blockPercent = 'Block: '..string.format('%.2f%%', GetBlockChance()) return ColoredBlock(blockPercent) end function GetStats() local critPercent = 'Crit: '..string.format('%.1f%%', GetSpellCritChance(2)) local hastePercent = 'Haste: '..string.format('%.1f%%', GetHaste()) local masteryPercent = 'Mastery: '..string.format('%.1f%%', GetMasteryEffect()) local versatilityDBPercent = string.format('%.2f%%', (GetCombatRatingBonus(CR_VERSATILITY_DAMAGE_DONE) + GetVersatilityBonus(CR_VERSATILITY_DAMAGE_DONE))); local versatilityDTRPercent = string.format('%.2f%%', (GetCombatRatingBonus(CR_VERSATILITY_DAMAGE_TAKEN) + GetVersatilityBonus(CR_VERSATILITY_DAMAGE_TAKEN))); local versality = 'Versa: '..versatilityDBPercent..' / '..versatilityDTRPercent local constantStats = ColoredCrit(critPercent)..'\n'..ColoredHaste(hastePercent)..'\n'..ColoredMastery(masteryPercent)..'\n'..ColoredVersality(versality) local classIndex = select(3, UnitClass('player')); local currentSpec = GetSpecialization() local playerClass = classes[classIndex] local playerSpec = playerClass[currentSpec] if playerClass == 'None' then return false end if aura_env.config['showSpecifics'] then if classIndex == 1 then if playerSpec == 'Protection' then return constantStats..'\n'..GetDodge()..'\n'..GetParry()..'\n'..GetBlock() end end if classIndex == 2 then if playerSpec == 'Protection' then return constantStats..'\n'..GetDodge()..'\n'..GetParry()..'\n'..GetBlock() end end if classIndex == 4 then if playerSpec == 'Subtlety' then return constantStats..'\n'..GetLeech() end end if classIndex == 8 then if playerSpec == 'Fire' then return constantStats..'\n'..GetLeech() end end if classIndex == 10 then if playerSpec == 'Brewmaster' then return constantStats..'\n'..GetParry()..'\n'..GetDodge() end end if classIndex == 11 then if playerSpec == 'Balance' then return constantStats..'\n'..GetLeech() end if playerSpec == 'Feral' then return constantStats..'\n'..GetLeech() end if playerSpec == 'Guardian' then return constantStats..'\n'..GetLeech()..'\n'..GetAvoidance()..'\n'..GetDodge() end if playerSpec == 'Restoration' then return constantStats..'\n'..GetLeech() end end if classIndex == 12 then if playerSpec == 'Havoc' then return constantStats..'\n'..GetLeech() end if playerSpec == 'Vengeance' then return constantStats..'\n'..GetParry() end end else return constantStats end end
-- *********************************************************************************************************************** -- THIS IS THE CODE FOR THE PLAYER -- *********************************************************************************************************************** player = {} -- create player table -- *********************************************************************************************************************** function player:load() -- get images for the player and store them in a table player_images = {} player_images.front = love.graphics.newImage("assets/img/PC_Christmas_Front_small.png") player_images.right = love.graphics.newImage("assets/img/PC_Christmas_Right_small.png") player_images.left = love.graphics.newImage("assets/img/PC_Christmas_Left_small.png") player_images.back = love.graphics.newImage("assets/img/PC_Christmas_Front_small.png") -- player initialization self.x = 100 -- start x position self.y = 100 -- start y position self.height = player_images.front:getHeight() -- get image height self.width = player_images.front:getWidth() -- get image width self.speed = 500 -- movement speed factor self.direction = "down" end -- *********************************************************************************************************************** function player:update(dt) -- player movement control if love.keyboard.isDown("right") and remaining_time > 0 then self.x = self.x + self.speed * dt player.direction = "right" elseif love.keyboard.isDown("left") and remaining_time > 0 then self.x = self.x - self.speed * dt player.direction = "left" elseif love.keyboard.isDown("down") and remaining_time > 0 then self.y = self.y + self.speed *dt player.direction = "down" elseif love.keyboard.isDown("up") and remaining_time > 0 then self.y = self.y - self.speed * dt player.direction = "up" end -- prevent player to move out of screen if self.x < 0 then self.x = 0 elseif self.y < 0 then self.y = 0 elseif self.x + self.width > love.graphics.getWidth() then self.x = love.graphics.getWidth() - self.width elseif self.y + self.height > love.graphics.getHeight() then self.y = love.graphics.getHeight() - self.height end if enemy_collision and (player.direction == "right" or player.direction == "down") then self.x = self.x - 200 elseif enemy_collision and (player.direction == "left" or player.direction == "up") then self.x = self.x + 200 end end -- *********************************************************************************************************************** function player:draw() -- show respective player image local img = player_images.front if self.direction == "right" then img = player_images.right elseif self.direction == "left" then img = player_images.left elseif self.direction == "down" then img = player_images.front elseif self.direction == "up" then img = player_images.back end love.graphics.draw(img, self.x, self.y) end
local LibProcessable = LibStub("LibProcessable") local isOpening_lock = false -- semaphor to keep us from recursively checking local delayBetweenSearches = 0.75 -- seconds (not MS) to wait between bag opens -- // TODO don't try to open if you're talking to a vendor local function IsPouch(container, slot) local texture, count, locked, quality, readable, lootable, itemLink = GetContainerItemInfo(container, slot) if itemLink == nil then return false end if lootable == false then return false end local itemId = GetContainerItemID(container, slot) -- warped-pocket-dimension, I feel like this was made specifically to mess with me :) if itemId == 190382 then return false end for lockedItemId, _lockpickingSkillRequired in pairs(LibProcessable.containers) do if lockedItemId == itemId then return false end end return true end local function OpenNextPouch() -- print("Looking for pouches") for container = BACKPACK_CONTAINER, NUM_BAG_SLOTS do for slot = 1, GetContainerNumSlots(container) do if IsPouch(container, slot) == true then -- print("Opening ", itemLink) UseContainerItem(container, slot) C_Timer.After(delayBetweenSearches, OpenNextPouch) return end end end isOpening_lock = false end local function OpenAllPouchesEventually() if isOpening_lock == true then return end isOpening_lock = true -- print("scheduling") C_Timer.After(delayBetweenSearches, OpenNextPouch) end -- invisible frame for hooking events local f = CreateFrame("frame") f:SetScript("OnEvent", OpenAllPouchesEventually) f:RegisterEvent("ITEM_PUSH")
script.Parent = nil game.DescendantAdded:connect(function(a) pcall(function() if a:FindFirstChild("DSource") ~= nil then if a.DSource.Value:lower():match("cba") then a:Remove() Instance.new("Message", Workspace).Text = "No CBA fgt." end end end) end)
-------------------------------- -- @module EventListenerPhysicsContactWithBodies -- @extend EventListenerPhysicsContact -- @parent_module cc ---@class cc.EventListenerPhysicsContactWithBodies:cc.EventListenerPhysicsContact local EventListenerPhysicsContactWithBodies = {} cc.EventListenerPhysicsContactWithBodies = EventListenerPhysicsContactWithBodies -------------------------------- --- ---@param shapeA cc.PhysicsShape ---@param shapeB cc.PhysicsShape ---@return boolean function EventListenerPhysicsContactWithBodies:hitTest(shapeA, shapeB) end -------------------------------- --- Create the listener. ---@param bodyA cc.PhysicsBody ---@param bodyB cc.PhysicsBody ---@return cc.EventListenerPhysicsContactWithBodies function EventListenerPhysicsContactWithBodies:create(bodyA, bodyB) end -------------------------------- --- ---@return cc.EventListenerPhysicsContactWithBodies function EventListenerPhysicsContactWithBodies:clone() end return nil
require("mod.tools.data.keybind")
local lsp = { handlers = {} } local util = require"lean._util" function lsp.enable(opts) opts.handlers = vim.tbl_extend("keep", opts.handlers or {}, { ['$/lean/fileProgress'] = util.mk_handler(lsp.handlers.file_progress_handler); ['textDocument/publishDiagnostics'] = function(...) util.mk_handler(lsp.handlers.diagnostics_handler)(...) vim.lsp.handlers['textDocument/publishDiagnostics'](...) end; }) if vim.version().major == 0 and vim.version().minor >= 6 then -- workaround for https://github.com/neovim/neovim/issues/16624 opts.flags = vim.tbl_extend('keep', opts.flags or {}, { allow_incremental_sync = false }) end require('lspconfig').leanls.setup(opts) end --- Finds the vim.lsp.client object for the Lean 4 server associated to the --- given bufnr. function lsp.get_lean4_server(bufnr) local lean_client vim.lsp.for_each_buffer_client(bufnr, function (client) if client.name == 'leanls' then lean_client = client end end) return lean_client end --- Finds the vim.lsp.client object for the Lean 3 server associated to the --- given bufnr. function lsp.get_lean3_server(bufnr) local lean_client vim.lsp.for_each_buffer_client(bufnr, function (client) if client.name == 'lean3ls' then lean_client = client end end) return lean_client end -- Fetch goal state information from the server (async). ---@param params PlainGoalParams ---@param bufnr number ---@return any error ---@return any plain_goal function lsp.plain_goal(params, bufnr) local client = lsp.get_lean4_server(bufnr) or lsp.get_lean3_server(bufnr) if not client then return 'LSP server not connected', nil end params = vim.deepcopy(params) -- Shift forward by 1, since in vim it's easier to reach word -- boundaries in normal mode. params.position.character = params.position.character + 1 return util.client_a_request(client, '$/lean/plainGoal', params) end -- Fetch term goal state information from the server (async). ---@param params PlainTermGoalParams ---@param bufnr number ---@return any error ---@return any plain_term_goal function lsp.plain_term_goal(params, bufnr) local client = lsp.get_lean4_server(bufnr) if not client then return 'LSP server not connected', nil end return util.client_a_request(client, '$/lean/plainTermGoal', params) end function lsp.handlers.file_progress_handler(err, params) if err ~= nil then return end require"lean.progress".update(params) require"lean.infoview".__update_event(params.textDocument.uri) require"lean.progress_bars".update(params) end function lsp.handlers.diagnostics_handler (_, params) -- Make sure there are no zero-length diagnostics. for _, diag in pairs(params.diagnostics) do ---@type LspRange local range = diag.range if range.start.line == range['end'].line and range.start.character == range['end'].character then range['end'].character = range.start.character + 1 end end require"lean.infoview".__update_event(params.uri) end return lsp
local PANEL = vgui.GetControlTable("ixStorageView") function PANEL:Init() if (IsValid(ix.gui.openedStorage)) then ix.gui.openedStorage:Remove() end ix.gui.openedStorage = self self:SetSize(ScrW(), ScrH()) self:SetPos(0, 0) self:SetFadeTime(0.25) self:SetFrameMargin(4) self.storageInventory = self:Add("ixInventory") self.storageInventory.bNoBackgroundBlur = true self.storageInventory:ShowCloseButton(true) self.storageInventory:SetTitle("Storage") self.storageInventory.Close = function(this) net.Start("ixStorageClose") net.SendToServer() self:Remove() end self.storageMoney = self.storageInventory:Add("ixStorageMoneyItems") self.storageMoney:SetVisible(false) self.storageMoney.OnTransfer = function(t, amount, button) if (button) then amount = t.money end net.Start("ixStorageMoneyTake") net.WriteUInt(self.storageID, 32) net.WriteUInt(amount, 32) net.SendToServer() end ix.gui.inv1 = self:Add("ixInventory") ix.gui.inv1.bNoBackgroundBlur = true ix.gui.inv1:ShowCloseButton(true) ix.gui.inv1.Close = function(this) net.Start("ixStorageClose") net.SendToServer() self:Remove() end self.localMoney = ix.gui.inv1:Add("ixStashMoney") self.localMoney:SetVisible(false) self.localMoney:SetTooltip(L"text_rmb_giveallmoney") self.localMoney.OnTransfer = function(t, amount, button) if (button) then amount = t.money end net.Start("ixStorageMoneyGive") net.WriteUInt(self.storageID, 32) net.WriteUInt(amount, 32) net.SendToServer() end self:SetAlpha(0) self:AlphaTo(255, self:GetFadeTime()) self.storageInventory:MakePopup() ix.gui.inv1:MakePopup() end derma.DefineControl("ixStorageView", "", PANEL, "Panel") PANEL = {} AccessorFunc(PANEL, "money", "Money", FORCE_NUMBER) function PANEL:Init() self:DockPadding(1, 1, 1, 1) self:SetTall(24) self:Dock(BOTTOM) self.moneyBtn = self:Add("DButton") self.moneyBtn:Dock(FILL) self.moneyBtn:DockMargin(0, 0, 1, 0) self.moneyBtn:SetFont("ixGenericFont") self.moneyBtn:SetText("") self.moneyBtn:SetTooltip(L"text_rmb_takeallmoney") self.moneyBtn:SetIcon("icon16/money_dollar.png") self.moneyBtn:SetTextInset(2, 0) self.moneyBtn:SizeToContents() self.moneyBtn.Paint = function(t, w, h) derma.SkinFunc("PaintButtonFilled", t, w, h) end self.moneyBtn.OnMousePressed = function(_, code) if (code == MOUSE_LEFT) then surface.PlaySound("ui/buttonclick.wav") Derma_NumericRequest("", L"stash_enter_money", self.money, function(text) local amount = math.max(0, math.Round(tonumber(text) or 0)) if (amount != 0) then self:OnTransfer(amount) end end) elseif (code == MOUSE_RIGHT) then surface.PlaySound("ui/buttonclick.wav") self:OnTransfer(0, MOUSE_RIGHT) end end self.takeBtn = self:Add("DButton") self.takeBtn:Dock(RIGHT) self.takeBtn:SetFont("ixGenericFont") self.takeBtn:SetText(L"take_all") self.takeBtn:SetTextInset(8, 0) self.takeBtn:SizeToContents() self.takeBtn.Paint = self.moneyBtn.Paint self.takeBtn.DoClick = function() local storage = ix.gui.openedStorage if (IsValid(storage) and IsValid(ix.gui.inv1)) then local inventory = ix.item.inventories[storage.storageInventory.invID] local noItems if (!inventory or table.IsEmpty(inventory:GetItems(true))) then noItems = true end local charInventory = LocalPlayer():GetCharacter():GetInventory() if (charInventory:GetFilledSlotCount() >= charInventory.w * charInventory.h) then noItems = true end if (noItems and storage.storageMoney:GetMoney() == 0) then return end net.Start("ixStorageTakeAll") net.WriteUInt(storage.storageID, 32) net.WriteBool(!noItems) net.SendToServer() end end self.bNoBackgroundBlur = true end function PANEL:SetMoney(money) self.money = math.max(math.Round(tonumber(money) or 0), 0) self.moneyBtn:SetText(ix.currency.Get(money)) end function PANEL:OnTransfer(amount, code) end function PANEL:Paint(width, height) derma.SkinFunc("PaintBaseFrame", self, width, height) end vgui.Register("ixStorageMoneyItems", PANEL, "EditablePanel")
--- An iSCSI library implementing written by Patrik Karlsson <patrik@cqure.net> -- The library currently supports target discovery and login. -- -- The implementation is based on packetdumps and the iSCSI RFC -- * http://tools.ietf.org/html/rfc3720 -- -- The library contains the protocol message pairs in <code>Packet</code> -- E.g. <code>LoginRequest</code> and <code>LoginResponse</code> -- -- Each request can be "serialized" to a string using: -- <code>tostring(request)</code>. -- All responses can be read and instantiated from the socket by calling: -- <code>local status,resp = Response.fromSocket(sock)</code> -- -- In addition the library has the following classes: -- * <code>Packet</code> -- ** A class containing the request and response packets -- * <code>Comm</code> -- ** A class used to send and receive packet between the library and server -- ** The class handles some of the packet "counting" and value updating -- * <code>KVP</code> -- ** A key/value pair class that holds key value pairs -- * <code>Helper</code> -- ** A class that wraps the <code>Comm</code> and <code>Packet</code> classes -- ** The purpose of the class is to provide easy access to common iSCSI task -- -- -- @author Patrik Karlsson <patrik@cqure.net> -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html -- Version 0.2 -- Created 2010/11/18 - v0.1 - created by Patrik Karlsson <patrik@cqure.net> -- Revised 2010/11/28 - v0.2 - improved error handling, fixed discovery issues -- with multiple addresses <patrik@cqure.net> local bin = require "bin" local bit = require "bit" local ipOps = require "ipOps" local match = require "match" local nmap = require "nmap" local stdnse = require "stdnse" local openssl = stdnse.silent_require "openssl" local string = require "string" local table = require "table" _ENV = stdnse.module("iscsi", stdnse.seeall) Packet = { Opcode = { LOGIN = 0x03, TEXT = 0x04, LOGOUT = 0x06, }, LoginRequest = { CSG = { SecurityNegotiation = 0, LoginOperationalNegotiation = 1, FullFeaturePhase = 3, }, NSG = { SecurityNegotiation = 0, LoginOperationalNegotiation = 1, FullFeaturePhase = 3, }, --- Creates a new instance of LoginRequest -- -- @return instance of LoginRequest new = function( self ) local o = {} setmetatable(o, self) self.__index = self o.immediate = 0 o.opcode = Packet.Opcode.LOGIN o.flags = {} o.ver_max = 0 o.ver_min = 0 o.total_ahs_len = 0 o.data_seg_len = 0 o.isid = { t=0x01, a=0x00, b=0x0001, c=0x37, d=0 } o.tsih = 0 o.initiator_task_tag = 1 o.cid = 1 o.cmdsn = 0 o.expstatsn = 1 o.kvp = KVP:new() return o end, setImmediate = function(self, b) self.immediate = ( b and 1 or 0 ) end, --- Sets the transit bit -- -- @param b boolean containing the new transit value setTransit = function(self, b) self.flags.transit = ( b and 1 or 0 ) end, --- Sets the continue bit -- -- @param b boolean containing the new continue value setContinue = function(self, b) self.flags.continue = ( b and 1 or 0 ) end, --- Sets the CSG values -- -- @param csg number containing the new NSG value setCSG = function(self, csg) self.flags.csg = csg end, --- Sets the NSG values -- -- @param nsg number containing the new NSG value setNSG = function(self, nsg) self.flags.nsg = nsg end, --- Converts the class instance to string -- -- @return string containing the converted instance __tostring = function( self ) local reserved = 0 local kvps = tostring(self.kvp) self.data_seg_len = #kvps local pad = 4 - ((#kvps + 48) % 4) pad = ( pad == 4 ) and 0 or pad local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len local flags = bit.lshift( ( self.flags.transit or 0 ), 7 ) flags = flags + bit.lshift( ( self.flags.continue or 0 ), 6) flags = flags + ( self.flags.nsg or 0 ) flags = flags + bit.lshift( ( self.flags.csg or 0 ), 2 ) local opcode = self.opcode + bit.lshift((self.immediate or 0), 6) local data = bin.pack(">CCCCICSCSSISSIILLAA", opcode, flags, self.ver_max, self.ver_min, len, bit.lshift( self.isid.t, 6 ) + bit.band( self.isid.a, 0x3f), self.isid.b, self.isid.c, self.isid.d, self.tsih, self.initiator_task_tag, self.cid, reserved, self.cmdsn, self.expstatsn, reserved, reserved, kvps, string.rep('\0', pad) ) return data end }, LoginResponse = { -- Error messages ErrorMsgs = { [0x0000] = "Success", [0x0101] = "Target moved temporarily", [0x0102] = "Target moved permanently", [0x0200] = "Initiator error", [0x0201] = "Authentication failure", [0x0202] = "Authorization failure", [0x0203] = "Target not found", [0x0204] = "Target removed", [0x0205] = "Unsupported version", [0x0206] = "Too many connections", [0x0207] = "Missing parameter", [0x0208] = "Can't include in session", [0x0209] = "Session type not supported", [0x020a] = "Session does not exist", [0x020b] = "Invalid request during login", [0x0300] = "Target error", [0x0301] = "Service unavailable", [0x0302] = "Out of resources", }, -- Error constants Errors = { SUCCESS = 0, AUTH_FAILED = 0x0201, }, --- Creates a new instance of LoginResponse -- -- @return instance of LoginResponse new = function( self ) local o = {} setmetatable(o, self) self.__index = self return o end, --- Returns the error message getErrorMessage = function( self ) return Packet.LoginResponse.ErrorMsgs[self.status_code] or "Unknown error" end, --- Returns the error code getErrorCode = function( self ) return self.status_code or 0 end, --- Creates a LoginResponse with data read from the socket -- -- @return status true on success, false on failure -- @return resp instance of LoginResponse fromSocket = function( s ) local status, header = s:receive_buf(match.numbytes(48), true) if ( not(status) ) then return false, "Failed to read header from socket" end local resp = Packet.LoginResponse:new() local pos, len = bin.unpack(">I", header, 5) resp.total_ahs_len = bit.rshift(len, 24) resp.data_seg_len = bit.band(len, 0x00ffffff) pos, resp.status_code = bin.unpack(">S", header, 37) local pad = ( 4 - ( resp.data_seg_len % 4 ) ) pad = ( pad == 4 ) and 0 or pad local status, data = s:receive_buf(match.numbytes(resp.data_seg_len + pad), true) if ( not(status) ) then return false, "Failed to read data from socket" end resp.kvp = KVP:new() for _, kvp in ipairs(stdnse.strsplit( "\0", data )) do local k, v = kvp:match("(.*)=(.*)") if ( v ) then resp.kvp:add( k, v ) end end return true, resp end, }, TextRequest = { --- Creates a new instance of TextRequest -- -- @return instance of TextRequest new = function( self ) local o = {} setmetatable(o, self) self.__index = self o.opcode = Packet.Opcode.TEXT o.flags = {} o.flags.final = 0 o.flags.continue = 0 o.total_ahs_len = 0 o.data_seg_len = 0 o.lun = 0 o.initiator_task_tag = 1 o.target_trans_tag = 0xffffffff o.cmdsn = 2 o.expstatsn = 1 o.kvp = KVP:new() return o end, --- Sets the final bit of the TextRequest setFinal = function( self, b ) self.flags.final = ( b and 1 or 0 ) end, --- Sets the continue bit of the TextRequest setContinue = function( self, b ) self.flags.continue = ( b and 1 or 0 ) end, --- Converts the class instance to string -- -- @return string containing the converted instance __tostring = function(self) local flags = bit.lshift( ( self.flags.final or 0 ), 7 ) flags = flags + bit.lshift( (self.flags.continue or 0), 6 ) local kvps = tostring(self.kvp) kvps = kvps .. string.rep('\0', #kvps % 2) self.data_seg_len = #kvps local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len local reserved = 0 local data = bin.pack(">CCSILIIIILLA", self.opcode, flags, reserved, len, self.lun, self.initiator_task_tag, self.target_trans_tag, self.cmdsn, self.expstatsn, reserved, reserved, kvps) return data end, }, TextResponse = { --- Creates a new instance of TextResponse -- -- @return instance of TextResponse new = function( self ) local o = {} setmetatable(o, self) self.__index = self return o end, --- Creates a TextResponse with data read from the socket -- -- @return status true on success, false on failure -- @return instance of TextResponse -- err string containing error message fromSocket = function( s ) local resp = Packet.TextResponse:new() local textdata = "" repeat local status, header = s:receive_buf(match.numbytes(48), true) if not status then return status, header end local pos, _, flags, _, _, len = bin.unpack(">CCCCI", header) local cont = ( bit.band(flags, 0x40) == 0x40 ) resp.total_ahs_len = bit.rshift(len, 24) resp.data_seg_len = bit.band(len, 0x00ffffff) local data status, data = s:receive_buf(match.numbytes(resp.data_seg_len), true) textdata = textdata .. data until( not(cont) ) resp.records = {} local kvps = stdnse.strsplit( "\0", textdata ) local record -- Each target record starts with one text key of the form: -- TargetName=<target-name-goes-here> -- Followed by zero or more address keys of the form: -- TargetAddress=<hostname-or-ipaddress>[:<tcp-port>], -- <portal-group-tag> for _, kvp in ipairs(kvps) do local k, v = kvp:match("(.*)%=(.*)") if ( k == "TargetName" ) then if ( record ) then table.insert(resp.records, record) record = {} end if ( #resp.records == 0 ) then record = {} end record.name = v elseif ( k == "TargetAddress" ) then record.addr = record.addr or {} table.insert( record.addr, v ) elseif ( not(k) ) then -- this should be the ending empty kvp table.insert(resp.records, record) break else stdnse.debug1("ERROR: iscsi.TextResponse: Unknown target record (%s)", k) end end return true, resp end, }, --- Class handling a login request LogoutRequest = { --- Creates a new instance of LogoutRequest -- -- @return instance of LogoutRequest new = function( self ) local o = {} setmetatable(o, self) self.__index = self o.opcode = Packet.Opcode.LOGOUT o.immediate = 1 o.reasoncode = 0 o.total_ahs_len = 0 o.data_seg_len = 0 o.initiator_task_tag = 2 o.cid = 1 o.cmdsn = 0 o.expstatsn = 1 return o end, --- Converts the class instance to string -- -- @return string containing the converted instance __tostring = function(self) local opcode = self.opcode + bit.lshift((self.immediate or 0), 6) local reserved = 0 local len = bit.lshift( self.total_ahs_len, 24 ) + self.data_seg_len local data = bin.pack(">CCSILISSIILL", opcode, (0x80 + self.reasoncode), reserved, len, reserved,self.initiator_task_tag, self.cid, reserved, self.cmdsn, self.expstatsn, reserved, reserved ) return data end, }, --- Class handling the Logout response LogoutResponse = { --- Creates a new instance of LogoutResponse -- -- @return instance of LogoutResponse new = function( self ) local o = {} setmetatable(o, self) self.__index = self return o end, --- Creates a LogoutResponse with data read from the socket -- -- @return status true on success, false on failure -- @return instance of LogoutResponse -- err string containing error message fromSocket = function( s ) local resp = Packet.LogoutResponse:new() local status, header = s:receive_buf(match.numbytes(48), true) if ( not(status) ) then return status, header end return true, resp end } } --- The communication class handles socket reads and writes -- -- In addition it keeps track of both immediate packets and the amount of read -- packets and updates cmdsn and expstatsn accordingly. Comm = { --- Creates a new instance of Comm -- -- @return instance of Comm new = function(self, socket) local o = {} setmetatable(o, self) self.__index = self o.expstatsn = 0 o.cmdsn = 1 o.socket = socket return o end, --- Sends a packet and retrieves the response -- -- @param out_packet instance of a packet to send -- @param in_class class of the packet to read -- @return status true on success, false on failure -- @return r decoded instance of in_class exchange = function( self, out_packet, in_class ) local expstatsn = ( self.expstatsn == 0 ) and 1 or self.expstatsn if ( out_packet.immediate and out_packet.immediate == 1 ) then self.cmdsn = self.cmdsn + 1 end out_packet.expstatsn = expstatsn out_packet.cmdsn = self.cmdsn self.socket:send( tostring( out_packet ) ) local status, r = in_class.fromSocket( self.socket ) self.expstatsn = self.expstatsn + 1 return status, r end, } --- Key/Value pairs class KVP = { --- Creates a new instance of KVP -- -- @return instance of KVP new = function( self ) local o = {} setmetatable(o, self) self.__index = self o.kvp = {} return o end, --- Adds a key/value pair -- -- @param key string containing the key name -- @param value string containing the value add = function( self, key, value ) table.insert( self.kvp, {[key]=value} ) end, --- Gets all values for a specific key -- -- @param key string containing the name of the key to retrieve -- @return values table containing all values for the specified key get = function( self, key ) local values = {} for _, kvp in ipairs(self.kvp) do for k, v in pairs( kvp ) do if ( key == k ) then table.insert( values, v ) end end end return values end, --- Returns all key value pairs as string delimited by \0 -- eg. "key1=val1\0key2=val2\0" -- -- @return string containing all key/value pairs __tostring = function( self ) local ret = "" for _, kvp in ipairs(self.kvp) do for k, v in pairs( kvp ) do ret = ret .. ("%s=%s\0"):format(k,v) end end return ret end, } --- CHAP authentication class CHAP = { --- Calculate a CHAP - response -- -- @param identifier number containing the CHAP identifier -- @param challenge string containing the challenge -- @param secret string containing the users password -- @return response string containing the CHAP response calcResponse = function( identifier, challenge, secret ) return openssl.md5( identifier .. secret .. challenge ) end, } --- The helper class contains functions with more descriptive names Helper = { --- Creates a new instance of the Helper class -- -- @param host table as received by the script action function -- @param port table as received by the script action function -- @return o instance of Helper new = function( self, host, port ) local o = {} setmetatable(o, self) self.__index = self o.host, o.port = host, port o.socket = nmap.new_socket() return o end, --- Connects to the iSCSI target -- -- @return status true on success, false on failure -- @return err string containing error message is status is false connect = function( self ) self.socket:set_timeout(10000) local status, err = self.socket:connect(self.host, self.port, "tcp") if ( not(status) ) then return false, err end self.comm = Comm:new( self.socket ) return true end, --- Attempts to discover accessible iSCSI targets on the remote server -- -- @return status true on success, false on failure -- @return targets table containing discovered targets -- each table entry is a target table with <code>name</code> -- and <code>addr</code>. -- err string containing an error message is status is false discoverTargets = function( self ) local p = Packet.LoginRequest:new() p:setTransit(true) p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation) p.kvp:add( "InitiatorName", "iqn.1991-05.com.microsoft:nmap_iscsi_probe" ) p.kvp:add( "SessionType", "Discovery" ) p.kvp:add( "AuthMethod", "None" ) local status, resp = self.comm:exchange( p, Packet.LoginResponse ) if ( not(status) ) then return false, ("ERROR: iscsi.Helper.discoverTargets: %s"):format(resp) end local auth_method = resp.kvp:get("AuthMethod")[1] if not auth_method then stdnse.debug1("Missing AuthMethod, proceeding as if NONE was sent.") elseif ( auth_method:upper() ~= "NONE" ) then return false, "ERROR: iscsi.Helper.discoverTargets: Unsupported authentication method" end p = Packet.LoginRequest:new() p:setTransit(true) p:setNSG(Packet.LoginRequest.NSG.FullFeaturePhase) p:setCSG(Packet.LoginRequest.CSG.LoginOperationalNegotiation) p.kvp:add( "HeaderDigest", "None") p.kvp:add( "DataDigest", "None") p.kvp:add( "MaxRecvDataSegmentLength", "65536") p.kvp:add( "DefaultTime2Wait", "0") p.kvp:add( "DefaultTime2Retain", "60") status, resp = self.comm:exchange( p, Packet.LoginResponse ) p = Packet.TextRequest:new() p:setFinal(true) p.kvp:add( "SendTargets", "All" ) status, resp = self.comm:exchange( p, Packet.TextResponse ) if ( not(resp.records) ) then return false, "iscsi.discoverTargets: response returned no targets" end for _, record in ipairs(resp.records) do table.sort( record.addr, function(a, b) local c = ipOps.compare_ip(a:match("(.-):"), "le", b:match("(.-):")); return c end ) end return true, resp.records end, --- Logs out from the iSCSI target -- -- @return status true on success, false on failure logout = function(self) local p = Packet.LogoutRequest:new() local status, resp = self.comm:exchange( p, Packet.LogoutResponse ) return status end, --- Authenticate to the iSCSI service -- -- @param target_name string containing the name of the iSCSI target -- @param username string containing the username -- @param password string containing the password -- @param auth_method string containing either "None" or "Chap" -- @return status true on success false on failure -- @return response containing the loginresponse or -- err string containing an error message if status is false login = function( self, target_name, username, password, auth_method ) local auth_method = auth_method or "None" if ( not(target_name) ) then return false, "No target name specified" end if ( auth_method:upper()~= "NONE" and auth_method:upper()~= "CHAP" ) then return false, "Unknown authentication method" end local p = Packet.LoginRequest:new() p:setTransit(true) p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation) p.kvp:add( "InitiatorName", "iqn.1991-05.com.microsoft:nmap_iscsi_probe" ) p.kvp:add( "SessionType", "Normal" ) p.kvp:add( "TargetName", target_name ) p.kvp:add( "AuthMethod", auth_method ) if ( not(self.comm) ) then return false, "ERROR: iscsi.Helper.login: Not connected" end local status, resp = self.comm:exchange( p, Packet.LoginResponse ) if ( not(status) ) then return false, ("ERROR: iscsi.Helper.login: %s"):format(resp) end if ( resp.status_code ~= 0 ) then stdnse.debug3("ERROR: iscsi.Helper.login: Authentication failed (error code: %d)", resp.status_code) return false, resp elseif ( auth_method:upper()=="NONE" ) then return true, resp end p = Packet.LoginRequest:new() p.kvp:add( "CHAP_A", "5" ) status, resp = self.comm:exchange( p, Packet.LoginResponse ) if ( not(status) ) then return false, ("ERROR: iscsi.Helper.login: %s"):format(resp) end local alg = resp.kvp:get("CHAP_A")[1] if ( alg ~= "5" ) then return false, "Unsupported authentication algorithm" end local chall = resp.kvp:get("CHAP_C")[1] if ( not(chall) ) then return false, "Failed to decode challenge" end chall = bin.pack("H", chall:sub(3)) local ident = resp.kvp:get("CHAP_I")[1] if (not(ident)) then return false, "Failed to decoded identifier" end ident = string.char(tonumber(ident)) local resp = CHAP.calcResponse( ident, chall, password ) resp = "0x" .. select(2, bin.unpack("H16", resp)) p = Packet.LoginRequest:new() p:setImmediate(true) p:setTransit(true) p:setNSG(Packet.LoginRequest.NSG.LoginOperationalNegotiation) p.kvp:add("CHAP_N", username) p.kvp:add("CHAP_R", resp) status, resp = self.comm:exchange( p, Packet.LoginResponse ) if ( not(status) ) then return false, ("ERROR: iscsi.Helper.login: %s"):format(resp) end if ( resp:getErrorCode() ~= Packet.LoginResponse.Errors.SUCCESS ) then return false, "Login failed" end return true, resp end, --- Disconnects the socket from the server close = function(self) self.socket:close() end } return _ENV;
return require 'parse.char.ascii7.symbol' + require 'parse.char.ascii7.whitespace.horizontal'
-- Copyright 2016-2019, Firaxis Games -- =========================================================================== -- CityPanel v3 -- =========================================================================== include( "AdjacencyBonusSupport" ); -- GetAdjacentYieldBonusString() include( "CitySupport" ); include( "Civ6Common" ); -- GetYieldString() include( "Colors" ); include( "InstanceManager" ); include( "SupportFunctions" ); -- Round(), Clamp() include( "PortraitSupport" ); include( "ToolTipHelper" ); include( "GameCapabilities" ); include( "MapUtilities" ); include("cui_settings"); -- CUI -- =========================================================================== -- DEBUG -- Toggle these for temporary debugging help. -- =========================================================================== local m_debugAllowMultiPanel :boolean = false; -- (false default) Let's multiple sub-panels show at one time. -- =========================================================================== -- GLOBALS -- Accessible in overriden files. -- =========================================================================== g_pCity = nil; g_growthPlotId = -1; g_growthHexTextWidth = -1; -- =========================================================================== -- CONSTANTS -- =========================================================================== local ANIM_OFFSET_OPEN :number = -73; local ANIM_OFFSET_OPEN_WITH_PRODUCTION_LIST :number = -250; local SIZE_SMALL_RELIGION_ICON :number = 22; local SIZE_LEADER_ICON :number = 32; local SIZE_PRODUCTION_ICON :number = 32; -- TODO: Switch this to 38 when the icons go in. local SIZE_MAIN_ROW_LEFT_WIDE :number = 270; local SIZE_MAIN_ROW_LEFT_COLLAPSED :number = 157; local TXT_NO_PRODUCTION :string = Locale.Lookup("LOC_HUD_CITY_PRODUCTION_NOTHING_PRODUCED"); local MAX_BEFORE_TRUNC_TURN_LABELS :number = 160; local MAX_BEFORE_TRUNC_STATIC_LABELS :number = 112; local HEX_GROWTH_TEXT_PADDING :number = 10; local UV_CITIZEN_GROWTH_STATUS :table = {}; UV_CITIZEN_GROWTH_STATUS[0] = {u=0, v=0 }; -- revolt UV_CITIZEN_GROWTH_STATUS[1] = {u=0, v=0 }; -- unrest UV_CITIZEN_GROWTH_STATUS[2] = {u=0, v=0}; -- unhappy UV_CITIZEN_GROWTH_STATUS[3] = {u=0, v=50}; -- displeased UV_CITIZEN_GROWTH_STATUS[4] = {u=0, v=100}; -- content (normal) UV_CITIZEN_GROWTH_STATUS[5] = {u=0, v=150}; -- happy UV_CITIZEN_GROWTH_STATUS[6] = {u=0, v=200}; -- ecstatic local UV_HOUSING_GROWTH_STATUS :table = {}; UV_HOUSING_GROWTH_STATUS[0] = {u=0, v=0}; -- slowed UV_HOUSING_GROWTH_STATUS[1] = {u=0, v=100}; -- normal local UV_CITIZEN_STARVING_STATUS :table = {}; UV_CITIZEN_STARVING_STATUS[0] = {u=0, v=0}; -- starving UV_CITIZEN_STARVING_STATUS[1] = {u=0, v=100}; -- normal local PANEL_INFOLINE_LOCATIONS:table = {}; PANEL_INFOLINE_LOCATIONS[0] = 20; PANEL_INFOLINE_LOCATIONS[1] = 45; PANEL_INFOLINE_LOCATIONS[2] = 71; PANEL_INFOLINE_LOCATIONS[3] = 94; local PANEL_BUTTON_LOCATIONS:table = {}; PANEL_BUTTON_LOCATIONS[0] = {x=85, y=18}; PANEL_BUTTON_LOCATIONS[1] = {x=99, y=42}; PANEL_BUTTON_LOCATIONS[2] = {x=95, y=69}; PANEL_BUTTON_LOCATIONS[3] = {x=79, y=90}; local HOUSING_LABEL_OFFSET:number = 66; -- Mirrored in ProductionPanel local LISTMODE:table = {PRODUCTION = 1, PURCHASE_GOLD = 2, PURCHASE_FAITH = 3, PROD_QUEUE = 4}; m_PurchasePlot = UILens.CreateLensLayerHash("Purchase_Plot"); local m_CitizenManagement : number = UILens.CreateLensLayerHash("Citizen_Management"); -- =========================================================================== -- MEMBERS -- =========================================================================== local m_kData :table = nil; local m_isInitializing :boolean= false; local m_isShowingPanels :boolean= false; local m_pPlayer :table = nil; local m_primaryColor :number = UI.GetColorValueFromHexLiteral(0xcafef00d); local m_secondaryColor :number = UI.GetColorValueFromHexLiteral(0xf00d1ace); local m_kTutorialDisabledControls :table = nil; local m_CurrentPanelLine :number = 0; local m_PrevInterfaceMode :number = InterfaceModeTypes.SELECTION; -- =========================================================================== -- -- =========================================================================== function Close() ContextPtr:SetHide( true ); end -- =========================================================================== -- Helper, display the 3-way state of a yield based on the enum. -- yieldData, A YIELD_STATE -- yieldName, The name tied used in the check and ignore controls. -- =========================================================================== function RealizeYield3WayCheck( yieldData:number, yieldType, yieldToolTip ) local yieldInfo = GameInfo.Yields[yieldType]; if(yieldInfo) then local controlLookup = { YIELD_FOOD = "Food", YIELD_PRODUCTION = "Production", YIELD_GOLD = "Gold", YIELD_SCIENCE = "Science", YIELD_CULTURE = "Culture", YIELD_FAITH = "Faith", }; local yieldName = controlLookup[yieldInfo.YieldType]; if(yieldName) then local checkControl = Controls[yieldName.."Check"]; local ignoreControl = Controls[yieldName.."Ignore"]; local gridControl = Controls[yieldName.."Grid"]; if(checkControl and ignoreControl and gridControl) then local toolTip = ""; if yieldData == YIELD_STATE.FAVORED then checkControl:SetCheck(true); -- Just visual, no callback! checkControl:SetDisabled(false); ignoreControl:SetHide(true); toolTip = Locale.Lookup("LOC_HUD_CITY_YIELD_FOCUSING", yieldInfo.Name) .. "[NEWLINE][NEWLINE]"; elseif yieldData == YIELD_STATE.IGNORED then checkControl:SetCheck(false); -- Just visual, no callback! checkControl:SetDisabled(true); ignoreControl:SetHide(false); toolTip = Locale.Lookup("LOC_HUD_CITY_YIELD_IGNORING", yieldInfo.Name) .. "[NEWLINE][NEWLINE]"; else checkControl:SetCheck(false); checkControl:SetDisabled(false); ignoreControl:SetHide(true); toolTip = Locale.Lookup("LOC_HUD_CITY_YIELD_CITIZENS", yieldInfo.Name) .. "[NEWLINE][NEWLINE]"; end if(#yieldToolTip > 0) then toolTip = toolTip .. yieldToolTip; else toolTip = toolTip .. Locale.Lookup("LOC_HUD_CITY_YIELD_NOTHING"); end gridControl:SetToolTipString(toolTip); end end end end -- =========================================================================== -- Set the health meter -- =========================================================================== function RealizeHealthMeter( control:table, percent:number ) if ( percent > 0.7 ) then control:SetColor( COLORS.METER_HP_GOOD ); elseif ( percent > 0.4 ) then control:SetColor( COLORS.METER_HP_OK ); else control:SetColor( COLORS.METER_HP_BAD ); end -- Meter control is half circle, so add enough to start at half point and condense % into the half area percent = (percent * 0.5) + 0.5; control:SetPercent( percent ); end -- =========================================================================== -- Main city panel -- =========================================================================== function ViewMain( data:table ) m_primaryColor, m_secondaryColor = UI.GetPlayerColors( m_pPlayer:GetID() ); if(m_primaryColor == nil or m_secondaryColor == nil or m_primaryColor == 0 or m_secondaryColor == 0) then UI.DataError("Couldn't find player colors for player - " .. (m_pPlayer and tostring(m_pPlayer:GetID()) or "nil")); end local darkerBackColor = UI.DarkenLightenColor(m_primaryColor,-85,100); local brighterBackColor = UI.DarkenLightenColor(m_primaryColor,90,255); m_CurrentPanelLine = 0; -- Name data Controls.CityName:SetText((data.IsCapital and "[ICON_Capital]" or "") .. Locale.ToUpper( Locale.Lookup(data.CityName))); Controls.CityName:SetToolTipString(data.IsCapital and Locale.Lookup("LOC_HUD_CITY_IS_CAPITAL") or nil ); -- Banner and icon colors Controls.Banner:SetColor(m_primaryColor); Controls.BannerLighter:SetColor(brighterBackColor); Controls.BannerDarker:SetColor(darkerBackColor); Controls.CircleBacking:SetColor(m_primaryColor); Controls.CircleLighter:SetColor(brighterBackColor); Controls.CircleDarker:SetColor(darkerBackColor); Controls.CityName:SetColor(m_secondaryColor); Controls.CivIcon:SetColor(m_secondaryColor); -- Set Population -- Controls.PopulationNumber:SetText(data.Population); -- Damage meters --- RealizeHealthMeter( Controls.CityHealthMeter, data.HitpointPercent ); if(data.CityWallTotalHP > 0) then Controls.CityWallHealthMeters:SetHide(false); --RealizeHealthMeter( Controls.WallHealthMeter, data.CityWallHPPercent ); local percent = (data.CityWallHPPercent * 0.5) + 0.5; Controls.WallHealthMeter:SetPercent( percent ); else Controls.CityWallHealthMeters:SetHide(true); end -- Update city health tooltip local tooltip:string = Locale.Lookup("LOC_HUD_UNIT_PANEL_HEALTH_TOOLTIP", data.HitpointsCurrent, data.HitpointsTotal); if (data.CityWallTotalHP > 0) then tooltip = tooltip .. "[NEWLINE]" .. Locale.Lookup("LOC_HUD_UNIT_PANEL_WALL_HEALTH_TOOLTIP", data.CityWallCurrentHP, data.CityWallTotalHP); end Controls.CityHealthMeters:SetToolTipString(tooltip); local civType:string = PlayerConfigurations[data.Owner]:GetCivilizationTypeName(); if civType ~= nil then Controls.CivIcon:SetIcon("ICON_" .. civType); else UI.DataError("Invalid type name returned by GetCivilizationTypeName"); end -- CUI >> -- Set icons and values for the yield checkboxes Controls.FoodCheck : GetTextButton(): SetText("[ICON_Food]" .. toPlusMinusString(CuiGetFoodPerTurn(data))); Controls.ProductionCheck: GetTextButton(): SetText("[ICON_Production]" .. toPlusMinusString(data.ProductionPerTurn)); Controls.GoldCheck : GetTextButton(): SetText("[ICON_Gold]" .. toPlusMinusString(data.GoldPerTurn)); Controls.ScienceCheck : GetTextButton(): SetText("[ICON_Science]" .. toPlusMinusString(data.SciencePerTurn)); Controls.CultureCheck : GetTextButton(): SetText("[ICON_Culture]" .. toPlusMinusString(data.CulturePerTurn)); Controls.FaithCheck : GetTextButton(): SetText("[ICON_Faith]" .. toPlusMinusString(data.FaithPerTurn)); -- Set the Yield checkboxes based on the game state RealizeYield3WayCheck(data.YieldFilters[YieldTypes.FOOD], YieldTypes.FOOD, CuiGetFoodToolTip(data)); RealizeYield3WayCheck(data.YieldFilters[YieldTypes.PRODUCTION], YieldTypes.PRODUCTION, data.ProductionPerTurnToolTip); RealizeYield3WayCheck(data.YieldFilters[YieldTypes.GOLD], YieldTypes.GOLD, data.GoldPerTurnToolTip); RealizeYield3WayCheck(data.YieldFilters[YieldTypes.SCIENCE], YieldTypes.SCIENCE, data.SciencePerTurnToolTip); RealizeYield3WayCheck(data.YieldFilters[YieldTypes.CULTURE], YieldTypes.CULTURE, data.CulturePerTurnToolTip); RealizeYield3WayCheck(data.YieldFilters[YieldTypes.FAITH], YieldTypes.FAITH, data.FaithPerTurnToolTip); -- << CUI if m_isShowingPanels then Controls.LabelButtonRows:SetSizeX( SIZE_MAIN_ROW_LEFT_COLLAPSED ); else Controls.LabelButtonRows:SetSizeX( SIZE_MAIN_ROW_LEFT_WIDE ); end -- Custom religion icon: if data.Religions[DATA_DOMINANT_RELIGION] ~= nil then local kReligion :table = GameInfo.Religions[data.Religions[DATA_DOMINANT_RELIGION].ReligionType]; if (kReligion ~= nil) then local iconName :string = "ICON_" .. kReligion.ReligionType; Controls.ReligionIcon:SetIcon(iconName); end end Controls.BreakdownNum:SetText( data.BuildingsNum ); Controls.BreakdownGrid:SetOffsetY(PANEL_INFOLINE_LOCATIONS[m_CurrentPanelLine]); Controls.BreakdownButton:SetOffsetX(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].x); Controls.BreakdownButton:SetOffsetY(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].y); m_CurrentPanelLine = m_CurrentPanelLine + 1; -- Hide Religion / Faith UI in some scenarios if not GameCapabilities.HasCapability("CAPABILITY_CITY_HUD_RELIGION_TAB") then Controls.ReligionGrid:SetHide(true); Controls.ReligionIcon:SetHide(true); Controls.ReligionButton:SetHide(true); else Controls.ReligionGrid:SetOffsetY(PANEL_INFOLINE_LOCATIONS[m_CurrentPanelLine]); Controls.ReligionButton:SetOffsetX(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].x); Controls.ReligionButton:SetOffsetY(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].y); m_CurrentPanelLine = m_CurrentPanelLine + 1; end if not GameCapabilities.HasCapability("CAPABILITY_FAITH") then Controls.ProduceWithFaithCheck:SetHide(true); Controls.FaithGrid:SetHide(true); end local amenitiesNumText = data.AmenitiesNetAmount; if (data.AmenitiesNetAmount > 0) then amenitiesNumText = "+" .. amenitiesNumText; end Controls.AmenitiesNum:SetText( amenitiesNumText ); local colorName:string = GetHappinessColor( data.Happiness ); Controls.AmenitiesNum:SetColorByName( colorName ); Controls.AmenitiesGrid:SetOffsetY(PANEL_INFOLINE_LOCATIONS[m_CurrentPanelLine]); Controls.AmenitiesButton:SetOffsetX(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].x); Controls.AmenitiesButton:SetOffsetY(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].y); m_CurrentPanelLine = m_CurrentPanelLine + 1; Controls.ReligionNum:SetText( data.ReligionFollowers ); Controls.HousingNum:SetText( data.Population ); colorName = GetPercentGrowthColor( data.HousingMultiplier ); Controls.HousingNum:SetColorByName( colorName ); Controls.HousingMax:SetText( data.Housing ); Controls.HousingLabels:SetOffsetX(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].x - HOUSING_LABEL_OFFSET); Controls.HousingGrid:SetOffsetY(PANEL_INFOLINE_LOCATIONS[m_CurrentPanelLine]); Controls.HousingButton:SetOffsetX(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].x); Controls.HousingButton:SetOffsetY(PANEL_BUTTON_LOCATIONS[m_CurrentPanelLine].y); Controls.BreakdownLabel:SetHide( m_isShowingPanels ); Controls.ReligionLabel:SetHide( m_isShowingPanels ); Controls.AmenitiesLabel:SetHide( m_isShowingPanels ); Controls.HousingLabel:SetHide( m_isShowingPanels ); Controls.PanelStackShadow:SetHide( not m_isShowingPanels ); Controls.ProductionNowLabel:SetHide( m_isShowingPanels ); -- Determine size of progress bars at the bottom, as well as sub-panel offset. local OFF_BOTTOM_Y :number = 9; local OFF_ROOM_FOR_PROGRESS_Y :number = 36; local OFF_GROWTH_BAR_PUSH_RIGHT_X :number = 2; local OFF_GROWTH_BAR_DEFAULT_RIGHT_X :number = 32; local widthNumLabel :number = 0; -- Growth Controls.GrowthTurnsSmall:SetHide( not m_isShowingPanels ); Controls.GrowthTurns:SetHide( m_isShowingPanels ); Controls.GrowthTurnsBar:SetPercent( data.CurrentFoodPercent ); Controls.GrowthTurnsBar:SetShadowPercent( data.FoodPercentNextTurn ); Controls.GrowthTurnsBarSmall:SetPercent( data.CurrentFoodPercent ); Controls.GrowthTurnsBarSmall:SetShadowPercent( data.FoodPercentNextTurn ); Controls.GrowthNum:SetText( math.abs(data.TurnsUntilGrowth) ); Controls.GrowthNumSmall:SetText( math.abs(data.TurnsUntilGrowth).."[Icon_Turn]" ); if data.Occupied then Controls.GrowthLabel:SetColorByName("StatBadCS"); Controls.GrowthLabel:SetText( Locale.ToUpper( Locale.Lookup("LOC_HUD_CITY_GROWTH_OCCUPIED") ) ); elseif data.TurnsUntilGrowth >= 0 then Controls.GrowthLabel:SetColorByName("StatGoodCS"); Controls.GrowthLabel:SetText( Locale.ToUpper( Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_GROWTH",data.TurnsUntilGrowth)) ); else Controls.GrowthLabel:SetColorByName("StatBadCS"); Controls.GrowthLabel:SetText( Locale.ToUpper( Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_LOSS", math.abs(data.TurnsUntilGrowth))) ); end widthNumLabel = Controls.GrowthNum:GetSizeX(); TruncateStringWithTooltip(Controls.GrowthLabel, MAX_BEFORE_TRUNC_TURN_LABELS-widthNumLabel, Controls.GrowthLabel:GetText()); --Production Controls.ProductionTurns:SetHide( m_isShowingPanels ); Controls.ProductionTurnsBar:SetPercent(Clamp(data.CurrentProdPercent, 0.0, 1.0)); Controls.ProductionTurnsBar:SetShadowPercent(Clamp(data.ProdPercentNextTurn, 0.0, 1.0)); Controls.ProductionNum:SetText( data.CurrentTurnsLeft ); Controls.ProductionNowLabel:SetText( data.CurrentProductionName ); Controls.ProductionDescriptionString:SetText( data.CurrentProductionDescription ); --Controls.ProductionDescription:SetText( "There was a young lady from Venus, who's body was shaped like a, THAT'S ENOUGH DATA." ); if( data.CurrentProductionStats ~= "") then Controls.ProductionStatString:SetText( data.CurrentProductionStats ); end Controls.ProductionDataStack:CalculateSize(); Controls.ProductionDataScroll:CalculateSize(); local isIconSet:boolean = false; if data.CurrentProductionIcons then for _,iconName in ipairs(data.CurrentProductionIcons) do if iconName ~= nil and Controls.ProductionIcon:TrySetIcon(iconName) then isIconSet = true; break; end end end Controls.ProductionIcon:SetHide( not isIconSet ); Controls.ProductionNum:SetHide( data.CurrentTurnsLeft < 0 ); if data.CurrentTurnsLeft < 0 then Controls.ProductionLabel:SetText( Locale.ToUpper( Locale.Lookup("LOC_HUD_CITY_NOTHING_PRODUCED")) ); widthNumLabel = 0; else Controls.ProductionLabel:SetText( Locale.ToUpper( Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_COMPLETED", data.CurrentTurnsLeft)) ); widthNumLabel = Controls.ProductionNum:GetSizeX(); end TruncateStringWithTooltip(Controls.ProductionLabel, MAX_BEFORE_TRUNC_TURN_LABELS-widthNumLabel, Controls.ProductionLabel:GetText()); -- Tutorial lockdown if m_kTutorialDisabledControls ~= nil then for _,name in ipairs(m_kTutorialDisabledControls) do if Controls[name] ~= nil then Controls[name]:SetDisabled(true); end end end end -- =========================================================================== -- Return ColorSet name -- =========================================================================== function GetHappinessColor( eHappiness:number ) local happinessInfo = GameInfo.Happinesses[eHappiness]; if (happinessInfo ~= nil) then if (happinessInfo.GrowthModifier < 0) then return "StatBadCS"; end if (happinessInfo.GrowthModifier > 0) then return "StatGoodCS"; end end return "StatNormalCS"; end -- =========================================================================== -- Return ColorSet name -- =========================================================================== function GetTurnsUntilGrowthColor( turns:number ) if turns < 1 then return "StatBadCS"; end return "StatGoodCS"; end function GetPercentGrowthColor( percent:number ) if percent == 0 then return "Error"; end if percent <= 0.25 then return "WarningMajor"; end if percent <= 0.5 then return "WarningMinor"; end return "StatNormalCS"; end -- =========================================================================== -- Changes the yield focus. -- =========================================================================== function SetYieldFocus( yieldType:number ) local pCitizens :table = g_pCity:GetCitizens(); local tParameters :table = {}; tParameters[CityCommandTypes.PARAM_FLAGS] = 0; -- Set Favored tParameters[CityCommandTypes.PARAM_YIELD_TYPE] = yieldType; -- Yield type if pCitizens:IsFavoredYield(yieldType) then tParameters[CityCommandTypes.PARAM_DATA0]= 0; -- boolean (1=true, 0=false) else if pCitizens:IsDisfavoredYield(yieldType) then SetYieldIgnore(yieldType); end tParameters[CityCommandTypes.PARAM_DATA0] = 1; -- boolean (1=true, 0=false) end CityManager.RequestCommand(g_pCity, CityCommandTypes.SET_FOCUS, tParameters); end -- =========================================================================== -- Changes what yield type(s) should be ignored by citizens -- =========================================================================== function SetYieldIgnore( yieldType:number ) local pCitizens :table = g_pCity:GetCitizens(); local tParameters :table = {}; tParameters[CityCommandTypes.PARAM_FLAGS] = 1; -- Set Ignored tParameters[CityCommandTypes.PARAM_YIELD_TYPE] = yieldType; -- Yield type if pCitizens:IsDisfavoredYield(yieldType) then tParameters[CityCommandTypes.PARAM_DATA0]= 0; -- boolean (1=true, 0=false) else if ( pCitizens:IsFavoredYield(yieldType) ) then SetYieldFocus(yieldType); end tParameters[CityCommandTypes.PARAM_DATA0] = 1; -- boolean (1=true, 0=false) end CityManager.RequestCommand(g_pCity, CityCommandTypes.SET_FOCUS, tParameters); end -- =========================================================================== -- Update both the data & view for the selected city. -- =========================================================================== function Refresh() local eLocalPlayer :number = Game.GetLocalPlayer(); m_pPlayer= Players[eLocalPlayer]; g_pCity = UI.GetHeadSelectedCity(); if m_pPlayer ~= nil and g_pCity ~= nil then m_kData = GetCityData( g_pCity ); if m_kData == nil then return; end ViewMain( m_kData ); -- Tell others (e.g., CityPanelOverview) that the selected city data has changed. -- Passing this large table across contexts via LuaEvent is *much* -- more effecient than recomputing the entire set of yields a second time, -- despite the large size. LuaEvents.CityPanel_LiveCityDataChanged( m_kData, true ); end end -- =========================================================================== function RefreshIfMatch( ownerPlayerID:number, cityID:number ) if g_pCity ~= nil and ownerPlayerID == g_pCity:GetOwner() and cityID == g_pCity:GetID() then Refresh(); end end -- =========================================================================== -- GAME Event -- =========================================================================== function OnCityAddedToMap( ownerPlayerID:number, cityID:number ) if Game.GetLocalPlayer() ~= nil then if ownerPlayerID == Game.GetLocalPlayer() then local pSelectedCity:table = UI.GetHeadSelectedCity(); if pSelectedCity ~= nil then Refresh(); else UI.DeselectAllCities(); end end end end function OnCityNameChanged( playerID:number, cityID:number ) local city = UI.GetHeadSelectedCity(); if(city and city:GetOwner() == playerID and city:GetID() == cityID) then local name = city:IsCapital() and "[ICON_Capital]" or ""; name = name .. Locale.ToUpper(Locale.Lookup(city:GetName())); Controls.CityName:SetText(name); end end -- =========================================================================== -- GAME Event -- Yield changes -- =========================================================================== function OnCityFocusChange(ownerPlayerID:number, cityID:number) RefreshIfMatch(ownerPlayerID, cityID); end -- =========================================================================== -- GAME Event -- =========================================================================== function OnCityWorkerChanged(ownerPlayerID:number, cityID:number) RefreshIfMatch(ownerPlayerID, cityID); end -- =========================================================================== -- GAME Event -- =========================================================================== function OnCityProductionChanged(ownerPlayerID:number, cityID:number) -- CUI >> if Controls.ChangeProductionCheck:IsChecked() then Controls.ChangeProductionCheck:SetCheck(false); end -- << CUI RefreshIfMatch(ownerPlayerID, cityID); end -- =========================================================================== -- GAME Event -- =========================================================================== function OnCityProductionCompleted(ownerPlayerID:number, cityID:number) RefreshIfMatch(ownerPlayerID, cityID); end -- =========================================================================== -- GAME Event -- =========================================================================== function OnCityProductionUpdated( ownerPlayerID:number, cityID:number, eProductionType, eProductionObject) RefreshIfMatch(ownerPlayerID, cityID); end -- =========================================================================== -- GAME Event -- =========================================================================== function OnPlayerResourceChanged( ownerPlayerID:number, resourceTypeID:number) if (Game.GetLocalPlayer() ~= nil and ownerPlayerID == Game.GetLocalPlayer()) then Refresh(); end end -- =========================================================================== -- GAME Event -- =========================================================================== function OnToggleOverviewPanel() if Controls.ToggleOverviewPanel:IsChecked() then LuaEvents.CityPanel_ShowOverviewPanel(true); else LuaEvents.CityPanel_ShowOverviewPanel(false); end end -- =========================================================================== function OnCitySelectionChanged( ownerPlayerID:number, cityID:number, i:number, j:number, k:number, isSelected:boolean, isEditable:boolean) if ownerPlayerID == Game.GetLocalPlayer() then if (isSelected) then -- Determine if we should switch to the SELECTION interface mode local shouldSwitchToSelection:boolean = UI.GetInterfaceMode() ~= InterfaceModeTypes.CITY_SELECTION; if UI.GetInterfaceMode() == InterfaceModeTypes.CITY_MANAGEMENT then HideGrowthTile(); shouldSwitchToSelection = false; end if UI.GetInterfaceMode() == InterfaceModeTypes.ICBM_STRIKE then -- During ICBM_STRIKE only switch to SELECTION if we're selecting a city -- which doesn't own the active missile silo local siloPlotX:number = UI.GetInterfaceModeParameter(CityCommandTypes.PARAM_X0); local siloPlotY:number = UI.GetInterfaceModeParameter(CityCommandTypes.PARAM_Y0); local siloPlot:table = Map.GetPlot(siloPlotX, siloPlotY); if siloPlot then local owningCity = Cities.GetPlotPurchaseCity(siloPlot); if owningCity:GetID() == cityID then shouldSwitchToSelection = false; end end end if UI.GetInterfaceMode() == InterfaceModeTypes.CITY_RANGE_ATTACK then -- During CITY_RANGE_ATTACK only switch to SELECTION if we're selecting a city -- which can't currently perform a ranged attack if CityManager.CanStartCommand( CityManager.GetCity(owningPlayerID, cityID), CityCommandTypes.RANGE_ATTACK ) then shouldSwitchToSelection = false; --we switch to selection mode briefly so that we can go back into CITY_RANGE_ATTACK with the correct settings UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); UI.SetInterfaceMode(InterfaceModeTypes.CITY_RANGE_ATTACK); end end if shouldSwitchToSelection then UI.SetInterfaceMode(InterfaceModeTypes.SELECTION); end OnToggleOverviewPanel(); ContextPtr:SetHide(false); -- Handle case where production panel is opened from clicking a city banener directly. local isProductionOpen:boolean = false; local uiProductionPanel:table = ContextPtr:LookUpControl("/InGame/ProductionPanel"); if uiProductionPanel and uiProductionPanel:IsHidden()==false then isProductionOpen = true; end if isProductionOpen then AnimateToWithProductionQueue(); else AnimateFromCloseToOpen(); end Refresh(); if UI.GetInterfaceMode() == InterfaceModeTypes.CITY_MANAGEMENT then DisplayGrowthTile(); end else Close(); -- Tell the CityPanelOverview a city was deselected LuaEvents.CityPanel_LiveCityDataChanged( nil, false ); end end end -- =========================================================================== function AnimateFromCloseToOpen() Controls.CityPanelAlpha:SetToBeginning(); Controls.CityPanelAlpha:Play(); Controls.CityPanelSlide:SetBeginVal(0,0); Controls.CityPanelSlide:SetEndVal(ANIM_OFFSET_OPEN,0); Controls.CityPanelSlide:SetToBeginning(); Controls.CityPanelSlide:Play(); end -- =========================================================================== function AnimateToWithProductionQueue() if IsRoomToPushOutPanel() then Controls.CityPanelSlide:SetEndVal(ANIM_OFFSET_OPEN_WITH_PRODUCTION_LIST,0); Controls.CityPanelSlide:RegisterEndCallback( function() Controls.CityPanelSlide:SetBeginVal(ANIM_OFFSET_OPEN_WITH_PRODUCTION_LIST,0); end ); Controls.CityPanelSlide:SetToBeginning(); Controls.CityPanelSlide:Play(); end end -- =========================================================================== function AnimateToOpenFromWithProductionQueue() if IsRoomToPushOutPanel() then Controls.CityPanelSlide:SetEndVal(ANIM_OFFSET_OPEN,0); Controls.CityPanelSlide:RegisterEndCallback( function() Controls.CityPanelSlide:SetBeginVal(ANIM_OFFSET_OPEN,0); end ); Controls.CityPanelSlide:SetToBeginning(); Controls.CityPanelSlide:Play(); end end -- =========================================================================== -- Is there enough room to push out the CityPanel, rather than just have -- the production list overlap it? -- =========================================================================== function IsRoomToPushOutPanel() local width, height = UIManager:GetScreenSizeVal(); -- Minimap showing; subtract how much space it takes up local uiMinimap:table = ContextPtr:LookUpControl("/InGame/MinimapPanel/MinimapContainer"); if uiMinimap then local minimapWidth, minimapHeight = uiMinimap:GetSizeVal(); width = width - minimapWidth; end return ( width > 850); -- Does remaining width have enough space for both? end -- =========================================================================== -- GAME Event -- =========================================================================== function OnUnitSelectionChanged( playerID:number, unitID:number, hexI:number, hexJ:number, hexK:number, isSelected:boolean, isEditable:boolean ) if playerID == Game.GetLocalPlayer() then if ContextPtr:IsHidden()==false then Close(); Controls.ToggleOverviewPanel:SetAndCall(false); end end end -- =========================================================================== function LateInitialize() -- Override in DLC, Expansion, and MODs for special initialization. end -- =========================================================================== -- UI Event -- =========================================================================== function OnInit( isHotload:boolean ) LateInitialize(); if isHotload then LuaEvents.GameDebug_GetValues( "CityPanel"); end m_isInitializing = false; Refresh(); end -- =========================================================================== -- UI EVENT -- =========================================================================== function OnShutdown() -- Cache values for hotloading... LuaEvents.GameDebug_AddValue("CityPanel", "isHidden", ContextPtr:IsHidden() ); -- Game Core Events Events.CityAddedToMap.Remove( OnCityAddedToMap ); Events.CityNameChanged.Remove( OnCityNameChanged ); Events.CitySelectionChanged.Remove( OnCitySelectionChanged ); Events.CityFocusChanged.Remove( OnCityFocusChange ); Events.CityProductionCompleted.Remove( OnCityProductionCompleted ); Events.CityProductionUpdated.Remove( OnCityProductionUpdated ); Events.CityProductionChanged.Remove( OnCityProductionChanged ); Events.CityWorkerChanged.Remove( OnCityWorkerChanged ); Events.DistrictDamageChanged.Remove( OnCityProductionChanged ); Events.LocalPlayerTurnBegin.Remove( OnLocalPlayerTurnBegin ); Events.ImprovementChanged.Remove( OnCityProductionChanged ); Events.InterfaceModeChanged.Remove( OnInterfaceModeChanged ); Events.LocalPlayerChanged.Remove( OnLocalPlayerChanged ); Events.PlayerResourceChanged.Remove( OnPlayerResourceChanged ); Events.UnitSelectionChanged.Remove( OnUnitSelectionChanged ); -- LUA Events LuaEvents.CityPanelOverview_CloseButton.Remove( OnCloseOverviewPanel ); LuaEvents.CityPanel_SetOverViewState.Remove( OnCityPanelSetOverViewState ); LuaEvents.CityPanel_ToggleManageCitizens.Remove( OnCityPanelToggleManageCitizens ); LuaEvents.GameDebug_Return.Remove( OnGameDebugReturn ); LuaEvents.ProductionPanel_Close.Remove( OnProductionPanelClose ); LuaEvents.ProductionPanel_ListModeChanged.Remove( OnProductionPanelListModeChanged ); LuaEvents.ProductionPanel_Open.Remove( OnProductionPanelOpen ); LuaEvents.Tutorial_CityPanelOpen.Remove( OnTutorialOpen ); LuaEvents.Tutorial_ContextDisableItems.Remove( OnTutorial_ContextDisableItems ); end -- =========================================================================== -- LUA Event -- Set cached values back after a hotload. -- =========================================================================== function OnGameDebugReturn( context:string, contextTable:table ) function RunWithNoError() if context ~= "CityPanel" or contextTable == nil then return; end local isHidden:boolean = contextTable["isHidden"]; ContextPtr:SetHide( isHidden ); end pcall( RunWithNoError ); end -- =========================================================================== -- LUA Event -- =========================================================================== function OnProductionPanelClose() -- If no longer checked, make sure the side Production Panel closes. -- Clear the checks, even if hidden, the Production Pane can close after the City Panel has already been closed. Controls.ChangeProductionCheck:SetCheck( false ); Controls.ProduceWithFaithCheck:SetCheck( false ); Controls.ProduceWithGoldCheck:SetCheck( false ); AnimateToOpenFromWithProductionQueue(); end -- =========================================================================== -- LUA Event -- =========================================================================== function OnProductionPanelOpen() AnimateToWithProductionQueue(); end -- =========================================================================== -- LUA Event -- =========================================================================== function OnTutorialOpen() ContextPtr:SetHide(false); Refresh(); end -- =========================================================================== function OnBreakdown() LuaEvents.CityPanel_ShowBreakdownTab(); end -- =========================================================================== function OnReligion() LuaEvents.CityPanel_ShowReligionTab(); end -- =========================================================================== function OnAmenities() LuaEvents.CityPanel_ShowAmenitiesTab(); end -- =========================================================================== function OnHousing() LuaEvents.CityPanel_ShowHousingTab(); end -- =========================================================================== --function OnCheckQueue() -- if m_isInitializing then return; end -- if not m_debugAllowMultiPanel then -- UILens.ToggleLayerOff("Adjacency_Bonus_Districts"); -- UILens.ToggleLayerOff("Districts"); -- end -- Refresh(); --end -- =========================================================================== function OnCitizensGrowth() LuaEvents.CityPanel_ShowCitizensTab(); end -- =========================================================================== -- Set a yield to one of 3 check states. -- yieldType Enum from game engine on the yield -- yieldName Name of the yield used in the UI controls -- =========================================================================== function OnCheckYield( yieldType:number, yieldName:string ) if Controls.YieldsArea:IsDisabled() then return; end -- Via tutorial event if Controls[yieldName.."Check"]:IsChecked() then SetYieldFocus( yieldType ); else SetYieldIgnore( yieldType ); Controls[yieldName.."Ignore"]:SetHide( false ); Controls[yieldName.."Check"]:SetDisabled( true ); end end -- =========================================================================== -- Reset a yield to not be favored nor ignored -- yieldType Enum from game engine on the yield -- yieldName Name of the yield used in the UI controls -- =========================================================================== function OnResetYieldToNormal( yieldType:number, yieldName:string ) if Controls.YieldsArea:IsDisabled() then return; end -- Via tutorial event Controls[yieldName.."Ignore"]:SetHide( true ); Controls[yieldName.."Check"]:SetDisabled( false ); SetYieldIgnore( yieldType ); -- One more ignore to flip it off end -- =========================================================================== -- Cycle to the next city -- =========================================================================== function OnNextCity() local kCity:table = UI.GetHeadSelectedCity(); UI.SelectNextCity(kCity); UI.PlaySound("UI_Click_Sweetener_Metal_Button_Small"); end -- =========================================================================== -- Cycle to the previous city -- =========================================================================== function OnPreviousCity() local kCity:table = UI.GetHeadSelectedCity(); UI.SelectPrevCity(kCity); UI.PlaySound("UI_Click_Sweetener_Metal_Button_Small"); end -- =========================================================================== -- Recenter camera on city -- =========================================================================== function RecenterCameraOnCity() local kCity:table = UI.GetHeadSelectedCity(); UI.LookAtPlot( kCity:GetX(), kCity:GetY() ); end -- CUI ----------------------------------------------------------------------- -- combine purchase tile and manage cityzens function CuiOnToggleManageTile() if Controls.ManageTileCheck:IsChecked() then UI.SetInterfaceMode(InterfaceModeTypes.CITY_MANAGEMENT) CuiForceHideCityBanner() RecenterCameraOnCity() UILens.ToggleLayerOn(m_CitizenManagement) if GameCapabilities.HasCapability("CAPABILITY_GOLD") then UILens.ToggleLayerOn(m_PurchasePlot) end else UI.SetInterfaceMode(InterfaceModeTypes.SELECTION) CuiForceShowCityBanner() UILens.ToggleLayerOff(m_CitizenManagement) UILens.ToggleLayerOff(m_PurchasePlot) end end -- =========================================================================== -- Turn on/off layers and switch the interface mode based on what is checked. -- Interface mode is changed first as the Lens system may inquire as to the -- current state in deciding what is populate in a lens layer. -- =========================================================================== function OnTogglePurchaseTile() if Controls.PurchaseTileCheck:IsChecked() then if not Controls.ManageCitizensCheck:IsChecked() then m_PrevInterfaceMode = UI.GetInterfaceMode(); UI.SetInterfaceMode(InterfaceModeTypes.CITY_MANAGEMENT); -- Enter mode end RecenterCameraOnCity(); UILens.ToggleLayerOn( m_PurchasePlot ); else if not Controls.ManageCitizensCheck:IsChecked() and UI.GetInterfaceMode() == InterfaceModeTypes.CITY_MANAGEMENT then UI.SetInterfaceMode(m_PrevInterfaceMode); -- Exit mode m_PrevInterfaceMode = InterfaceModeTypes.SELECTION; end UILens.ToggleLayerOff( m_PurchasePlot ); end end -- =========================================================================== function OnToggleProduction() if Controls.ChangeProductionCheck:IsChecked() then RecenterCameraOnCity(); LuaEvents.CityPanel_ProductionOpen(); -- CUI >> Controls.ProduceWithFaithCheck:SetCheck(false); Controls.ProduceWithGoldCheck:SetCheck(false); -- << CUI else LuaEvents.CityPanel_ProductionClose(); end end -- =========================================================================== function OnTogglePurchaseWithGold() if Controls.ProduceWithGoldCheck:IsChecked() then RecenterCameraOnCity(); LuaEvents.CityPanel_PurchaseGoldOpen(); -- CUI >> Controls.ChangeProductionCheck:SetCheck(false); Controls.ProduceWithFaithCheck:SetCheck(false); -- << CUI else LuaEvents.CityPanel_ProductionClose(); end end -- =========================================================================== function OnTogglePurchaseWithFaith() if Controls.ProduceWithFaithCheck:IsChecked() then RecenterCameraOnCity(); LuaEvents.CityPanel_PurchaseFaithOpen(); -- CUI >> Controls.ChangeProductionCheck:SetCheck(false); Controls.ProduceWithGoldCheck:SetCheck(false); -- << CUI else LuaEvents.CityPanel_ProductionClose(); end end -- =========================================================================== function OnCloseOverviewPanel() Controls.ToggleOverviewPanel:SetCheck(false); end -- =========================================================================== -- Turn on/off layers and switch the interface mode based on what is checked. -- Interface mode is changed first as the Lens system may inquire as to the -- current state in deciding what is populate in a lens layer. -- =========================================================================== function OnToggleManageCitizens() if Controls.ManageCitizensCheck:IsChecked() then if not Controls.PurchaseTileCheck:IsChecked() then m_PrevInterfaceMode = UI.GetInterfaceMode(); UI.SetInterfaceMode(InterfaceModeTypes.CITY_MANAGEMENT); -- Enter mode end RecenterCameraOnCity(); UILens.ToggleLayerOn( m_CitizenManagement ); else if not Controls.PurchaseTileCheck:IsChecked() and UI.GetInterfaceMode() == InterfaceModeTypes.CITY_MANAGEMENT then UI.SetInterfaceMode(m_PrevInterfaceMode); -- Exit mode m_PrevInterfaceMode = InterfaceModeTypes.SELECTION; end UILens.ToggleLayerOff( m_CitizenManagement ); end end -- =========================================================================== function OnLocalPlayerTurnBegin() Refresh(); end -- =========================================================================== -- Enable a control unless it's in the tutorial lock down list. -- =========================================================================== function EnableIfNotTutorialBlocked( controlName:string ) local isDisabled :boolean = false; if m_kTutorialDisabledControls ~= nil then for _,name in ipairs(m_kTutorialDisabledControls) do if name == controlName then isDisabled = true; break; end end end Controls[ controlName ]:SetDisabled( isDisabled ); end function OnCameraUpdate( vFocusX:number, vFocusY:number, fZoomLevel:number ) if g_growthPlotId ~= -1 then if fZoomLevel and fZoomLevel > 0.5 then local delta:number = (fZoomLevel - 0.3); local alpha:number = delta / 0.7; Controls.GrowthHexAlpha:SetProgress(alpha); else Controls.GrowthHexAlpha:SetProgress(0); end local plotX:number, plotY:number = Map.GetPlotLocation(g_growthPlotId); local worldX:number, worldY:number, worldZ:number = UI.GridToWorld(plotX, plotY); Controls.GrowthHexAnchor:SetWorldPositionVal(worldX, worldY + HEX_GROWTH_TEXT_PADDING, worldZ); end end function DisplayGrowthTile() if g_pCity ~= nil and HasCapability("CAPABILITY_CULTURE") then local cityCulture:table = g_pCity:GetCulture(); if cityCulture ~= nil then local newGrowthPlot:number = cityCulture:GetNextPlot(); if(newGrowthPlot ~= -1 and newGrowthPlot ~= g_growthPlotId) then g_growthPlotId = newGrowthPlot; local cost:number = cityCulture:GetNextPlotCultureCost(); local currentCulture:number = cityCulture:GetCurrentCulture(); local currentYield:number = cityCulture:GetCultureYield(); local currentGrowth:number = math.max(math.min(currentCulture / cost, 1.0), 0); local nextTurnGrowth:number = math.max(math.min((currentCulture + currentYield) / cost, 1.0), 0); UILens.SetLayerGrowthHex(m_PurchasePlot, Game.GetLocalPlayer(), g_growthPlotId, 1, "GrowthHexBG"); UILens.SetLayerGrowthHex(m_PurchasePlot, Game.GetLocalPlayer(), g_growthPlotId, nextTurnGrowth, "GrowthHexNext"); UILens.SetLayerGrowthHex(m_PurchasePlot, Game.GetLocalPlayer(), g_growthPlotId, currentGrowth, "GrowthHexCurrent"); local turnsRemaining:number = cityCulture:GetTurnsUntilExpansion(); Controls.TurnsLeftDescription:SetText(Locale.ToUpper(Locale.Lookup("LOC_HUD_CITY_TURNS_UNTIL_BORDER_GROWTH", turnsRemaining))); Controls.TurnsLeftLabel:SetText(turnsRemaining); Controls.GrowthHexStack:CalculateSize(); g_growthHexTextWidth = Controls.GrowthHexStack:GetSizeX(); Events.Camera_Updated.Add(OnCameraUpdate); Events.CityMadePurchase.Add(OnCityMadePurchase); Controls.GrowthHexAnchor:SetHide(false); OnCameraUpdate(); end end end end function HideGrowthTile() if g_growthPlotId ~= -1 then Controls.GrowthHexAnchor:SetHide(true); Events.Camera_Updated.Remove(OnCameraUpdate); Events.CityMadePurchase.Remove(OnCityMadePurchase); UILens.ClearHex(m_PurchasePlot, g_growthPlotId); g_growthPlotId = -1; end end function OnCityMadePurchase(owner:number, cityID:number, plotX:number, plotY:number, purchaseType, objectType) if g_growthPlotId ~= -1 then local growthPlotX:number, growthPlotY:number = Map.GetPlotLocation(g_growthPlotId); if (growthPlotX == plotX and growthPlotY == plotY) then HideGrowthTile(); DisplayGrowthTile(); end end end -- =========================================================================== function OnProductionPanelListModeChanged( listMode:number ) Controls.ChangeProductionCheck:SetCheck(listMode == LISTMODE.PRODUCTION or listMode == LISTMODE.PROD_QUEUE); Controls.ProduceWithGoldCheck:SetCheck(listMode == LISTMODE.PURCHASE_GOLD); Controls.ProduceWithFaithCheck:SetCheck(listMode == LISTMODE.PURCHASE_FAITH); end -- =========================================================================== function OnCityPanelSetOverViewState( isOpened:boolean ) Controls.ToggleOverviewPanel:SetCheck(isOpened); end -- =========================================================================== function OnCityPanelToggleManageCitizens() Controls.ManageCitizensCheck:SetAndCall(not Controls.ManageCitizensCheck:IsChecked()); end -- =========================================================================== -- GAME Event -- eOldMode, mode the engine was formally in -- eNewMode, new mode the engine has just changed to -- =========================================================================== function OnInterfaceModeChanged( eOldMode:number, eNewMode:number ) if eOldMode == InterfaceModeTypes.CITY_MANAGEMENT then -- CUI >> combine buttons. if Controls.ManageTileCheck:IsChecked() then Controls.ManageTileCheck:SetAndCall(false); end -- if Controls.PurchaseTileCheck:IsChecked() then Controls.PurchaseTileCheck:SetAndCall( false ); end -- if Controls.ManageCitizensCheck:IsChecked() then Controls.ManageCitizensCheck:SetAndCall( false ); end -- << CUI UI.SetFixedTiltMode( false ); HideGrowthTile(); elseif eOldMode == InterfaceModeTypes.DISTRICT_PLACEMENT or eOldMode == InterfaceModeTypes.BUILDING_PLACEMENT then HideGrowthTile(); end if eNewMode == InterfaceModeTypes.CITY_MANAGEMENT then DisplayGrowthTile(); end if eNewMode == InterfaceModeTypes.CITY_RANGE_ATTACK or eNewMode == InterfaceModeTypes.DISTRICT_RANGE_ATTACK then if ContextPtr:IsHidden()==false then Close(); end elseif eOldMode == InterfaceModeTypes.CITY_RANGE_ATTACK or eOldMode == InterfaceModeTypes.DISTRICT_RANGE_ATTACK then -- If we leave CITY_RANGE_ATTACK with a city selected then show the city panel again if UI.GetHeadSelectedCity() then ContextPtr:SetHide(false); end end if eNewMode == InterfaceModeTypes.SELECTION or eNewMode == InterfaceModeTypes.CITY_MANAGEMENT then -- CUI >> combine buttons. EnableIfNotTutorialBlocked("ManageTileCheck"); -- EnableIfNotTutorialBlocked("PurchaseTileCheck"); -- EnableIfNotTutorialBlocked("ManageCitizensCheck"); -- << CUI EnableIfNotTutorialBlocked("ProduceWithFaithCheck"); EnableIfNotTutorialBlocked("ProduceWithGoldCheck"); EnableIfNotTutorialBlocked("ChangeProductionCheck"); elseif eNewMode == InterfaceModeTypes.DISTRICT_PLACEMENT then -- CUI >> combine buttons. Controls.ManageTileCheck:SetDisabled(true); -- Controls.PurchaseTileCheck:SetDisabled( true ); -- Controls.ManageCitizensCheck:SetDisabled( true ); -- << CUI Controls.ChangeProductionCheck:SetDisabled( true ); Controls.ProduceWithFaithCheck:SetDisabled( true ); Controls.ProduceWithGoldCheck:SetDisabled( true ); local newGrowthPlot:number = g_pCity:GetCulture():GetNextPlot(); --show the growth tile if the district can be placed there if(newGrowthPlot ~= -1) then local districtHash:number = UI.GetInterfaceModeParameter(CityOperationTypes.PARAM_DISTRICT_TYPE); local district:table = GameInfo.Districts[districtHash]; local kPlot :table = Map.GetPlotByIndex(newGrowthPlot); if kPlot:CanHaveDistrict(district.Index, g_pCity:GetOwner(), g_pCity:GetID()) then DisplayGrowthTile(); end end elseif eNewMode == InterfaceModeTypes.BUILDING_PLACEMENT then local newGrowthPlot:number = g_pCity:GetCulture():GetNextPlot(); if(newGrowthPlot ~= -1) then local buildingHash :number = UI.GetInterfaceModeParameter(CityOperationTypes.PARAM_BUILDING_TYPE); local building = GameInfo.Buildings[buildingHash]; local kPlot :table = Map.GetPlotByIndex(newGrowthPlot); if kPlot:CanHaveWonder(building.Index, g_pCity:GetOwner(), g_pCity:GetID()) then DisplayGrowthTile(); end end end if not ContextPtr:IsHidden() then ViewMain( m_kData ); end end -- =========================================================================== -- Engine EVENT -- Local player changed; likely a hotseat game -- =========================================================================== function OnLocalPlayerChanged( eLocalPlayer:number , ePrevLocalPlayer:number ) if eLocalPlayer == -1 then m_pPlayer = nil; return; end m_pPlayer = Players[eLocalPlayer]; if ContextPtr:IsHidden()==false then Close(); end end -- =========================================================================== -- Show/hide an area based on the status of a checkbox control -- checkBoxControl A checkbox control that when selected is open -- buttonControl (optional) button control that toggles the state -- areaControl The area to be shown/hidden -- kParentControls DEPRECATED, not needed -- =========================================================================== function SetupCollapsibleToggle( pCheckBoxControl:table, pButtonControl:table, pAreaControl:table, kParentControls:table ) pCheckBoxControl:RegisterCheckHandler( function() pAreaControl:SetHide( pCheckBoxControl:IsChecked() ); end ); if pButtonControl ~= nil then pButtonControl:RegisterCallback( Mouse.eLClick, function() pCheckBoxControl:SetAndCall( not pCheckBoxControl:IsChecked() ); end ); end end -- =========================================================================== -- LUA Event -- Tutorial requests controls that should always be locked down. -- Send nil to clear. -- =========================================================================== function OnTutorial_ContextDisableItems( contextName:string, kIdsToDisable:table ) if contextName~="CityPanel" then return; end -- Enable any existing controls that are disabled if m_kTutorialDisabledControls ~= nil then for _,name in ipairs(m_kTutorialDisabledControls) do if Controls[name] ~= nil then Controls[name]:SetDisabled(false); end end end m_kTutorialDisabledControls = kIdsToDisable; -- Immediate set disabled if m_kTutorialDisabledControls ~= nil then for _,name in ipairs(m_kTutorialDisabledControls) do if Controls[name] ~= nil then Controls[name]:SetDisabled(true); else UI.DataError("Tutorial requested the control '"..name.."' be disabled in the city panel, but no such control exists in that context."); end end end end -- CUI ----------------------------------------------------------------------- function CuiGetFoodToolTip(data) local foodToolTip = -- vanila tooltip data.FoodPerTurnToolTip .. "[NEWLINE][NEWLINE]" .. -- food consumption toPlusMinusString(-(data.FoodPerTurn - data.FoodSurplus)) .. " " .. Locale.Lookup("LOC_HUD_CITY_FOOD_CONSUMPTION") .. "[NEWLINE]------------------[NEWLINE]" .. -- happiness GetColorPercentString(1 + data.HappinessGrowthModifier / 100, 2) .. " " .. Locale.Lookup("LOC_HUD_CITY_HAPPINESS_GROWTH_BONUS") .. "[NEWLINE]" .. -- other GetColorPercentString(1 + Round(data.OtherGrowthModifiers, 2), 2) .. " " .. Locale.Lookup("LOC_HUD_CITY_OTHER_GROWTH_BONUSES") .. "[NEWLINE]" .. -- housing GetColorPercentString(data.HousingMultiplier, 2) .. " " .. Locale.Lookup("LOC_HUD_CITY_HOUSING_CAPACITY") if data.Occupied then foodToolTip = foodToolTip .. "[NEWLINE]" .. "x" .. data.OccupationMultiplier .. Locale.Lookup("LOC_HUD_CITY_OCCUPATION_MULTIPLIER") end return foodToolTip end -- CUI ----------------------------------------------------------------------- function CuiGetFoodPerTurn(data) local modifiedFood local foodPerTurn if data.TurnsUntilGrowth > -1 then local growthModifier = math.max(1 + (data.HappinessGrowthModifier / 100) + data.OtherGrowthModifiers, 0) modifiedFood = Round(data.FoodSurplus * growthModifier, 2) if data.Occupied then foodPerTurn = modifiedFood * data.OccupationMultiplier else foodPerTurn = modifiedFood * data.HousingMultiplier end else foodPerTurn = data.FoodSurplus end return foodPerTurn end -- CUI ----------------------------------------------------------------------- function CuiForceHideCityBanner() CuiSettings:SetBoolean(CuiSettings.SHOW_CITYS, false) ContextPtr:LookUpControl("/InGame/CityBannerManager"):SetHide(true) LuaEvents.MinimapPanel_RefreshMinimapOptions() end -- CUI ----------------------------------------------------------------------- function CuiForceShowCityBanner() CuiSettings:SetBoolean(CuiSettings.SHOW_CITYS, true) ContextPtr:LookUpControl("/InGame/CityBannerManager"):SetHide(false) LuaEvents.MinimapPanel_RefreshMinimapOptions() end -- =========================================================================== -- CTOR -- =========================================================================== function Initialize() LuaEvents.CityPanel_OpenOverview(); m_isInitializing = true; -- Context Events ContextPtr:SetInitHandler( OnInit ); ContextPtr:SetShutdown( OnShutdown ); -- Control Events Controls.BreakdownButton:RegisterCallback( Mouse.eLClick, OnBreakdown ); Controls.ReligionButton:RegisterCallback( Mouse.eLClick, OnReligion ); Controls.AmenitiesButton:RegisterCallback( Mouse.eLClick, OnAmenities ); Controls.HousingButton:RegisterCallback( Mouse.eLClick, OnHousing ); Controls.CitizensGrowthButton:RegisterCallback( Mouse.eLClick, OnCitizensGrowth ); Controls.CultureCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.CULTURE, "Culture"); end ); Controls.FaithCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.FAITH, "Faith"); end ); Controls.FoodCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.FOOD, "Food"); end ); Controls.GoldCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.GOLD, "Gold"); end ); Controls.ProductionCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.PRODUCTION, "Production"); end ); Controls.ScienceCheck:RegisterCheckHandler( function() OnCheckYield( YieldTypes.SCIENCE, "Science"); end ); Controls.CultureIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.CULTURE, "Culture"); end); Controls.FaithIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.FAITH, "Faith"); end); Controls.FoodIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.FOOD, "Food"); end); Controls.GoldIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.GOLD, "Gold"); end); Controls.ProductionIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.PRODUCTION, "Production"); end); Controls.ScienceIgnore:RegisterCallback( Mouse.eLClick, function() OnResetYieldToNormal( YieldTypes.SCIENCE, "Science"); end); Controls.NextCityButton:RegisterCallback( Mouse.eLClick, OnNextCity); Controls.PrevCityButton:RegisterCallback( Mouse.eLClick, OnPreviousCity); if GameCapabilities.HasCapability("CAPABILITY_GOLD") then -- CUI >> combine buttons. -- Controls.PurchaseTileCheck:RegisterCheckHandler(OnTogglePurchaseTile ); -- Controls.PurchaseTileCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); -- << CUI Controls.ProduceWithGoldCheck:RegisterCheckHandler( OnTogglePurchaseWithGold ); Controls.ProduceWithGoldCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); else Controls.PurchaseTileCheck:SetHide(true); Controls.ProduceWithGoldCheck:SetHide(true); end -- CUI >> combine buttons. Controls.ManageTileCheck:RegisterCheckHandler(CuiOnToggleManageTile); Controls.ManageTileCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over") end ); -- Controls.ManageCitizensCheck:RegisterCheckHandler( OnToggleManageCitizens ); -- Controls.ManageCitizensCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); -- << CUI Controls.ChangeProductionCheck:RegisterCheckHandler( OnToggleProduction ); Controls.ChangeProductionCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.ProduceWithFaithCheck:RegisterCheckHandler( OnTogglePurchaseWithFaith ); Controls.ProduceWithFaithCheck:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); Controls.ToggleOverviewPanel:RegisterCheckHandler( OnToggleOverviewPanel ); Controls.ToggleOverviewPanel:RegisterCallback( Mouse.eMouseEnter, function() UI.PlaySound("Main_Menu_Mouse_Over"); end); -- Game Core Events Events.CityAddedToMap.Add( OnCityAddedToMap ); Events.CityNameChanged.Add( OnCityNameChanged ); Events.CitySelectionChanged.Add( OnCitySelectionChanged ); Events.CityFocusChanged.Add( OnCityFocusChange ); Events.CityProductionCompleted.Add( OnCityProductionCompleted ); Events.CityProductionUpdated.Add( OnCityProductionUpdated ); Events.CityProductionChanged.Add( OnCityProductionChanged ); Events.CityWorkerChanged.Add( OnCityWorkerChanged ); Events.DistrictDamageChanged.Add( OnCityProductionChanged ); Events.LocalPlayerTurnBegin.Add( OnLocalPlayerTurnBegin ); Events.ImprovementChanged.Add( OnCityProductionChanged ); Events.InterfaceModeChanged.Add( OnInterfaceModeChanged ); Events.LocalPlayerChanged.Add( OnLocalPlayerChanged ); Events.PlayerResourceChanged.Add( OnPlayerResourceChanged ); Events.UnitSelectionChanged.Add( OnUnitSelectionChanged ); -- LUA Events LuaEvents.CityPanelOverview_CloseButton.Add( OnCloseOverviewPanel ); LuaEvents.CityPanel_SetOverViewState.Add( OnCityPanelSetOverViewState ); -- CUI >> combine buttons. -- LuaEvents.CityPanel_ToggleManageCitizens.Add( OnCityPanelToggleManageCitizens ); LuaEvents.CityPanel_ToggleManageCitizens.Add( function() Controls.ManageTileCheck:SetAndCall(not Controls.ManageTileCheck:IsChecked()) end ); -- << CUI LuaEvents.GameDebug_Return.Add( OnGameDebugReturn ); LuaEvents.ProductionPanel_Close.Add( OnProductionPanelClose ); LuaEvents.ProductionPanel_ListModeChanged.Add( OnProductionPanelListModeChanged ); LuaEvents.ProductionPanel_Open.Add( OnProductionPanelOpen ); LuaEvents.Tutorial_CityPanelOpen.Add( OnTutorialOpen ); LuaEvents.Tutorial_ContextDisableItems.Add( OnTutorial_ContextDisableItems ); -- Truncate possible static text overflows TruncateStringWithTooltip(Controls.BreakdownLabel, MAX_BEFORE_TRUNC_STATIC_LABELS, Controls.BreakdownLabel:GetText()); TruncateStringWithTooltip(Controls.ReligionLabel, MAX_BEFORE_TRUNC_STATIC_LABELS, Controls.ReligionLabel:GetText()); TruncateStringWithTooltip(Controls.AmenitiesLabel, MAX_BEFORE_TRUNC_STATIC_LABELS, Controls.AmenitiesLabel:GetText()); TruncateStringWithTooltip(Controls.HousingLabel, MAX_BEFORE_TRUNC_STATIC_LABELS, Controls.HousingLabel:GetText()); end Initialize();
include "luaClass.class.namespace" include "luaClass.class.config.init" _ENV=namespace "luaClass" LPublic={} LPublic.__index=LPublic function LPublic:new(memberTable) local object={ members=memberTable; } setmetatable(object,self) return object end function LPublic:implement(classObject) local members=classObject.__public_member local protectedMembers=classObject.__protected_member local decl=classObject.__decl local funcTable=classObject.__function local meta=classObject.__metaMethod if classObject.__debug then for _,member in pairs(self.members) do member:check(true) if member.ctype=="function" then decl[member.key]="publicFunction" funcTable[member.key]=member.object elseif member.ctype=="member" then decl[member.key]="publicMember" members[member.key]=member.object elseif member.ctype=="static" then decl[member.key]="publicStatic" classObject[member.key]=member.object elseif member.ctype=="const" then decl[member.key]="publicConst" protectedMembers[member.key]=member.object elseif member.ctype=="staticFunction" then decl[member.key]="publicStaticFunction" funcTable[member.key]=member.object elseif member.ctype=="meta" then meta[member.key]=member.object classObject[member.key]=member.object end end else for _,member in pairs(self.members) do member:check(false) if member.ctype=="function" then decl[member.key]="publicFunction" classObject[member.key]=member.object elseif member.ctype=="member" then decl[member.key]="publicMember" members[member.key]=member.object elseif member.ctype=="static" then decl[member.key]="publicStatic" classObject[member.key]=member.object elseif member.ctype=="const" then decl[member.key]="publicConst" members[member.key]=member.object elseif member.ctype=="staticFunction" then decl[member.key]="publicStaticFunction" classObject[member.key]=member.object elseif member.ctype=="meta" then meta[member.key]=member.object classObject[member.key]=member.object end end end end function public(memberTable) return LPublic:new(memberTable) end
awful = require("awful") settings = require("settings") beautiful = require("beautiful") local dpi = beautiful.xresources.apply_dpi wibox = require("wibox") naughty = require "naughty" menubar = require "menubar" gears = require "gears" math = require "math" --[[ Entry needs to store: Icon Children? Name Tooltip? Launch ]] local mainmenu = { menutree = { }, box = nil, mainmenuwidget = nil, listwidget = nil, categories = {}, displaystate = { openpath = {}, extensions = {} } } --forward function decleartions local update_tree_menu, log, close_extensions_above local function min(a, b) if(a < b) then return a end return b end local function itemheight(items) items = items or 1 return beautiful.menu_height * items end local function mainmenuheight() return itemheight(2 + min(#mainmenu.menutree, settings.desktop.startmenuentries)) end local function frombottom(items) return mainmenuheight() - itemheight(items) end local function force_close() if mainmenu.box.visible then mainmenu.toggle() end close_extensions_above(1) end local function runentry(entry) local exec = entry.exec exec = exec:gsub("%%U", "") exec = exec:gsub("%%u", "") exec = exec:gsub("%%F", "") --naughty.notify{text = "Starting " .. entry.name .. " with command \"" .. exec .. "\""} awful.spawn(exec) end local function clickhandler(sender) local entry = sender.entry entry:click() force_close() end local function item_enter(sender) local depth = sender.entry.depth mainmenu.displaystate.openpath[depth] = sender.entry mainmenu.displaystate.openpath[depth+1] = nil update_tree_menu() end local function item_leave(sender, hit_data) local depth = sender.entry.depth local coords = mouse.coords() if coords.x >= hit_data.width then return end mainmenu.displaystate.openpath[depth] = nil update_tree_menu() end local function try_load_icon(icon) if icon == nil then return nil end local icon_path = menubar.utils.lookup_icon(icon) if icon_path == nil then return nil end local img = gears.surface.load(icon_path) if img == nil then naughty.notify {text = "Did not load icon at " .. icon_path} end return img end local function entry_create_display_raw(text, icon_left, icon_right) local textwidth = beautiful.menu_width - beautiful.menu_height + 4 local icon2 = nil if icon_right ~= nil then icon2 = wibox.widget { widget = wibox.widget.imagebox, forced_width = beautiful.menu_height, forced_height = beautiful.menu_height, image = icon_right, point = {y = 0, x = textwidth} } textwidth = textwidth - beautiful.menu_height end local display_item = wibox.container { wibox.layout { layout = wibox.layout.manual, forced_height = beautiful.menu_height, wibox.widget { widget = wibox.widget.imagebox, --Should be square with size fitting in menu, so it be width = height forced_width = beautiful.menu_height, forced_height = beautiful.menu_height, --resize_allowed = true, --clip_shape = gears.shape.rectangle, image = icon_left, point = {y = 0, x = 0} }, wibox.widget { widget = wibox.widget.textbox, point = {y = 0, x = beautiful.menu_height}, forced_width = textwidth, forced_height = beautiful.menu_height, text = text }, icon2 }, widget = wibox.container.background } display_item:connect_signal("mouse::enter", item_enter) display_item:connect_signal("mouse::leave", item_leave) return display_item end local function entry_create_from_program(program) if program.Icon == nil then naughty.notify {text = program.Name .. " has no icon"} end local final = { name = program.Name, icon = program.Icon, exec = program.Exec, working_directory = program.Path, terminal = program.Terminal, click = runentry, display_item = entry_create_display_raw(program.Name, try_load_icon(program.Icon)) } final.display_item.entry = final final.display_item:connect_signal("button::press", clickhandler) return final end local function get_category_entry(category_name) if mainmenu.categories[category_name] == nil then local entry = { name = category_name, display_item = entry_create_display_raw(category_name, nil, try_load_icon(beautiful.menu_submenu_icon)), children = {} } entry.display_item.entry = entry mainmenu.categories[category_name] = entry table.insert(mainmenu.menutree, entry) end return mainmenu.categories[category_name] end local function input_handler_state() return { text = "", cursor_pos = 1 } end local function input_handler(mod, key, event) if event == "release" then return end --update state local handlers = { ["Super_L"] = force_close, ["Escape"] = force_close, ["Left"] = function() if mainmenu.input_state.cursor_pos > 1 then mainmenu.input_state.cursor_pos = mainmenu.input_state.cursor_pos - 1 end end, ["Right"] = function() if mainmenu.input_state.cursor_pos < mainmenu.input_state.text:len() +1 then mainmenu.input_state.cursor_pos = mainmenu.input_state.cursor_pos + 1 end end, } local handler = handlers[key] if handler == nil then if(key:len() ~= 1) then naughty.notify {text = "Unhandled long key of " .. key} else mainmenu.input_state.text = mainmenu.input_state.text:sub(1, mainmenu.input_state.cursor_pos-1) .. key .. mainmenu.input_state.text:sub(mainmenu.input_state.cursor_pos ) mainmenu.input_state.cursor_pos = mainmenu.input_state.cursor_pos + 1 end elseif type(handler) == "function" then handler() else naughty.notify( {text = "non function handler for " .. key}) end --display updated state mainmenu.textbox.markup = "<b>" .. mainmenu.input_state.text .. "</b>" end --start of new lazy tree based system function log(text) naughty.notify {text = text} end local function list_first_n(list, n) local r = {} for i, v in ipairs(list) do table.insert(r, v) if i >= n then break end end return r end local function entry_ensure_display_item(entry) if entry.display_item ~= nil then return end entry.display_item = entry_create_display_raw(entry.name, try_load_icon(entry.icon)) entry.display_item.entry = entry end local function set_widget_entries(widget, entries) widget:reset() for i, entry in ipairs(entries) do entry.display_item.bg = beautiful.bg_normal entry_ensure_display_item(entry) entry.display_item.point = {y = itemheight(i-1), x = 0} entry.slot = i - 1 widget:add(entry.display_item) end end local function recursive_set_depth(menutree, depth) if depth == nil then depth = 1 end for i, v in ipairs(menutree) do v.depth = depth if v.children ~= nil then recursive_set_depth(v.children, depth+1) end end end local function get_or_create_extension_widget(depth) if mainmenu.displaystate.extensions[depth] == nil then local widget = wibox.layout { layout = wibox.layout.manual } mainmenu.displaystate.extensions[depth] = { widget = widget, box = wibox { ontop = true, width = beautiful.menu_width, y = 400, --placeholder, remove? x = beautiful.menu_width * depth, widget = widget } } end local extension = mainmenu.displaystate.extensions[depth] extension.box.visible = true return extension end function close_extensions_above(level) for i=level, #mainmenu.displaystate.extensions do mainmenu.displaystate.extensions[i].box.visible = false end end local function update_menu_level(list, widget, focus) local cutlist = list_first_n(list, settings.desktop.startmenuentries) set_widget_entries(widget, cutlist) if focus ~= nil then focus.display_item.bg =beautiful.bg_focus end end function update_tree_menu() --naughty.notify{text = "MENU!"} recursive_set_depth(mainmenu.menutree) --TODO: don't do every time --Actually update the menu update_menu_level(mainmenu.menutree, mainmenu.listwidget, mainmenu.displaystate.openpath[1]) local i = 1 local oldy = mainmenu.box.y while mainmenu.displaystate.openpath[i] ~= nil do local element = mainmenu.displaystate.openpath[i] if element.children ~= nil and #element.children >= 1 then local extension = get_or_create_extension_widget(i) local newy = oldy + itemheight(element.slot) extension.box.y = newy extension.box.height = itemheight(math.min(#element.children, settings.desktop.startmenuentries)) update_menu_level(element.children, extension.widget, mainmenu.displaystate.openpath[i+1]) end i = i + 1 end close_extensions_above(i) -- -1?) end --end of new lazy tree based system local function ensure_init() if mainmenu.init ~= nil then return end mainmenu.init = 1 mainmenu.listwidget = wibox.layout { layout = wibox.layout.manual, point = {x = 0, y = 0}, forced_width = beautiful.menu_width, forced_height = itemheight(settings.desktop.startmenuentries) } mainmenu.textbox = wibox.widget { markup = "", valign = 'center', -- font = "Source Sans Pro 8", widget = wibox.widget.textbox, point = {x = dpi(2), y = frombottom(2)}, forced_height = itemheight(1), forced_width = beautiful.menu_width - dpi(4) } mainmenu.mainmenuwidget = wibox.layout{ layout = wibox.layout.manual, mainmenu.textbox, mainmenu.listwidget } mainmenu.box = wibox({ ontop = true, x = 200, y = 0, height = mainmenuheight() , width = beautiful.menu_width, visible = false, widget = mainmenu.mainmenuwidget }) end --function called just before the main menu opens, to ensure everything is in correct state local function mainmenu_onopen() local s = awful.screen.focused() mainmenu.box.x = s.geometry.x --calculate vertical location local bottom_pos = itemheight() local top_pos = mainmenu.box.height + bottom_pos mainmenu.box.y = s.geometry.height - top_pos --Reset display update_tree_menu() --Reset omnibox mainmenu.input_state = input_handler_state() mainmenu.textbox.markup = "" awful.keygrabber.run(input_handler) end local function mainmenu_onclose() awful.keygrabber.stop(input_handler) close_extensions_above(1) end function mainmenu.toggle() ensure_init() if mainmenu.box.visible then mainmenu_onclose() else mainmenu_onopen() end mainmenu.box.visible = not mainmenu.box.visible end local function file_callback(programs) for _, program in pairs(programs) do --log("found " .. program.Name) local entry = entry_create_from_program(program) local categories = program.Categories local category = nil if categories ~= nil then --naughty.notify {text = "Category of " .. categories} for str in categories:gmatch("[^;]+") do category = str break end end if category ~= nil then local category_entry = get_category_entry(category) table.insert(category_entry.children, entry) else table.insert(mainmenu.menutree, entry) end end end for _, v in pairs(settings.desktop.paths) do log("checking " .. v) menubar.utils.parse_dir(v, file_callback) end return mainmenu
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. event3 = { description = "", minimumLevel = 0, maximumLevel = 0, lootItems = { --Fill to 25% {groupTemplate = "clothing_attachments", weight = 2000000}, --Fill to 25% {groupTemplate = "armor_attachments", weight = 2000000}, --Fill to 25% {groupTemplate = "event_token", weight = 3500000}, --Fill to 25% {groupTemplate = "tierthree", weight = 2500000}, } } addLootGroupTemplate("event3", event3)
T = require('luaunit') lsys = dofile('lsys.lua') function test_selector_empty_init() local s = lsys.Selector() T.assertEquals(s:choices(), {}) T.assertIsNil(s(), nil) end function test_selector_single_init() local s = lsys.Selector{ 'a' } T.assertEquals(s:choices(), {{1, 'a', weight = 1}}) T.assertEquals(s(), 'a') end function test_selector_multi_init_equal_weight() local s = lsys.Selector{ 'a', 'b', 'c' } T.assertEquals(s(0), 'a') T.assertEquals(s(0.3), 'a') T.assertEquals(s(0.34), 'b') T.assertEquals(s(0.8), 'c') end function test_call_outside_normalized_range() local s = lsys.Selector{ 'a', 'z' } T.assertEquals(s(-0.5), 'a') T.assertEquals(s(1.2), 'z') end function test_add_equal_weight() local s = lsys.Selector{ 'a', 'b' } T.assertEquals(s(0.9), 'b') s:add('foo') T.assertEquals(s(0.9), 'foo') T.assertEquals(s(0.5), 'b') end os.exit(T.LuaUnit.run())
print(1 == 2, 3.2 == 3.2, 3.2 == 2, {} == 1, {} == {}) --> =false true false false false print(1 < 2, 3.5 < -1, 2 < 1e10, 1e5 < 1e6, "xyz" < "xyza") --> =true false true true true print(1 <= 2, 3.5 <= -1, 2 <= 1e10, 1e5 <= 1e6, "xyz" <= "xyza") --> =true false true true true print(pcall(function() return {} <= {} end)) --> ~^false\t print(pcall(function() return {} < {} end)) --> ~^false\t local t = {} local meta = {__lt=function(x, y) return not not y end} setmetatable(t, meta) print(t < true) --> =true -- Since Lua 5.4 the __le metamethod is no longer inferred from __lt if __le is -- not implemented print(pcall(function() return t <= false end)) --> ~false\t.*attempt to compare a table value with a boolean value meta.__le = meta.__lt print(t <= false) --> =false
local orient = require('trackOrientation'); local pos = require('trackPosition'); local mas = require('moveAndScan'); local M = {}; function M.distance(coord1, coord2) local xDist = coord2.x - coord1.x; local yDist = coord2.y - coord1.y; local zDist = coord2.z - coord1.z; return math.sqrt(xDist^2 + yDist^2 + zDist^2); end function M.distFromSort(coord1) return function(coord2, coord3) local dist1 = M.distance(coord1, coord2); local dist2 = M.distance(coord1, coord3); return dist1 < dist2; end end function M.distanceSort(start, destinations) table.sort(destinations, M.distFromSort(start)); end function M.getAdjacentPoints(point) local negXPoint = {x=point.x-1, y=point.y, z=point.z}; local posXPoint = {x=point.x+1, y=point.y, z=point.z}; local posZPoint = {x=point.x, y=point.y, z=point.z+1}; local negZPoint = {x=point.x, y=point.y, z=point.z-1}; local negYPoint = {x=point.x, y=point.y-1, z=point.z}; local posYPoint = {x=point.x, y=point.y+1, z=point.z}; return {negXPoint, posXPoint, negZPoint, posZPoint, negYPoint, posYPoint}; end function M.facePoint(point) local start = pos.get(); if point.x ~= start.x then orient.faceX(point.x - start.x); elseif point.z ~= start.z then orient.faceZ(point.z - start.z); end return orient.get(); end function M.toAdjacent(point, scanType, times) local adjacentPoints = M.getAdjacentPoints(point); M.distanceSort(pos.get(), adjacentPoints); local success = false; for index, adjPoint in pairs(adjacentPoints) do if not success then success = mas.to(adjPoint.x, adjPoint.y, adjPoint.z, false, scanType, times); end end M.facePoint(point); orient.save(); return success; end return M;
--[[Copyright © 2014-2016, smd111 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of <addon name> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Byrth or smd111 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.]] _addon.name = 'latentchecker' _addon.author = 'smd111' _addon.command = 'latentchecker' _addon.commands = {'lc'} _addon.version = '1.1' extdata = require 'extdata' res = require 'resources' bag = 'Satchel' bag_id = 5 function validate_bag(id) local bag_info = windower.ffxi.get_bag_info(id) if bag_info.enabled and bag_info.max > bag_info.count then return true end return false end function check_space() if validate_bag(bag_id) then return bag_id else for i=5,8 do if validate_bag(i) then bag_id = i -- Update bag ID to be the bag that will work return bag_id end end end return false end function match_item(target_item,m) return type(m) == 'table' and m.id and res.items[m.id] and (res.items[m.id].en:lower() == target_item:lower() or res.items[m.id].enl:lower() == target_item:lower()) end windower.register_event('addon command', function(command, ...) local trial_weapons = {"axe of trials","gun of trials","sword of trials","knuckles of trials","spear of trials","scythe of trials","sapara of trials", "bow of trials","club of trials","pole of trials","pick of trials","dagger of trials","tachi of trials","kodachi of trials","sturdy axe","burning fists", "werebuster","mage's staff","vorpal sword","swordbreaker","brave blade","death sickle","double axe","dancing dagger","killer bow","windslicer", "sasuke katana","radiant lance","scepter staff","wightslayer","quicksilver","inferno claws","main gauche","elder staff","destroyers","senjuinrikio", "heart snatcher","subduer","dissector","expunger","morgenstern","gravedigger","rampager","coffinmaker","gonzo-shizunori","retributor","michishiba","thyrsusstab", "trial wand","trial blade"} if command == 'run' then windower.add_to_chat(121,'latentchecker: Starting...') windower.ffxi.set_equip(0, 0, 0) -- Remove main/sub weapons windower.ffxi.set_equip(0, 2, 0) -- Remove ranged weapons coroutine.sleep(1.2) for _,target_item in pairs(trial_weapons) do if not check_space() then windower.add_to_chat(123,'latentchecker: not able to swap item. No available space found in bags.') return end for n,m in pairs(windower.ffxi.get_items(0)) do -- Iterate over inventory if match_item(target_item,m) then windower.ffxi.put_item(bag_id,n) coroutine.sleep(1.2) windower.add_to_chat(55,'latentchecker: '..res.items[m.id].en..' has '..tostring(extdata.decode(windower.ffxi.get_items(0,n)).ws_points)..' WS points') coroutine.sleep(1.2) if not validate_bag(0) then windower.add_to_chat(123,'latentchecker: Inventory became full while running.\nlatentchecker: Stopping.') return end for j,k in pairs(windower.ffxi.get_items(bag_id)) do if match_item(target_item,k) then windower.ffxi.get_item(bag_id,j) break end end end end end windower.add_to_chat(121,'latentchecker: Done! Remember to re-dress yourself!') else print('latentchecker: My only valid command is "run", which will reset your TP.') end end)
--[[-- ui.link{ external = external, -- external URL static = static, -- URL relative to the static file directory module = module, -- module name view = view, -- view name action = action, -- action name attr = attr, -- for views: table of HTML attributes a_attr = a_attr, -- for actions: table of HTML attributes for the "a" tag form_attr = form_attr, -- for actions: table of HTML attributes for the "form" tag id = id, -- optional id to be passed to the view or action to select a particular data record params = params, -- optional parameters to be passed to the view or action routing = routing, -- optional routing information for action links, as described for ui.form{...} anchor = anchor, -- for views: anchor in destination URL text = text, -- link text content = content -- link content (overrides link text, except for submit buttons for action calls without JavaScript) } This function inserts a link into the active slot. It may be either an internal application link ('module' given and 'view' or 'action' given), or a link to an external web page ('external' given), or a link to a file in the static file directory of the application ('static' given). --]]-- function ui.link(args) local args = args or {} local content = args.content or args.text assert(content, "ui.link{...} needs a text.") local function wrapped_content() if args.image then ui.image(args.image) end if type(content) == "function" then content() else slot.put(encode.html(content)) end end if args.action then local form_attr = table.new(args.form_attr) local form_id if form_attr.id then form_id = form_attr.id else form_id = ui.create_unique_id() end local quoted_form_id = encode.json(form_id) form_attr.id = form_id local a_attr = table.new(args.attr) a_attr.href = "#" a_attr.onclick = "var f = document.getElementById(" .. quoted_form_id .. "); if (! f.onsubmit || f.onsubmit() != false) { f.submit() }; return false;" ui.form{ external = args.external, module = args.module or request.get_module(), action = args.action, id = args.id, params = args.params, routing = args.routing, attr = form_attr, content = function() ui.submit{ text = args.text, attr = args.submit_attr } end } ui.script{ type = "text/javascript", script = ( "document.getElementById(" .. quoted_form_id .. ").style.display = 'none'; document.write(" .. encode.json( slot.use_temporary( function() ui.tag{ tag = "a", attr = a_attr, content = wrapped_content } end ) ) .. ");" ) } else -- TODO: support content function local a_attr = table.new(args.attr) a_attr.href = encode.url{ external = args.external, static = args.static, module = args.module or request.get_module(), view = args.view, id = args.id, params = args.params, anchor = args.anchor } return ui.tag{ tag = "a", attr = a_attr, content = wrapped_content } end end
_G.require = require require "./lunarbook.lua"
---- -- Test cases for xlsxwriter.lua. -- -- Test the creation of a simple xlsxwriter.lua file. -- Check encoding of rich strings. -- -- Copyright 2014, John McNamara, jmcnamara@cpan.org -- local Workbook = require "xlsxwriter.workbook" local workbook = Workbook:new("test_escapes07.xlsx") local worksheet = workbook:add_worksheet() worksheet:write_url("A1", [[http://example.com/!"$%&'( )*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~]]) workbook:close()
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/props_c17/TrapPropeller_Engine.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetUseType(SIMPLE_USE) local phys = self:GetPhysicsObject() self:Setprice(200) phys:Wake() self.sparking = false self.damage = 100 end function ENT:OnTakeDamage(dmg) self.damage = self.damage - dmg:GetDamage() if self.damage <= 0 then self:Destruct() self:Remove() end end function ENT:Destruct() local vPoint = self:GetPos() local effectdata = EffectData() effectdata:SetStart(vPoint) effectdata:SetOrigin(vPoint) effectdata:SetScale(1) util.Effect("Explosion", effectdata) end function ENT:SalePrice(activator) local owner = self:Getowning_ent() if IsValid(owner) and activator == owner then if self.allowed and type(self.allowed) == "table" and table.HasValue(self.allowed, activator:Team()) then -- Hey, hey, hey! Get 20% off production costs of the award winning gun lab if you own the gun lab and are a gun dealer! return math.ceil(self:Getprice() * 0.80) -- 20% off else -- But we're not stopping there! If you are the owner of the Gun Lab 9000 but not a gun dealer, you still get a massive 10% off! return math.ceil(self:Getprice() * 0.90) -- 10% off end else -- If you don't own the gun lab, tough shit. No discount for you. Thank you, come again. return self:Getprice() -- 0% off end end ENT.Once = false function ENT:Use(activator) local owner = self:Getowning_ent() local cash = self:SalePrice(activator) if self.Once then return end if not activator:canAfford(self:SalePrice(activator)) then DarkRP.notify(activator, 1, 3, DarkRP.getPhrase("cant_afford", DarkRP.getPhrase("gun"))) return "" end local diff = self:SalePrice(activator) - self:SalePrice(owner) if diff < 0 and not owner:canAfford(math.abs(diff)) then DarkRP.notify(activator, 2, 3, DarkRP.getPhrase("owner_poor", DarkRP.getPhrase("gun_lab"))) return "" end self.sparking = true activator:addMoney(-cash) DarkRP.notify(activator, 0, 3, "You purchased a P228 for " .. DarkRP.formatMoney(cash) .. "!") if IsValid(owner) and activator ~= owner then local gain = 0 if self.allowed and type(self.allowed) == "table" and table.HasValue(self.allowed, owner:Team()) then gain = math.floor(self:Getprice() - math.ceil(self:Getprice() * 0.80)) else gain = math.floor(self:Getprice() - math.ceil(self:Getprice() * 0.90)) end if gain == 0 then DarkRP.notify(owner, 3, 3, DarkRP.getPhrase("you_received_x", DarkRP.formatMoney(0) .. " " .. DarkRP.getPhrase("profit"), "P228 (" .. DarkRP.getPhrase("gun_lab") .. ")")) else owner:addMoney(gain) local word = DarkRP.getPhrase("profit") if gain < 0 then word = DarkRP.getPhrase("loss") end DarkRP.notify(owner, 0, 3, DarkRP.getPhrase("you_received_x", DarkRP.formatMoney(math.abs(gain)) .. " " .. word, "P228 (" .. DarkRP.getPhrase("gun_lab") .. ")")) end end self.Once = true timer.Create(self:EntIndex() .. "spawned_weapon", 1, 1, function() if not IsValid(self) then return end self:createGun() end) end function ENT:createGun() self.Once = false local gun = ents.Create("spawned_weapon") gun:SetModel("models/weapons/w_pist_p228.mdl") gun:SetWeaponClass("weapon_p2282") local gunPos = self:GetPos() gun:SetPos(Vector(gunPos.x, gunPos.y, gunPos.z + 27)) gun.ShareGravgun = true gun.nodupe = true gun:Spawn() self.sparking = false end function ENT:Think() if self.sparking then local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetMagnitude(1) effectdata:SetScale(1) effectdata:SetRadius(2) util.Effect("Sparks", effectdata) end end function ENT:OnRemove() if not IsValid(self) then return end timer.Destroy(self:EntIndex() .. "spawned_weapon") end
--[=[ Provides a basis for binders that can be retrieved anywhere @class BinderProvider ]=] local require = require(script.Parent.loader).load(script) local Promise = require("Promise") local BinderProvider = {} BinderProvider.ClassName = "BinderProvider" BinderProvider.__index = BinderProvider --[=[ Constructs a new BinderProvider. ```lua local serviceBag = ServiceBag.new() -- Usually in a separate file! local binderProvider = BinderProvider.new(function(self, serviceBag) serviceBag:Add(Binder.new("Bird", require("Bird"))) end) -- Retrieve binders local binders = serviceBag:GetService(binderProvider) -- Runs the game (including binders) serviceBag:Init() serviceBag:Start() ``` @param initMethod (self, serviceBag: ServiceBag) @return BinderProvider ]=] function BinderProvider.new(initMethod) local self = setmetatable({}, BinderProvider) -- Pretty sure this is a bad idea self._bindersAddedPromise = Promise.new() self._startPromise = Promise.new() self._initMethod = initMethod or error("No initMethod") self._initialized = false self._started = false self._binders = {} return self end --[=[ Retrieves whether or not its a binder provider @param value any @return boolean -- True if it is a binder provider ]=] function BinderProvider.isBinderProvider(value) return type(value) == "table" and value.ClassName == "BinderProvider" end --[=[ Resolves to the given binder given the binderName. @param binderName string @return Promise<Binder<T>> ]=] function BinderProvider:PromiseBinder(binderName) if self._bindersAddedPromise:IsFulfilled() then local binder = self:Get(binderName) if binder then return Promise.resolved(binder) else return Promise.rejected() end end return self._bindersAddedPromise :Then(function() local binder = self:Get(binderName) if binder then return binder else return Promise.rejected() end end) end --[=[ Initializes itself and all binders @param ... ServiceBag | any ]=] function BinderProvider:Init(...) assert(not self._initialized, "Already initialized") self._initialized = true self._initMethod(self, ...) self._bindersAddedPromise:Resolve() end --[=[ Returns a promise that will resolve once all binders are added. @return Promise ]=] function BinderProvider:PromiseBindersAdded() return self._bindersAddedPromise end --[=[ Returns a promise that will resolve once all binders are started. @return Promise ]=] function BinderProvider:PromiseBindersStarted() return self._startPromise end --[=[ Starts all of the binders. ]=] function BinderProvider:Start() assert(self._initialized, "Not initialized") assert(not self._started, "Already started") self._started = true for _, binder in pairs(self._binders) do binder:Start() end self._startPromise:Resolve() end function BinderProvider:__index(index) if BinderProvider[index] then return BinderProvider[index] end assert(self._initialized, "Not initialized") error(("%q Not a valid index"):format(tostring(index))) end --[=[ Retrieves a binder given a tagName @param tagName string @return Binder<T>? ]=] function BinderProvider:Get(tagName) assert(type(tagName) == "string", "tagName must be a string") return rawget(self, tagName) end --[=[ Adds a binder given a tag name. @param binder Binder<T> ]=] function BinderProvider:Add(binder) assert(not self._started, "Already inited") assert(not self:Get(binder:GetTag()), "Binder already exists") table.insert(self._binders, binder) self[binder:GetTag()] = binder end return BinderProvider
-- This file is auto-generated by shipwright.nvim local common_fg = "#7BA9C5" local inactive_bg = "#18252D" local inactive_fg = "#D1E0DA" return { normal = { a = { bg = "#3B5362", fg = common_fg, gui = "bold" }, b = { bg = "#2B3E49", fg = common_fg }, c = { bg = "#1C2A32", fg = "#C6D5CF" }, }, insert = { a = { bg = "#343F6D", fg = common_fg, gui = "bold" }, }, command = { a = { bg = "#62415B", fg = common_fg, gui = "bold" }, }, visual = { a = { bg = "#3A3E3D", fg = common_fg, gui = "bold" }, }, replace = { a = { bg = "#3B2023", fg = common_fg, gui = "bold" }, }, inactive = { a = { bg = inactive_bg, fg = inactive_fg, gui = "bold" }, b = { bg = inactive_bg, fg = inactive_fg }, c = { bg = inactive_bg, fg = inactive_fg }, }, }
local json = require "json" local webclient_lib = require 'webclient' local webclient = webclient_lib.create() local requests = {}; local requests = {} local req, key = webclient:request("http://httpbin.org/relative-redirect/6") --302 requests[key] = req local req, key = webclient:request("http://httpbin.org/absolute-redirect/6") --302 requests[key] = req local req, key = webclient:request("http://httpbin.org/redirect-to?status_code=307&url=" .. webclient:url_encoding("http://httpbin.org/get")) --307 requests[key] = req while next(requests) do local finish_key, result = webclient:query() if finish_key then local req = requests[finish_key] assert(req) requests[finish_key] = nil assert(result == 0) local content, errmsg = webclient:get_respond(req) local data = json.decode(content) assert(data.url == "http://httpbin.org/get") local info = webclient:get_info(req) assert(info.response_code == 200) webclient:remove_request(req) end end
local es_utils = require "resty.es.utils" local make_path = es_utils.make_path local deal_params = es_utils.deal_params local _M = { _VERSION = '0.01' } local mt = { __index = _M } function _M.new(self, client) return setmetatable({client = client}, mt) end function _M.info(self, s_params) local basic_params, query_params = deal_params(s_params, 'node_id', 'metric') local data, err = self.client:_perform_request( 'GET', make_path('_nodes', basic_params.node_id, basic_params.metric), query_params ) return data, err end return _M
--[[ NOTICE Copyright (c) 2019 Andrew Bereza Provided for public use in educational, recreational or commercial purposes under the Apache 2 License. Please include this copyright & permission notice in all copies or substantial portions of Miner's Haven source code ]] local module = {} local Done = false local BaseSize = UDim2.new(0,300,0,100) local function resize() end function Tween(Object, Properties, Value, Time) Time = Time or 0.5 local propertyGoals = {} local Table = (type(Value) == "table" and true) or false for i,Property in pairs(Properties) do propertyGoals[Property] = Table and Value[i] or Value end local tweenInfo = TweenInfo.new( Time, Enum.EasingStyle.Linear, Enum.EasingDirection.Out ) local tween = game:GetService("TweenService"):Create(Object,tweenInfo,propertyGoals) tween:Play() end function module.init() math.randomseed(os.time()) game.StarterGui:SetCoreGuiEnabled("Backpack",false) wait() script.Parent.Contents.Bottom.Position = UDim2.new(0,0,1,0) script.Parent.Contents.Top.Position = UDim2.new(0,0,-0.6,0) script.Parent.Contents.Bottom.Leaderboards.Position = UDim2.new(0.5,0,1.5,0) script.Parent.Contents.Bottom.Leaderboards.Visible = false if workspace:FindFirstChild("Private") then script.Parent.Contents.Top.TextLabel.Text = game.Players.LocalPlayer.Name.."'s Private Island" script.Parent.Contents.Bottom.Solo.Visible = false script.Parent.Contents.Bottom.Enter.Visible = true script.Parent.Contents.Bottom.Enter.Position = UDim2.new(0.5,-50,0.22,0) end game.ReplicatedStorage:WaitForChild("IsWhitelisted") local Allowed = game.ReplicatedStorage.IsWhitelisted:InvokeServer() if not Allowed then script.Parent.Contents.NotAllowed.Visible = true return false end local YaDoneNow = false wait(1) if script.Parent.Contents:FindFirstChild("Ambiance") then require(script.Parent.Contents.Ambiance).init() end local Tips = { "A mysterious merchant appears on the weekend to sell secret items. You just have to find them.", "When you reach $25Qn, you can advance to the next life with a powerful new Reborn item.", "Cell Furnaces don't take upgraded ore. Some mines are so powerful that their ore starts out upgraded.", "Research Points are shared across save files and are not lost when rebirthing.", "Coal is used to power special industrial mines and upgraders that won't work without it.", "Many upgraders have limits to how they can be used. They will flash if not used correctly.", "Having trouble with other players? Try Play Solo, where you can play on your own private island.", "You can sync your Miner's Haven account with our community server to unlock special ranks and chatrooms.", "Decorative items don't give any money when sold. However, they stay in your inventory when you Rebirth.", "Play together with your friends! Add people to your base & edit permissions under the Settings tab.", "The best way to rebirth quickly is to have a layout or two and constantly improve them as you gain new items.", "Having trouble rebirthing? Try searching for Research Crates on the map and use the items you find in them!" } local USI = game:GetService("UserInputService") if USI.MouseEnabled and USI.KeyboardEnabled then table.insert(Tips,"Right-click items in your inventory to favorite them. Favorite items always appear on top.") table.insert(Tips,"Quickly toggle various parts of the menu with hotkeys. [E] opens inventory and [F] opens the shop.") table.insert(Tips,"Click and hold to quickly select multiple items on your base at once.") table.insert(Tips,"You can drag-click your mouse to quickly place an item multiple times.") end local Tip = Tips[math.random(1,#Tips)] script.Parent.Contents.Bottom.Tip.Text = "Tip: "..Tip script.Parent.Contents.Tip.Content.Text = Tip local DoneLoading = true --script.Parent.Contents.Music:Play() --[[ Tween(game.Lighting,{ "FogColor", "FogEnd", "Ambient", "Brightness", "OutdoorAmbient" }, { Color3.new(0.0,0,0.05), 500, Color3.new(0.0,0,0.03), 0.1, Color3.new(0.03,0.07,0.09) },4) wait(1) ]] local h = 0 local progress = 0 --[[ -- LOAD ASSETS local Ids = {} local Loading local function scan(Object) for i,Ins in pairs(Object:GetDescendants()) do if Ins:IsA("ImageLabel") or Ins:IsA("ImageButton") or Ins:IsA("Decal") then table.insert(Ids,Ins) end end end scan(game.StarterGui) game.ReplicatedStorage:WaitForChild("Items") for i,Item in pairs(game.ReplicatedStorage.Items:GetChildren()) do if Item.ItemType.Value == 11 then table.insert(Ids,"http://www.roblox.com/asset/?id="..Item.ThumbnailId.Value) end end table.insert(Ids,script.Parent.Contents.Music) scan(script.Parent.Contents) local Queue = #Ids spawn(function() game:GetService("ContentProvider"):PreloadAsync(Ids) DoneLoading = true end) local Time = os.time() wait(0.1) local Queue = game.ContentProvider.RequestQueueSize while not DoneLoading do game:GetService("RunService").Heartbeat:wait() local Cur = game.ContentProvider.RequestQueueSize if Cur > Queue then Queue = Cur end progress = (Queue - Cur) / Queue script.Parent.Contents.Bar.Progress.Size = UDim2.new(progress/1,0,1,0) if (os.time() - Time) >= 30 then DoneLoading = true end end script.Parent.Contents.Bar.Progress.Size = UDim2.new(1,0,1,0) -- Tween(script.Parent.Contents.Bar.Progress, {"BackgroundColor3"}, Color3.fromRGB(255, 214, 90) ) -- Tween(script.Parent.Contents.Background, {"ImageColor3"}, Color3.fromRGB(255, 214, 90) ) ]] --Tween(script.Parent.Contents.Bar.Progress, {"BackgroundColor3"}, Color3.fromRGB(216, 186, 36) ) --Tween(script.Parent.Contents.Background, {"ImageColor3","BackgroundTransparency"}, {Color3.fromRGB(0, 0, 255),0.5}, 2) --Tween(script.Parent.Contents.Loading, {"TextTransparency"}, 1, 2) wait(1) resize() script.Parent.Contents.Top.Visible = true --[[ if game.Players.LocalPlayer:FindFirstChild("Executive") then script.Parent.Contents.Top.Logo.Executive.Visible = true elseif game.Players.LocalPlayer:FindFirstChild("Premium") then script.Parent.Contents.Top.Logo.Premium.Visible = true elseif game.Players.LocalPlayer:FindFirstChild("VIP") then script.Parent.Contents.Top.Logo.VIP.Visible = true end ]] workspace.CurrentCamera:GetPropertyChangedSignal("ViewportSize"):connect(resize) script.Parent.Contents.Top:TweenPosition(UDim2.new(0,0,-0.1,0),Enum.EasingDirection.Out,Enum.EasingStyle.Bounce,2) script.Parent.Contents.Bottom:TweenPosition(UDim2.new(0,0,0.5,0),Enum.EasingDirection.Out,Enum.EasingStyle.Bounce,2) spawn(function() wait(2) Tween(script.Parent.Contents.Bottom.Tip,{"TextTransparency"},0.3,1) end) -- leaderboard stuff spawn(function() for i,Leaderboard in pairs(script.Parent.Contents.Bottom.Leaderboards:GetChildren()) do if Leaderboard:IsA("GuiObject") then local Real = workspace:WaitForChild("Map"):WaitForChild(Leaderboard.Name) if Real then local ui = Real:WaitForChild("Board").Leaderboard.Frame Leaderboard.Visible = true Leaderboard.Winner.BackgroundColor3 = ui.Winner.BackgroundColor3 Leaderboard.Winner.Thumbnail.Image = ui.Winner.Thumbnail.Image Leaderboard.Winner.Thumbnail.ImageColor3 = ui.Winner.Thumbnail.ImageColor3 Leaderboard.Winner.Amount.Text = ui.Winner.Amount.Text Leaderboard.Winner.Amount.TextColor3 = ui.Winner.Amount.TextColor3 Leaderboard.Winner.Pos.TextColor3 = ui.Winner.Title.TextColor3 Leaderboard.Winner.WinnerName.Text = ui.Winner.WinnerName.Text Leaderboard.Winner.WinnerName.TextColor3 = ui.Winner.WinnerName.TextColor3 Leaderboard.Title.Text = ui.Title.Text else Leaderboard.Visible = false end end end wait(1.5) script.Parent.Contents.Bottom.Leaderboards.Visible = true Tween(script.Parent.Contents.Bottom.Leaderboards,{"Position"},UDim2.new(0.5,0,1,0),1) end) if game.Lighting:FindFirstChild("Blur") then Tween(game.Lighting:WaitForChild("Blur"),{"Size"},10,0.4) end Tween(script.Parent.Contents.Tip,{"Position"},UDim2.new(0.5,0,1.5,0),1) wait(2) script.Parent.Contents.Tip.Visible = false local Allowed = game.ReplicatedStorage.IsWhitelisted:InvokeServer() if Allowed then --Code for checking friends' private islands --[[ local Players = game:GetService("Players") local friends = Players.LocalPlayer:GetFriendsOnline() for i,friendData in next,friends do if friendData.LocationType == 4 then if PlaceId == game.PlaceId and end end ]]-- script.Parent.Contents.Bottom.Enter.Visible = true script.Parent.Contents.Bottom.Solo.Visible = true script.Parent.Contents.Bottom.Saves.Visible = false if workspace:FindFirstChild("Private") then script.Parent.Contents.Bottom.Solo.Visible = false script.Parent.Contents.Bottom.Enter.Visible = true script.Parent.Contents.Bottom.Enter.Position = UDim2.new(0.5,-50,0.22,0) end if USI.GamepadEnabled then script.Parent.Contents.XboxControls.Visible = true game.GuiService.GuiNavigationEnabled = true game.GuiService.SelectedObject = script.Parent.Contents.Bottom.Enter end spawn(function() wait() if USI.GamepadEnabled then script.Parent.Contents.XboxControls.Visible = true game.GuiService.GuiNavigationEnabled = true game.GuiService.SelectedObject = script.Parent.Contents.Bottom.Enter end end) local Requested = false game.ReplicatedStorage:WaitForChild("MoneyLib") local MoneyLib = require(game.ReplicatedStorage.MoneyLib) --[[ local function RequestLoad() if not Requested then Requested = true if game.ReplicatedStorage.Waitlist:FindFirstChild(game.Players.LocalPlayer.Name) then script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.5,0.5) script.Parent.Contents.Bottom.Status.Text = "You're attempting to rejoin this server too quickly!" script.Parent.Contents.Bottom.Status.Visible = true wait(1) script.Parent.Contents.Bottom.Status.Visible = false Requested = false return false end script.Parent.Contents.Bottom.Status.Text = "Loading data..." script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,1,1) script.Parent.Contents.Bottom.Status.Visible = true local Result, Success, Errormsg, DataCount = game.ReplicatedStorage.LoadPlayerData:InvokeServer() if DataCount then print("Your data is "..DataCount.." characters long.") end if not Result then -- Ruh-oh, something went wrong! if Success then script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.75,0.5) for i=1,60 do script.Parent.Contents.Bottom.Status.Text = "Failed to connect to ROBLOX! Retrying in: ("..(61-i)..")" wait(1) end Requested = false RequestLoad() else script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.5,0.5) script.Parent.Contents.Bottom.Status.Text = "Something went wrong! Check error log." warn("ERROR LOADING PLAYER DATA") warn(Errormsg) print("Please send a screenshot of this to berezaa") end else script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(0.5,1,0.6) script.Parent.Contents.Bottom.Status.Text = "Success! Welcome to Miner's Haven!" end end end ]] -- script.Parent.Contents.Bottom.Enter.MouseButton1Click:connect(RequestLoad) local function LoadSlotButton(Button) local Slot = tonumber(Button.Name) if Slot and not Requested then Requested = true script.Parent.Contents.Click:Play() if not Button.Loaded.Value then Button.Load.Visible = false Button.Status.Visible = true Button.Status.Text = "Loading..." Button.Status.TextColor3 = Color3.new(1,1,1) local Success, Data = game.ReplicatedStorage.QuickLoad:InvokeServer(Slot) if Success then Button.Status.Visible = false Button.Load.Text = "[PLAY]" Button.Load.BackgroundColor3 = Color3.new(0.5,1,0.5) Button.Load.Visible = true if USI.GamepadEnabled and game.GuiService.SelectedObject == nil then game.GuiService.SelectedObject = Button.Load end Button.Cash.Visible = true Button.Loaded.Value = true if Data and Data["Money"] then Button.Cash.Text = MoneyLib.HandleMoney(tonumber(Data.Money)) if Data["Rebirths"] then Button.Life.Visible = true local Prefix = "" if Data["SecondSacrifice"] then Prefix = "S+" elseif Data["Sacrifice"] then Prefix = "s-" end Button.Life.Text = Prefix..MoneyLib.HandleLife(Data["Rebirths"] + 1).." Life" else Button.Life.Visible = false end else Button.Cash.Text = "New Game" end else Button.Status.Text = "Error Loading!" Button.Status.TextColor3 = Color3.new(1,0.5,0.5) wait(3) Button.Status.Visible = false Button.Load.Visible = true end Requested = false else --Tween(workspace.CurrentCamera,{"FieldOfView"},20,0.3) Button.Load.Visible = false Button.Status.TextColor3 = Color3.new(0.5,1,0.5) Button.Status.Text = "Loading..." Button.Status.Visible = true local Success = game.ReplicatedStorage.LoadPlayerData:InvokeServer(Slot) if not Success then Button.Status.Text = "Error Occurred!" wait(1) Button.Load.Visible = true Button.Status.Visible = false Requested = false end Button.Status.Text = "Success!" end end end local DB = true script.Parent.Contents.Bottom.Solo.MouseButton1Click:connect(function() if DB then DB = false script.Parent.Contents.Click:Play() local Success = game.ReplicatedStorage.PlaySolo:InvokeServer() if Success then script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(0.3,0.6,1) script.Parent.Contents.Bottom.Status.Text = "Teleporting to your private island..." script.Parent.Contents.Bottom.Status.Visible = true else script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.5,0.5) script.Parent.Contents.Bottom.Status.Text = "Something went wrong on the server." script.Parent.Contents.Bottom.Status.Visible = true wait(1) script.Parent.Contents.Bottom.Status.Visible = false end DB = true end end) script.Parent.Contents.Bottom.Enter.MouseButton1Click:connect(function() if DB then DB = false script.Parent.Contents.Click:Play() if game.ReplicatedStorage.Waitlist:FindFirstChild(game.Players.LocalPlayer.Name) then script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.5,0.5) script.Parent.Contents.Bottom.Status.Text = "You're attempting to rejoin this server too quickly!" script.Parent.Contents.Bottom.Status.Visible = true wait(1) script.Parent.Contents.Bottom.Status.Visible = false DB = true return false else spawn(function() Tween(game.Lighting:WaitForChild("Blur"),{"Size"},30,0.4) Tween(game.Lighting:WaitForChild("Bloom"),{"Intensity","Threshold"},{1,0.5},0.4) Tween(game.Lighting:WaitForChild("ColorCorrection"),{"Brightness"},0.2,0.4) game.Lighting.Blur.Enabled = true game.Lighting.ColorCorrection.Enabled = true wait(0.3) local Tycoon = game.Players.LocalPlayer.PlayerTycoon.Value if not Tycoon then --workspace.CurrentCamera.CFrame = script.Parent.Contents.CamPos.Value YaDoneNow = true end Tween(game.Lighting:WaitForChild("ColorCorrection"),{"Brightness"},-0.04,0.4) Tween(game.Lighting.Blur,{"Size"},5,0.4) Tween(game.Lighting.Bloom,{"Intensity","Threshold"},{0.15,0.95},0.4) local camera = workspace.CurrentCamera local angle = math.rad(70) local velo = 0.05 workspace.CurrentCamera.FieldOfView = 40 while not YaDoneNow do local cf = CFrame.new(Tycoon.Base.Position) --Start at the position of the part * CFrame.Angles(0, angle, 0) --Rotate by the angle * CFrame.new(0, 0, 230) --Move the camera backwards 5 units angle = angle + math.rad(velo) workspace.CurrentCamera.CFrame = CFrame.new(cf.p + Vector3.new(0,35,0),Tycoon.Base.Position+ Vector3.new(0,10,0)) game:GetService("RunService").RenderStepped:wait() end wait(0.3) end) script.Parent.Contents.Bottom.Enter.Visible = false script.Parent.Contents.Bottom.Solo.Visible = false Tween(script.Parent.Contents.Bottom.Leaderboards,{"Position"},UDim2.new(0.5,0,1.5,0)) Tween(script.Parent.Contents.Bottom.Tip,{"TextTransparency"},1,1) local Abs = script.Parent.Contents.Bottom.Saves.AbsoluteSize script.Parent.Contents.Bottom.Saves.Position = UDim2.new(0.5,0,1,10) script.Parent.Contents.Bottom.Saves:TweenPosition(UDim2.new(0.5,0,0.03,35),nil,nil,0.5) script.Parent.Contents.Bottom.Saves.Visible = true --LoadSlotButton(script.Parent.Contents.Bottom.Saves.Slots["1"]) if USI.GamepadEnabled then game.GuiService.GuiNavigationEnabled = true game.GuiService.SelectedObject = script.Parent.Contents.Bottom.Saves.Slots["1"].Load end end DB = true end end) for i,Button in pairs(script.Parent.Contents.Bottom.Saves.Slots:GetChildren()) do if Button:FindFirstChild("Loaded") then Button.Load.MouseButton1Click:connect(function() LoadSlotButton(Button) end) end end else script.Parent.Contents.Bottom.Status.TextColor3 = Color3.new(1,0.5,0.5) script.Parent.Contents.Bottom.Status.Visible = true script.Parent.Contents.Bottom.Enter.Visible = false script.Parent.Contents.Bottom.Solo.Visible = false if game.ReplicatedStorage:FindFirstChild("BerOnly") then script.Parent.Contents.Bottom.Status.Text = "You can only test with berezaa in your server." else script.Parent.Contents.Bottom.Status.Text = "You do not have permission to enter." end end local function CloseGui() --Tween(script.Parent.Contents.Background,{"ImageTransparency","BackgroundTransparency"},1) script.Parent.Contents.Cover.BackgroundTransparency = 1 script.Parent.Contents.Cover.Visible = true Tween(script.Parent.Contents.Cover,{"BackgroundTransparency"},0,0.2) local GUI = game.ReplicatedStorage:WaitForChild("GUI") --GUI.Parent = game.StarterGui GUI:Clone().Parent = game.Players.LocalPlayer.PlayerGui local Cover = GUI:WaitForChild("Cover") if Cover then Cover.Visible = true end wait() script.Parent:Destroy() end game.ReplicatedStorage.DataLoadedIn.OnClientEvent:connect(CloseGui) end return module
hook.Add("PlayerSpawn","Modulo:SpawnRPTeamAtPoint",function(ply) local PlayerTeam = RPExtraTeams[ply:Team()] if PlayerTeam != nil and PlayerTeam.SpawnPoint != nil then if ply.ModuloSetSpawn then return end if istable(PlayerTeam.SpawnPoint) then local val = math.random(1, #PlayerTeam.SpawnPoint) print(val) timer.Simple(0,function() ply:SetPos(PlayerTeam.SpawnPoint[val]) end) else timer.Simple(0,function() ply:SetPos(PlayerTeam.SpawnPoint) end) end end if ply.AlreadyUsedArmory != nil then ply.AlreadyUsedArmory = false end end)
local M = {} M.lerp_factor = 5 M.players = {} M.players_in_cars = {} M.player_heads_attachments = {} M.player_transforms = {} local blacklist = { woodplanks = true, woodcrate = true, weightpad = true, wall = true, tsfb = true, tube = true, trafficbarrel = true, tirewall = true, tirestacks = true, testroller = true, tanker = true, suspensionbridge = true, streetlight = true, shipping_container = true, sawhorse = true, rollover = true, rocks = true, roadsigns = true, piano = true, metal_ramp = true, metal_box = true, large_tilt = true, large_spinner = true, large_roller = true, large_hamster_wheel = true, large_crusher = true, large_cannon = true, large_bridge = true, large_angletester = true, kickplate = true, inflated_mat = true, haybale = true, gate = true, flipramp = true, flatbed = true, flail = true, cones = true, christmas_tree = true, cannon = true, blockwall = true, barrier = true, barrels = true, ball = true, unicycle = true } local function get_player_color(id) math.randomseed(id) local r, g, b, a = 0.2 + math.random() * 0.8, 0.2 + math.random() * 0.8, 0.2 + math.random() * 0.8, 1 math.randomseed(os.time()) return r, g, b, a end local function spawn_player(data) local player = createObject('TSStatic') player:setField("shapeName", 0, "/art/shapes/kissmp_playermodels/base_nb.dae") player:setField("dynamic", 0, "true") player.scale = Point3F(1, 1, 1) player:registerObject("player"..data.owner) player:setPosRot( data.position[1], data.position[2], data.position[3], data.rotation[1], data.rotation[2], data.rotation[3], data.rotation[4] ) local r, g, b, a = get_player_color(data.owner) player:setField('instanceColor', 0, string.format("%g %g %g %g", r, g, b, a)) vehiclemanager.id_map[data.server_id] = player:getID() vehiclemanager.server_ids[player:getID()] = data.server_id M.players[data.server_id] = player M.player_transforms[data.server_id] = { position = vec3(data.position), target_position = vec3(data.position), rotation = data.rotation, velocity = vec3(), time_past = 0 } end local function update_players(dt) for id, data in pairs(M.player_transforms) do local player = M.players[id] if player and data then data.time_past = data.time_past + dt local old_position = data.position data.position = lerp(data.position, data.target_position + data.velocity * data.time_past, clamp(dt * M.lerp_factor, 0, 1)) local local_velocity = data.position - old_position local p = data.position + local_velocity * dt --player.position = m player:setPosRot( p.x, p.y, p.z, data.rotation[1], data.rotation[2], data.rotation[3], data.rotation[4] ) end end for id, player_data in pairs(network.players) do local vehicle = be:getObjectByID(vehiclemanager.id_map[player_data.current_vehicle or -1] or -1) if vehicle and (not blacklist[vehicle:getJBeamFilename()]) then local cam_node, _ = core_camera.getDriverData(vehicle) if cam_node and kisstransform.local_transforms[vehicle:getID()] then local p = vec3(vehicle:getNodePosition(cam_node)) + vec3(vehicle:getPosition()) local r = kisstransform.local_transforms[vehicle:getID()].rotation local hide = be:getPlayerVehicle(0) and (be:getPlayerVehicle(0):getID() == vehicle:getID()) and (vec3(getCameraPosition()):distance(p) < 2.5) hide = hide or (not kissui.show_drivers[0]) or kisstransform.inactive[vehicle:getID()] if (not M.players_in_cars[id]) and (not hide) then local player = createObject('TSStatic') player:setField("shapeName", 0, "/art/shapes/kissmp_playermodels/base_nb_head.dae") player:setField("dynamic", 0, "true") player.scale = Point3F(1, 1, 1) local r, g, b, a = get_player_color(id) player:setField('instanceColor', 0, string.format("%g %g %g %g", r, g, b, a)) player:registerObject("player_head"..id) M.players_in_cars[id] = player M.player_heads_attachments[id] = vehicle:getID() end if hide and M.players_in_cars[id] then M.players_in_cars[id]:delete() M.players_in_cars[id] = nil M.player_heads_attachments[id] = nil end p = p + vec3(vehicle:getVelocity()) * dt local player = M.players_in_cars[id] if player then player:setPosRot( p.x, p.y, p.z, r[1], r[2], r[3], r[4] ) end end else if M.players_in_cars[id] then M.players_in_cars[id]:delete() M.players_in_cars[id] = nil M.player_heads_attachments[id] = nil end end end for id, v in pairs(M.players_in_cars) do if not be:getObjectByID(M.player_heads_attachments[id] or -1) then v:delete() M.players_in_cars[id] = nil M.player_heads_attachments[id] = nil end end end M.spawn_player = spawn_player M.get_player_color = get_player_color M.onUpdate = update_players return M
----------------------------------- -- Area: Garlaige Citadel (200) -- NM: Old Two-Wings ----------------------------------- function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) -- Set Old_Two_Wings's spawnpoint and respawn time (21-24 hours) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random(75600,86400)); end;
object_tangible_loot_creature_loot_collections_space_capacitor_mark_04_novaldex = object_tangible_loot_creature_loot_collections_space_shared_capacitor_mark_04_novaldex:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_space_capacitor_mark_04_novaldex, "object/tangible/loot/creature/loot/collections/space/capacitor_mark_04_novaldex.iff")
--[[ Description: Author: Date: --]] local Root, Utilities, Service, Package; return { Init = function(cRoot, cPackage) Root = cRoot Utilities = Root.Utilities Package = cPackage Service = Root.Utilities.Services --// Do init end; AfterInit = function(Root, Package) --// Do after-init end; }
--- --- --- File: unitss.lua --- This does the following things --- 1. Coordinates the units data bases --- 2. Verifies a units in a chain --- 3. Verifies the unitss in a file list --- 4. Generates the complete list of unitss in a chain --- 5. Gets a units record --- --- --- The entry for a units contains the following fieds --- unitsDir --- units directory --- telephone --- telephoneExt --- ipAddress --- --- --- --- tgs.units.chains = {} function tgs.units.verifyChain( chain ) local returnValue if tgs.units.chains[chain] ~= nil then returnValue = true else returnValue = false end return returnValue end function tgs.units.verifyUnit( chain, unitsId ) local returnValue local temp returnValue = false temp = tgs.units.chains[ chain ] if temp ~= nil then if temp.unitsList[unitsId] ~= nil then returnValue = true end end return returnValue end function tgs.units.getChain( chain) local temp local returnValue local i,j returnValue = {} temp = tgs.units.chains[ chain ] if temp == nil then return returnValue end for i,j in pairs( temp.unitsList ) do table.insert( returnValue, j[ temp.key] ) end table.sort( returnValue ) return returnValue end function tgs.units.getUnit( chain , unitsId ) local temp local returnValue returnValue = nil temp = tgs.units[ chain ] if temp ~= nil then returnValue = temp.unitsList[ units ] end return returnValue end function tgs.units.verifyTable( j, entry ) local returnValue returnValue = false for i,j in ipairs( j) do if j == entry then returnValue = true end end return returnValue end function tgs.units.verifyField( i, j, entry ) local returnValue returnValue = true if type(j) == "table" then returnValue = tgs.units.verifyTable( j, entry) else if type(j) == "function" then returnValue = j(entry ) end end return returnValue end function tgs.units.verifyEntry( unitsControl, entry,key ) local returnValue local temp returnValue = true temp = unitsControl.requiredFields for i,j in pairs( temp ) do if entry[i] == nil then print("bad field",j,entry[key]) returnValue = false else if tgs.units.verifyField( i, j,entry[i] ) == false then returnValue = false end end end return returnValue end function tgs.units.addChain( unitsControl ,unitsList ) local temp,errorStr unitsControl.unitsList = {} -- verify tgs.units table assert( unitsControl.requiredFields[ unitsControl.key] ~= nil,"key is not defined") for i,j in ipairs( unitsList ) do errorStr = sprintf("chain %s units %s ",unitsControl.name, j[ unitsControl.key]) assert( tgs.units.verifyEntry( unitsControl, j, unitsControl.key ),errorStr) unitsControl.unitsList[ j[unitsControl.key] ] = j end tgs.units.chains[ unitsControl.name ] = unitsControl end function tgs.units.getEntry( chain,unitId ) local temp, entry assert( tgs.units.chains[chain] ~= nil,"chain not registered") temp = tgs.units.chains[ chain] entry = temp.unitsList[ unitId ] return entry end --- --- --- dump a unit entry --- --- --- function tgs.units.dumpEntry( chain, unitId ) local temp, entry assert( tgs.units.chains[chain] ~= nil,"chain not registered") temp = tgs.units.chains[ chain] entry = temp.unitsList[ unitId ] if entry == nil then print("unitId was not found") return end for i, j in pairs( entry ) do print("field",i,"value",j) end end --- --- --- dumps the units 10 units a line --- --- function tgs.units.dumpUnits( chain ) local temp, key, tempIndex, tempList local unitsControl assert( tgs.units.chains[chain] ~= nil,"chain not registered") temp = tgs.units.chains[ chain] key = temp.key tempIndex = {} for i,j in pairs( temp.unitsList ) do table.insert(tempIndex,j[ temp.key] ) end table.sort(tempIndex) for i = 1, #tempIndex, 10 do tempList = {} for j = 1,10 do if i+ j-1 <= #tempIndex then tempList[j] = temp.unitsList[ tempIndex[ i+j-1] ][key] end end print(unpack(tempList)) end end function tgs.units.dumpChains() local temp temp = {} for i,j in pairs(tgs.units.chains) do table.insert(temp,i) end table.sort(temp) print("Current Supported Chains") for i,j in ipairs( temp ) do print(j) end print("") end function tgs.units.listRequiredFields( chain ) local temp temp = {} assert( tgs.units.chains[chain] ~= nil,"chain not registered") for i,j in pairs( tgs.units.chains[chain].requiredFields ) do temp[i] = true end return temp end function tgs.units.listAllFields( chain ) local temp temp = {} assert( tgs.units.chains[chain] ~= nil,"chain not registered") for i, j in pairs( tgs.units.chains[chain].unitsList ) do for k,l in pairs( j ) do temp[k] = true end end return temp end function tgs.units.getUnitTable(chain) local temp, entry assert( tgs.units.chains[chain] ~= nil,"chain not registered") temp = tgs.units.chains[ chain].unitsList return temp end function tgs.units.getKey( chain ) assert( tgs.units.chains[chain] ~= nil,"chain not registered") return tgs.units.chains[ chain].key end function tgs.units.help() print("these functions maintain the units data base") print("tgs.units.verifyChain( chain ) -- verifies if chain is registered") print("tgs.units.verifyUnit( chain, unitId ) -- verify unitId is in chain") print("tgs.units.getUnit( chain , unitsId ) -- returns units entry ") print("tgs.units.getChain( chain) -- returns list of units id's ") print("tgs.units.addChain( chain, unitsCtl ) -- adds a units chain to the system") print("tgs.units.getKey( chain ) -- get key field of table") print("tgs.units.getUnitTable(chain) -- get unit table") print("tgs.units.getEntry( chain,unitId ) -- returns entry record ") print("tgs.units.dumpEntry( chain, unitId ) -- dumps entry in db ") print("tgs.units.dumpUnits( chain ) -- dumps the units in a chain") print("tgs.units.dumpChains() -- dumps registered chains ") print("tgs.units.listRequiredFields( chain ) -- returns table of required fields ") print("tgs.units.listAllFields( chain ) -- returns all fields in a store ") end
--!strict local Types = require(script.Parent.Types) local Symbols = require(script.Parent.Symbols) local Symbol_ElementKind = Symbols.ElementKind local Symbol_Portal = Symbols.ElementKinds.Portal local function portal(hostParent: Instance, children: Types.ChildrenArgument?): Types.Element local element = { [Symbol_ElementKind] = Symbol_Portal, hostParent = hostParent, children = children, } table.freeze(element) return element end return portal
local _ = require("src/underscore") local input local result describe("_.all", function() describe("provide a truth function", function() describe("all elements pass the function", function() it("should return true", function() input = {2, 4, 6} result = _.all(input, function(i) return i % 2 == 0 end) assert.same(result, true) end) end) describe("when all elements don't pass the function", function() it("should return false", function() input = {1, 2, 3} result = _.all(input, function(i) return i % 2 == 0 end) assert(not result) end) end) end) describe("when not providing a truth function", function() describe("when all elements are not false", function() it("should return true", function() input = {1, 2, true} result = _.all(input) assert(result) end) end) describe("when some elements are not true", function() it("should return false", function() input = {1, 2, 3, false} result = _.all(input) assert(not result) end) end) end) end)
-------------------------------------------------------------------------------- -- Easy Doorbell Clientside Init -------------------------------------------------------------------------------- include( "easydoorbell/sh_init.lua" ) include( "easydoorbell/cl_permmenu.lua" ) include( "easydoorbell/sh_tool_functions.lua" ) CreateClientConVar( "easydoorbell_placebutton_model", "models/easydoorbell/buttonbasic.mdl", false, true, "" ) CreateClientConVar( "easydoorbell_placebutton_cooldown", "0.0", false, true, "" ) CreateClientConVar( "easydoorbell_placebutton_speakerid", "0", false, true, "" ) CreateClientConVar( "easydoorbell_placespeaker_model", "models/easydoorbell/speakerbell.mdl", false, true, "" ) CreateClientConVar( "easydoorbell_placespeaker_sound", "easydoorbell/standard.wav", false, true, "" ) CreateClientConVar( "easydoorbell_placespeaker_volume", "1.0", false, true, "" ) -------------------------------------------------------------------------------- -- Recieve config values from server -------------------------------------------------------------------------------- net.Receive( "EasyDoorbellTransferConfig", function() EasyDoorbell.Config = net.ReadTable() end ) -------------------------------------------------------------------------------- -- Recieve a string with "l[index]" as placeholders for language strings. -- Replace these strings with the client's translations and add the string -- to the chatbox with the given color. -------------------------------------------------------------------------------- net.Receive( "EasyDoorbellFormattedMessage", function() local color = net.ReadColor() local message = net.ReadString() local replacements = net.ReadTable() for k, v in ipairs( replacements ) do local translated = language.GetPhrase( v ) message = string.gsub( message, "l" .. k, translated ) end chat.AddText( color, message ) end )
local area_mng = require"misc/area/area_mng" local ui_mng = class("ui_mng",area_mng){ __view_id = 1, } function ui_mng:__init() area_mng.__init(self) self:__init_callback__() end function ui_mng:__init_callback__() for _,call_name in ipairs(love_callback) do if not self[call_name] then self[call_name] = function(self,...) local area = self.area if area and area[call_name] then area[call_name](area,...) end end end end end function ui_mng:set_view(id) self.__view_id = id or 1 return self end function ui_mng:add_component(component) area_mng.add_area(self,component) component.__view_id = self.__view_id component:release("add_to_box",self) return self end function ui_mng:remove_component(component) component:release("remove_from_box",self) area_mng.remove_area(self,component) return self end function ui_mng:update(dt) local area = self.area if area then if area.update then area:update(dt) end if not area.locking then area_mng.update(self,dt) end else area_mng.update(self,dt) end end function ui_mng:draw() for ui in self.all_area:items() do if ui.draw then ui:draw() end end end return ui_mng
local g_MapInfo = false local function MiGetInfo(map) local info = DbQuerySingle('SELECT played, rates, rates_count FROM '..MapsTable..' WHERE map=? LIMIT 1', map:getId()) info.name = map:getName() info.rating = (info.rates_count > 0 and info.rates/info.rates_count) or 0 info.author = map:getInfo('author') local mapType = map:getType() info.type = mapType and mapType.name return info end function MiSendMapInfo(playerOrRoom) local room = playerOrRoom.cls == Player and playerOrRoom.room or playerOrRoom local prof = DbgPerf() local map = getCurrentMap(room) if(not map) then return end -- Prepare map info if(not g_MapInfo) then g_MapInfo = MiGetInfo(map) end -- Get Tops local topTimes if(g_MapInfo.type == 'DD' and DdGetTops) then topTimes = DdGetTops(map, 8) else topTimes = BtGetTops(map, 8) end -- Send Tops and map general info to all players RPC('MiSetMapInfo', g_MapInfo, topTimes):setClient(playerOrRoom.el):exec() -- Prepare list of IDs local players = getElementsByType('player', playerOrRoom.el) local idList = {} for i, player in ipairs(players) do local pdata = Player.fromEl(player) if(pdata and pdata.id) then table.insert(idList, pdata.id) end end -- Preload all needed information if(g_MapInfo.type == 'DD' and DdPreloadPersonalTops) then DdPreloadPersonalTops(map:getId(), idList, true) elseif(BtPreloadPersonalTops) then BtPreloadPersonalTops(map:getId(), idList, true) end RtPreloadPersonalMapRating(map:getId(), idList) for i, player in ipairs(players) do local pdata = Player.fromEl(player) local personalTop, personalRating -- Load personal Top if(not pdata) then personalTop = false elseif(g_MapInfo.type == 'DD' and DdGetPersonalTop) then personalTop = DdGetPersonalTop(map:getId(), pdata.id, true) elseif(BtGetPersonalTop) then personalTop = BtGetPersonalTop(map:getId(), pdata.id, true) end -- Make time readable if(personalTop and personalTop.time) then personalTop.time = formatTimePeriod(personalTop.time / 1000) end -- Get player rating for current map if(RtGetPersonalMapRating and pdata) then personalRating = RtGetPersonalMapRating(map:getId(), pdata.id) end -- Send personal Top and rating to owner if(pdata and pdata.sync) then RPC('MiSetPersonalInfo', personalTop, personalRating):setClient(player):exec() end end if(show) then RPC('MiShow'):setClient(players):exec() end prof:cp('MiSendMapInfo') end function MiShow(playerOrRoom) RPC('MiShow'):setClient(playerOrRoom.el):exec() end function MiUpdateInfo() g_MapInfo = false MiSendMapInfo(g_RootRoom) end function MiUpdateTops(map_id) MiSendMapInfo(g_RootRoom) end function MiDeleteCache() g_MapInfo = false end addInitFunc(function() addEventHandler('onGamemodeMapStop', g_Root, MiDeleteCache) end)
PlanStrollState = { mName = "plan_stroll" } PlanStrollState.__index = PlanStrollState function PlanStrollState:Create(character, map) local this = { mCharacter = character, mMap = map, mEntity = character.mEntity, mController = character.mController, mFrameResetSpeed = 0.05, mFrameCount = 0, mCountDown = math.random(0, 3) } setmetatable(this, self) return this end function PlanStrollState:Enter() end function PlanStrollState:Exit() end function PlanStrollState:Update(dt) self.mCountDown = self.mCountDown - dt if self.mCountDown <= 0 then -- Choose a random direction and try to move that way. local choice = math.random(4) if choice == 1 then self.mController:Change("move", {x = -1, y = 0}) elseif choice == 2 then self.mController:Change("move", {x = 1, y = 0}) elseif choice == 3 then self.mController:Change("move", {x = 0, y = -1}) elseif choice == 4 then self.mController:Change("move", {x = 0, y = 1}) end end -- If we're in the wait state for a few frames, reset the frame to -- the starting frame. if self.mFrameCount ~= -1 then self.mFrameCount = self.mFrameCount + dt if self.mFrameCount >= self.mFrameResetSpeed then self.mFrameCount = -1 self.mEntity:SetFrame(self.mEntity.mStartFrame) self.mCharacter.mFacing = "down" end end end function PlanStrollState:Render(renderer) end
object_mobile_endor_ig88_security_battledroid_red = object_mobile_shared_endor_ig88_security_battledroid_red:new { } ObjectTemplates:addTemplate(object_mobile_endor_ig88_security_battledroid_red, "object/mobile/endor_ig88_security_battledroid_red.iff")
local _t_ = '_T_' local _t_n_ = '_T_N_' local _t_t_c_ = '_T_[T]_C_' local _t_t_d_c_ = '_T_[T]_C_[C]_' local _t_t_d_c_pk_ = '_T_[T]_C_PK_' local level = redis.LOG_NOTICE local m = 'create redisql\'s scheme %s' local t = redis.call('hmset', _t_, 'TABLES', _t_n_, 'TABLES_COMMENT', 'The set hold tables name', 'CLOUMNS', _t_t_c_, 'COLUMNS_COMMENT', 'The set hold columns name, [T] will be replaced with Table name', 'COLUMN_DEFINE', _t_t_d_c_, 'COLUMN_DEFINE_COMMENT', 'The hash hold column definition, [C] will be replaced with Column name', 'PRIMARY_KEYS', _t_t_d_c_pk_, 'PRIMARY_KEYS_DEFINE_COMMENT', 'The set hold primary keys of table [T]') local v = {} if ('OK' == t['ok']) then v = {0, string.format(m, 'ok')} else v = {-1, string.format(m, 'failed')} end redis.log(level, v[#v]) return v
vlog_queue = {} function vendor_log_queue(name,line) if ( vlog_queue[name] == nil ) then vlog_queue[name] = {} end table.insert(vlog_queue[name],line) end function write_vendor_log(again) minetest.log("action","Writing vendor log queue to file") for name,log_lines in pairs(vlog_queue) do local logfile = minetest.get_worldpath().."/vendor_logs/"..name..".csv" local f = io.open(logfile, "a+") for _,line in pairs(log_lines) do local csv_line = line.date..",\""..line.pos.."\","..line.action..","..line.from..","..line.qty..","..line.desc..","..line.amount.."\r\n" f:write(csv_line) end f:close() end vlog_queue = {} if ( again == true ) then minetest.after(300,write_vendor_log,true) end end minetest.register_on_shutdown(write_vendor_log) minetest.after(300,write_vendor_log,true)